From 5d6ab2699cfda84a77134475930652e1fc649d33 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 16 Jun 2021 11:48:59 +0100 Subject: [PATCH 001/251] First Performance pass Signed-off-by: igarri --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 3 +- .../AssetBrowser/AssetBrowserModel.cpp | 3 +- .../AssetBrowser/AssetBrowserTableModel.cpp | 58 ++++++++++++++----- .../AssetBrowser/AssetBrowserTableModel.h | 2 + .../Views/AssetBrowserTableView.cpp | 18 +++--- .../Views/AssetBrowserTableView.h | 2 - .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 2 + .../Editor/EditorPreferencesPageFiles.cpp | 21 ++++++- .../Editor/EditorPreferencesPageFiles.h | 7 +++ Code/Sandbox/Editor/Settings.cpp | 2 + Code/Sandbox/Editor/Settings.h | 7 +++ 11 files changed, 97 insertions(+), 28 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 9bbdbc8442..3191c9ee8f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -185,6 +185,7 @@ namespace AzToolsFramework } } invalidateFilter(); + Q_EMIT filterChanged(); } @@ -204,6 +205,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 069ac6de84..5d215f1b97 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp @@ -133,7 +133,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 e03b1116c3..dcd8bb1cf6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -14,6 +14,7 @@ namespace AzToolsFramework { AssetBrowserTableModel::AssetBrowserTableModel(QObject* parent /* = nullptr */) : QSortFilterProxyModel(parent) + , m_numberOfItemsDisplayed(200) { setDynamicSortFilter(false); } @@ -88,25 +89,40 @@ namespace AzToolsFramework int AssetBrowserTableModel::BuildTableModelMap( const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) { + static int cont = 0; int rows = model ? model->rowCount(parent) : 0; + + if (parent == QModelIndex()) + { + cont = 0; + } + for (int i = 0; i < rows; ++i) { - 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) + if (cont < m_numberOfItemsDisplayed) { - beginInsertRows(parent, row, row); - m_indexMap[row] = index; - endInsertRows(); - - Q_EMIT dataChanged(index, index); - ++row; + 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(); + + Q_EMIT dataChanged(index, index); + ++row; + ++cont; + } + + if (model->hasChildren(index) && cont < 10) + { + row = BuildTableModelMap(model, index, row); + } } - - if (model->hasChildren(index)) + else { - row = BuildTableModelMap(model, index, row); + break; } } return row; @@ -134,6 +150,22 @@ namespace AzToolsFramework m_indexMap.clear(); endRemoveRows(); } + + AzToolsFramework::EditorSettingsAPIRequests::SettingOutcome outcome; + AzToolsFramework::EditorSettingsAPIBus::BroadcastResult(outcome, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetValue, + "Settings|MaxDisplayedItemsNumInSearch"); + //AzToolsFramework::EditorSettingsAPIBus::BroadcastResult( + // outcome, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetValue, + // "Settings\ExperimentalFeatures|TotalIlluminationEnabled"); + + AZStd::any* outcomeValue = &outcome.GetValue(); + //bool trr = false; + if (outcomeValue->is() == true) + { + m_numberOfItemsDisplayed = AZStd::any_cast(*outcomeValue); + //trr = AZStd::any_cast(outcomeValue); + } + BuildTableModelMap(sourceModel()); emit layoutChanged(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 3ce6543f6f..5395512dae 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -11,6 +11,7 @@ #include #include #endif +#include namespace AzToolsFramework { @@ -49,6 +50,7 @@ namespace AzToolsFramework int BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); private: + int m_numberOfItemsDisplayed; 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 20e3d307ea..924d73433d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -5,18 +5,18 @@ * */ -#include +//#include -#include +//#include -#include +//#include #include #include #include -#include -#include -#include +//#include +//#include +//#include #include #include @@ -27,9 +27,9 @@ AZ_PUSH_DISABLE_WARNING( #include #include #include -#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 7e1c8c9ab4..4df87e6e3f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -8,7 +8,6 @@ #if !defined(Q_MOC_RUN) #include #include -#include #include #include @@ -54,7 +53,6 @@ namespace AzToolsFramework void OnAssetBrowserComponentReady() override; ////////////////////////////////////////////////////////////////////////// - Q_SIGNALS: void selectionChangedSignal(const QItemSelection& selected, const QItemSelection& deselected); void ClearStringFilter(); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 2a5f853e9b..52721a6162 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -78,6 +78,8 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_viewSwitcherCheckBox->setVisible(false); m_ui->m_assetBrowserTableViewWidget->setVisible(false); + m_ui->m_searchWidget->SetFilterInputInterval(AZStd::chrono::milliseconds(350)); + if (ed_useNewAssetBrowserTableView) { m_ui->m_viewSwitcherCheckBox->setVisible(true); diff --git a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp index c09c3441df..cba3888bd1 100644 --- a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp +++ b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp @@ -42,11 +42,17 @@ 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_numOfItemsShown); + 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("Asset Browser Search", &CEditorPreferencesPage_Files::m_assetBrowserSearch); AZ::EditContext* editContext = serialize.GetEditContext(); @@ -79,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_numOfItemsShown, "Maximum number of displayed items", + "Maximum number of displayed items displayed in the Search View") + ->Attribute(AZ::Edit::Attributes::Min, 200) + ->Attribute(AZ::Edit::Attributes::Max, 1000); + 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"); } } @@ -123,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.numberOfItemsShownInSearch = m_assetBrowserSearch.m_numOfItemsShown; } void CEditorPreferencesPage_Files::InitializeSettings() @@ -147,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_numOfItemsShown = gSettings.numberOfItemsShownInSearch; } diff --git a/Code/Sandbox/Editor/EditorPreferencesPageFiles.h b/Code/Sandbox/Editor/EditorPreferencesPageFiles.h index 44bcb3ba8d..2e27cd3c3e 100644 --- a/Code/Sandbox/Editor/EditorPreferencesPageFiles.h +++ b/Code/Sandbox/Editor/EditorPreferencesPageFiles.h @@ -68,10 +68,17 @@ private: int m_remindTime; }; + struct AssetBrowserSearch + { + AZ_TYPE_INFO(AssetBrowserSearch, "{9FBFCD24-9452-49DF-99F4-2711443CEAAE}") + + int m_numOfItemsShown; + }; Files m_files; ExternalEditors m_editors; AutoBackup m_autoBackup; + AssetBrowserSearch m_assetBrowserSearch; QIcon m_icon; }; diff --git a/Code/Sandbox/Editor/Settings.cpp b/Code/Sandbox/Editor/Settings.cpp index bf699c842c..c1929119fb 100644 --- a/Code/Sandbox/Editor/Settings.cpp +++ b/Code/Sandbox/Editor/Settings.cpp @@ -498,6 +498,7 @@ void SEditorSettings::Save() SaveValue("Settings", "AutoBackupTime", autoBackupTime); SaveValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); SaveValue("Settings", "AutoRemindTime", autoRemindTime); + SaveValue("Settings", "MaxDisplayedItemsNumInSearch", numberOfItemsShownInSearch); SaveValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); SaveValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); SaveValue("Settings", "StylusMode", stylusMode); @@ -710,6 +711,7 @@ void SEditorSettings::Load() LoadValue("Settings", "AutoBackupTime", autoBackupTime); LoadValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); LoadValue("Settings", "AutoRemindTime", autoRemindTime); + LoadValue("Settings", "MaxDisplayedItemsNumInSearch", numberOfItemsShownInSearch); LoadValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); LoadValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); LoadValue("Settings", "StylusMode", stylusMode); diff --git a/Code/Sandbox/Editor/Settings.h b/Code/Sandbox/Editor/Settings.h index 7618a11485..9591695248 100644 --- a/Code/Sandbox/Editor/Settings.h +++ b/Code/Sandbox/Editor/Settings.h @@ -377,6 +377,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 numberOfItemsShownInSearch; + ////////////////////////////////////////////////////////////////////////// + //! If true preview windows is displayed when browsing geometries. bool bPreviewGeometryWindow; From c061802ab0ed017c566b042f675557c959b0151d Mon Sep 17 00:00:00 2001 From: igarri Date: Mon, 21 Jun 2021 13:18:51 +0100 Subject: [PATCH 002/251] Retrieving data from preferences Signed-off-by: igarri --- .../AssetBrowser/AssetBrowserTableModel.cpp | 23 ++++++++++--------- .../Editor/EditorSettingsAPIBus.h | 1 + .../AzAssetBrowser/AzAssetBrowserWindow.cpp | 2 +- .../Editor/EditorPreferencesPageFiles.cpp | 2 +- Code/Sandbox/Editor/Settings.cpp | 5 ++++ Code/Sandbox/Editor/Settings.h | 1 + 6 files changed, 21 insertions(+), 13 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index dcd8bb1cf6..d76ee9b515 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -8,6 +8,8 @@ #include #include +#pragma optimize("", off) + namespace AzToolsFramework { namespace AssetBrowser @@ -151,24 +153,23 @@ namespace AzToolsFramework endRemoveRows(); } - AzToolsFramework::EditorSettingsAPIRequests::SettingOutcome outcome; - AzToolsFramework::EditorSettingsAPIBus::BroadcastResult(outcome, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetValue, - "Settings|MaxDisplayedItemsNumInSearch"); - //AzToolsFramework::EditorSettingsAPIBus::BroadcastResult( - // outcome, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetValue, - // "Settings\ExperimentalFeatures|TotalIlluminationEnabled"); + AzToolsFramework::EditorSettingsAPIRequests::SettingOutcome outcome; + AzToolsFramework::EditorSettingsAPIBus::BroadcastResult(outcome, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetValue, + "Settings|MaxDisplayedItemsNumInSearch"); - AZStd::any* outcomeValue = &outcome.GetValue(); - //bool trr = false; - if (outcomeValue->is() == true) + AZStd::any outcomeValue = outcome.GetValue(); + if (outcomeValue.is() == true) { - m_numberOfItemsDisplayed = AZStd::any_cast(*outcomeValue); - //trr = AZStd::any_cast(outcomeValue); + m_numberOfItemsDisplayed = AZStd::any_cast(outcome.GetValue()); } + AzToolsFramework::EditorSettingsAPIBus::BroadcastResult( + m_numberOfItemsDisplayed, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetMaxNumberOfItemsShownInSearchView); + BuildTableModelMap(sourceModel()); emit layoutChanged(); } } // namespace AssetBrowser } // namespace AzToolsFramework #include "AssetBrowser/moc_AssetBrowserTableModel.cpp" +#pragma optimize("", on) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h index 4f037b870a..ce45577335 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h @@ -37,6 +37,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/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 52721a6162..f16f0e362b 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -78,7 +78,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_viewSwitcherCheckBox->setVisible(false); m_ui->m_assetBrowserTableViewWidget->setVisible(false); - m_ui->m_searchWidget->SetFilterInputInterval(AZStd::chrono::milliseconds(350)); + m_ui->m_searchWidget->SetFilterInputInterval(AZStd::chrono::milliseconds(250)); if (ed_useNewAssetBrowserTableView) { diff --git a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp index cba3888bd1..7833ccdf88 100644 --- a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp +++ b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp @@ -88,7 +88,7 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) editContext->Class("Asset Browser Search View", "Asset Browser Search View") ->DataElement(AZ::Edit::UIHandlers::SpinBox, &AssetBrowserSearch::m_numOfItemsShown, "Maximum number of displayed items", "Maximum number of displayed items displayed in the Search View") - ->Attribute(AZ::Edit::Attributes::Min, 200) + ->Attribute(AZ::Edit::Attributes::Min, 10) ->Attribute(AZ::Edit::Attributes::Max, 1000); editContext->Class("File Preferences", "Class for handling File Preferences") diff --git a/Code/Sandbox/Editor/Settings.cpp b/Code/Sandbox/Editor/Settings.cpp index c1929119fb..398ad5f5cb 100644 --- a/Code/Sandbox/Editor/Settings.cpp +++ b/Code/Sandbox/Editor/Settings.cpp @@ -1205,3 +1205,8 @@ AzToolsFramework::ConsoleColorTheme SEditorSettings::GetConsoleColorTheme() cons { return consoleBackgroundColorTheme; } + +int SEditorSettings::GetMaxNumberOfItemsShownInSearchView() const +{ + return SEditorSettings::numberOfItemsShownInSearch; +} diff --git a/Code/Sandbox/Editor/Settings.h b/Code/Sandbox/Editor/Settings.h index 9591695248..ee6aa24ca5 100644 --- a/Code/Sandbox/Editor/Settings.h +++ b/Code/Sandbox/Editor/Settings.h @@ -302,6 +302,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); From 514f9ef6c2b373d5c5c821d641cc87f69ba8715f Mon Sep 17 00:00:00 2001 From: igarri Date: Fri, 25 Jun 2021 10:37:39 +0100 Subject: [PATCH 003/251] Adjusted parameters Signed-off-by: igarri --- .../AssetBrowser/AssetBrowserTableModel.cpp | 10 ---------- .../Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp | 2 +- Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp | 2 +- 3 files changed, 2 insertions(+), 12 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index d76ee9b515..0a2a1954f4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -153,16 +153,6 @@ namespace AzToolsFramework endRemoveRows(); } - AzToolsFramework::EditorSettingsAPIRequests::SettingOutcome outcome; - AzToolsFramework::EditorSettingsAPIBus::BroadcastResult(outcome, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetValue, - "Settings|MaxDisplayedItemsNumInSearch"); - - AZStd::any outcomeValue = outcome.GetValue(); - if (outcomeValue.is() == true) - { - m_numberOfItemsDisplayed = AZStd::any_cast(outcome.GetValue()); - } - AzToolsFramework::EditorSettingsAPIBus::BroadcastResult( m_numberOfItemsDisplayed, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetMaxNumberOfItemsShownInSearchView); diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index f16f0e362b..c131f62fc6 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -82,7 +82,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) if (ed_useNewAssetBrowserTableView) { - m_ui->m_viewSwitcherCheckBox->setVisible(true); + m_ui->m_viewSwitcherCheckBox->setVisible(false); m_tableModel->setFilterRole(Qt::DisplayRole); m_tableModel->setSourceModel(m_filterModel.data()); m_ui->m_assetBrowserTableViewWidget->setModel(m_tableModel.data()); diff --git a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp index 7833ccdf88..d4e7378d2b 100644 --- a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp +++ b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp @@ -88,7 +88,7 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) editContext->Class("Asset Browser Search View", "Asset Browser Search View") ->DataElement(AZ::Edit::UIHandlers::SpinBox, &AssetBrowserSearch::m_numOfItemsShown, "Maximum number of displayed items", "Maximum number of displayed items displayed in the Search View") - ->Attribute(AZ::Edit::Attributes::Min, 10) + ->Attribute(AZ::Edit::Attributes::Min, 100) ->Attribute(AZ::Edit::Attributes::Max, 1000); editContext->Class("File Preferences", "Class for handling File Preferences") From a07445c2da041624c0d54adc09b62497bf63c4ec Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 30 Jun 2021 13:45:34 +0100 Subject: [PATCH 004/251] Cleanup and removed optimize Signed-off-by: igarri --- .../AssetBrowser/AssetBrowserTableModel.cpp | 3 --- .../AssetBrowser/Views/AssetBrowserTableView.cpp | 12 +----------- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 0a2a1954f4..1c4f141f38 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -8,8 +8,6 @@ #include #include -#pragma optimize("", off) - namespace AzToolsFramework { namespace AssetBrowser @@ -162,4 +160,3 @@ namespace AzToolsFramework } // namespace AssetBrowser } // namespace AzToolsFramework #include "AssetBrowser/moc_AssetBrowserTableModel.cpp" -#pragma optimize("", on) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index 924d73433d..2840523683 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -5,18 +5,10 @@ * */ -//#include - -//#include - -//#include #include #include #include -//#include -//#include -//#include #include #include @@ -27,9 +19,7 @@ AZ_PUSH_DISABLE_WARNING( #include #include #include -//#include -//#include -//#include + #include AZ_POP_DISABLE_WARNING namespace AzToolsFramework From b0ddd938245e406081f341cc635a40481a5a429d Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 30 Jun 2021 15:16:23 +0100 Subject: [PATCH 005/251] Code cleanup and review changes Signed-off-by: igarri --- .../AssetBrowser/AssetBrowserTableModel.cpp | 13 +++++-------- .../Sandbox/Editor/EditorPreferencesPageFiles.cpp | 15 +++++++-------- Code/Sandbox/Editor/EditorPreferencesPageFiles.h | 2 +- Code/Sandbox/Editor/Settings.cpp | 6 +++--- Code/Sandbox/Editor/Settings.h | 2 +- 5 files changed, 17 insertions(+), 21 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 1c4f141f38..2cf5b13c91 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -89,17 +89,17 @@ namespace AzToolsFramework int AssetBrowserTableModel::BuildTableModelMap( const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) { - static int cont = 0; + static int displayedItemsCounter = 0; int rows = model ? model->rowCount(parent) : 0; if (parent == QModelIndex()) { - cont = 0; + displayedItemsCounter = 0; } for (int i = 0; i < rows; ++i) { - if (cont < m_numberOfItemsDisplayed) + if (displayedItemsCounter < m_numberOfItemsDisplayed) { QModelIndex index = model->index(i, 0, parent); AssetBrowserEntry* entry = GetAssetEntry(m_filterModel->mapToSource(index)); @@ -112,18 +112,15 @@ namespace AzToolsFramework Q_EMIT dataChanged(index, index); ++row; - ++cont; + ++displayedItemsCounter; } - if (model->hasChildren(index) && cont < 10) + if (model->hasChildren(index)) { row = BuildTableModelMap(model, index, row); } } - else - { break; - } } return row; } diff --git a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp index d4e7378d2b..f6333b9a76 100644 --- a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp +++ b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp @@ -42,10 +42,9 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->Field("MaxCount", &AutoBackup::m_maxCount) ->Field("RemindTime", &AutoBackup::m_remindTime); - serialize - .Class() + serialize.Class() ->Version(1) - ->Field("Max number of items displayed", &AssetBrowserSearch::m_numOfItemsShown); + ->Field("Max number of items displayed", &AssetBrowserSearch::m_maxNumberOfItemsShownInSearch); serialize.Class() ->Version(1) @@ -86,10 +85,10 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->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_numOfItemsShown, "Maximum number of displayed items", + ->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, 100) - ->Attribute(AZ::Edit::Attributes::Max, 1000); + ->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, "") @@ -137,7 +136,7 @@ void CEditorPreferencesPage_Files::OnApply() gSettings.autoBackupMaxCount = m_autoBackup.m_maxCount; gSettings.autoRemindTime = m_autoBackup.m_remindTime; - gSettings.numberOfItemsShownInSearch = m_assetBrowserSearch.m_numOfItemsShown; + gSettings.maxNumberOfItemsShownInSearch = m_assetBrowserSearch.m_maxNumberOfItemsShownInSearch; } void CEditorPreferencesPage_Files::InitializeSettings() @@ -163,5 +162,5 @@ void CEditorPreferencesPage_Files::InitializeSettings() m_autoBackup.m_maxCount = gSettings.autoBackupMaxCount; m_autoBackup.m_remindTime = gSettings.autoRemindTime; - m_assetBrowserSearch.m_numOfItemsShown = gSettings.numberOfItemsShownInSearch; + m_assetBrowserSearch.m_maxNumberOfItemsShownInSearch = gSettings.maxNumberOfItemsShownInSearch; } diff --git a/Code/Sandbox/Editor/EditorPreferencesPageFiles.h b/Code/Sandbox/Editor/EditorPreferencesPageFiles.h index 2e27cd3c3e..40e9577f7f 100644 --- a/Code/Sandbox/Editor/EditorPreferencesPageFiles.h +++ b/Code/Sandbox/Editor/EditorPreferencesPageFiles.h @@ -72,7 +72,7 @@ private: { AZ_TYPE_INFO(AssetBrowserSearch, "{9FBFCD24-9452-49DF-99F4-2711443CEAAE}") - int m_numOfItemsShown; + int m_maxNumberOfItemsShownInSearch; }; Files m_files; diff --git a/Code/Sandbox/Editor/Settings.cpp b/Code/Sandbox/Editor/Settings.cpp index 398ad5f5cb..d49a1d40d1 100644 --- a/Code/Sandbox/Editor/Settings.cpp +++ b/Code/Sandbox/Editor/Settings.cpp @@ -498,7 +498,7 @@ void SEditorSettings::Save() SaveValue("Settings", "AutoBackupTime", autoBackupTime); SaveValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); SaveValue("Settings", "AutoRemindTime", autoRemindTime); - SaveValue("Settings", "MaxDisplayedItemsNumInSearch", numberOfItemsShownInSearch); + SaveValue("Settings", "MaxDisplayedItemsNumInSearch", maxNumberOfItemsShownInSearch); SaveValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); SaveValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); SaveValue("Settings", "StylusMode", stylusMode); @@ -711,7 +711,7 @@ void SEditorSettings::Load() LoadValue("Settings", "AutoBackupTime", autoBackupTime); LoadValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); LoadValue("Settings", "AutoRemindTime", autoRemindTime); - LoadValue("Settings", "MaxDisplayedItemsNumInSearch", numberOfItemsShownInSearch); + LoadValue("Settings", "MaxDisplayedItemsNumInSearch", maxNumberOfItemsShownInSearch); LoadValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); LoadValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); LoadValue("Settings", "StylusMode", stylusMode); @@ -1208,5 +1208,5 @@ AzToolsFramework::ConsoleColorTheme SEditorSettings::GetConsoleColorTheme() cons int SEditorSettings::GetMaxNumberOfItemsShownInSearchView() const { - return SEditorSettings::numberOfItemsShownInSearch; + return SEditorSettings::maxNumberOfItemsShownInSearch; } diff --git a/Code/Sandbox/Editor/Settings.h b/Code/Sandbox/Editor/Settings.h index ee6aa24ca5..802809ac11 100644 --- a/Code/Sandbox/Editor/Settings.h +++ b/Code/Sandbox/Editor/Settings.h @@ -382,7 +382,7 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING // Asset Browser Search View. ////////////////////////////////////////////////////////////////////////// //! Current maximum number of items that can be displayed in the AssetBrowser Search View. - int numberOfItemsShownInSearch; + int maxNumberOfItemsShownInSearch; ////////////////////////////////////////////////////////////////////////// From 4251e2600a5defd438edde84ab0e9b087bda8c11 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 30 Jun 2021 15:18:29 +0100 Subject: [PATCH 006/251] Fixing Asset Browser Search name Signed-off-by: igarri --- Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp index f6333b9a76..81f5e52828 100644 --- a/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp +++ b/Code/Sandbox/Editor/EditorPreferencesPageFiles.cpp @@ -51,7 +51,7 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->Field("Files", &CEditorPreferencesPage_Files::m_files) ->Field("Editors", &CEditorPreferencesPage_Files::m_editors) ->Field("AutoBackup", &CEditorPreferencesPage_Files::m_autoBackup) - ->Field("Asset Browser Search", &CEditorPreferencesPage_Files::m_assetBrowserSearch); + ->Field("AssetBrowserSearch", &CEditorPreferencesPage_Files::m_assetBrowserSearch); AZ::EditContext* editContext = serialize.GetEditContext(); From e9f44863a47b8eaaf26a8e745eeecfe10971fe72 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 30 Jun 2021 15:21:34 +0100 Subject: [PATCH 007/251] Fixed BuildMap method Signed-off-by: igarri --- .../AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 2cf5b13c91..9874c5571f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -120,7 +120,10 @@ namespace AzToolsFramework row = BuildTableModelMap(model, index, row); } } + else + { break; + } } return row; } From 8b016f86a63df1b92f86848b0fe5a5284e0ea5c7 Mon Sep 17 00:00:00 2001 From: igarri Date: Fri, 2 Jul 2021 13:38:35 +0100 Subject: [PATCH 008/251] Adressing Code review comments Signed-off-by: igarri --- .../AssetBrowser/AssetBrowserTableModel.cpp | 14 ++++++-------- .../AssetBrowser/AssetBrowserTableModel.h | 3 ++- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 9874c5571f..0da7007e01 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -14,7 +14,6 @@ namespace AzToolsFramework { AssetBrowserTableModel::AssetBrowserTableModel(QObject* parent /* = nullptr */) : QSortFilterProxyModel(parent) - , m_numberOfItemsDisplayed(200) { setDynamicSortFilter(false); } @@ -89,21 +88,20 @@ namespace AzToolsFramework int AssetBrowserTableModel::BuildTableModelMap( const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) { - static int displayedItemsCounter = 0; int rows = model ? model->rowCount(parent) : 0; if (parent == QModelIndex()) { - displayedItemsCounter = 0; + m_displayedItemsCounter = 0; } - for (int i = 0; i < rows; ++i) + for (int currentRow = 0; currentRow < rows; ++currentRow) { - if (displayedItemsCounter < m_numberOfItemsDisplayed) + if (m_displayedItemsCounter < m_numberOfItemsDisplayed) { - QModelIndex index = model->index(i, 0, parent); + QModelIndex index = model->index(currentRow, 0, parent); AssetBrowserEntry* entry = GetAssetEntry(m_filterModel->mapToSource(index)); - // We only wanna see the source assets. + // We only want to see the source assets. if (entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Source) { beginInsertRows(parent, row, row); @@ -112,7 +110,7 @@ namespace AzToolsFramework Q_EMIT dataChanged(index, index); ++row; - ++displayedItemsCounter; + ++m_displayedItemsCounter; } if (model->hasChildren(index)) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 5395512dae..b2131c2ae3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -50,7 +50,8 @@ namespace AzToolsFramework int BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); private: - int m_numberOfItemsDisplayed; + int m_numberOfItemsDisplayed = 0; + int m_displayedItemsCounter = 0; QPointer m_filterModel; QMap m_indexMap; }; From 26d9a3b5b3dd9025499dccbf4620f8974c58e33e Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 7 Jul 2021 13:54:18 +0100 Subject: [PATCH 009/251] Fixed tabs Signed-off-by: igarri --- Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index 6bd0c00150..c0e08f86b1 100644 --- a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -81,7 +81,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)); + m_ui->m_searchWidget->SetFilterInputInterval(AZStd::chrono::milliseconds(250)); if (ed_useNewAssetBrowserTableView) { m_ui->m_toggleDisplayViewBtn->setVisible(true); From ae60bd0167483bad342bcaae9fa2638ee5df91d9 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Fri, 16 Jul 2021 14:33:39 -0700 Subject: [PATCH 010/251] [installer/2106-font] revert back to default install bootstrapper font Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- .../Windows/Packaging/BootstrapperTheme.xml.in | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in b/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in index 8d8416539e..c670ef3d9a 100644 --- a/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in +++ b/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in @@ -4,15 +4,15 @@ #(loc.WindowTitle) - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI From 679ecf480197d234cc86fd123c5535a33c25d474 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 16 Jul 2021 17:40:27 -0500 Subject: [PATCH 011/251] External Gem and Projects now appear in Editor AssetBrowser (#2227) * External Gem and Projects now appear in Editor AssetBrowser Optimized logic populating the FolderAssetBrowserEntries in the Editor AssetBrowser. Added an "[External]" tag to scan folders which reside outside of the Engine Root Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Fixed conversion of fixed_string to string when normalizing an added AssetBrowser file path. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * RootAssetBrowserEntry.cpp Linux conditional expression fix Because an AZ::IO::PathView is convertible to an AZ::IO::FixedMaxPath and vice-versa, the conversion of the second part of the ternary expression absolutePathView needs to explicitly convert to an AZ::IO::FixedMaxPath Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- .../Entries/AssetBrowserEntry.cpp | 4 +- .../AssetBrowser/Entries/AssetBrowserEntry.h | 5 +- .../Entries/FolderAssetBrowserEntry.cpp | 4 +- .../Entries/RootAssetBrowserEntry.cpp | 193 ++++++++---------- .../Entries/RootAssetBrowserEntry.h | 12 +- .../Entries/SourceAssetBrowserEntry.cpp | 4 +- 6 files changed, 101 insertions(+), 121 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp index 17a20a9d19..7eae7621d2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp @@ -206,12 +206,12 @@ namespace AzToolsFramework const AZStd::string& AssetBrowserEntry::GetRelativePath() const { - return m_relativePath; + return m_relativePath.Native(); } const AZStd::string& AssetBrowserEntry::GetFullPath() const { - return m_fullPath; + return m_fullPath.Native(); } const AssetBrowserEntry* AssetBrowserEntry::GetChild(int index) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h index e4a7b6b4cb..24f037a623 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h @@ -9,6 +9,7 @@ #if !defined(Q_MOC_RUN) #include #include +#include #include #include @@ -130,8 +131,8 @@ namespace AzToolsFramework protected: AZStd::string m_name; QString m_displayName; - AZStd::string m_relativePath; - AZStd::string m_fullPath; + AZ::IO::Path m_relativePath; + AZ::IO::Path m_fullPath; AZStd::vector m_children; AssetBrowserEntry* m_parentAssetEntry = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp index 3c5afab0d0..febd406f23 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp @@ -37,8 +37,8 @@ namespace AzToolsFramework void FolderAssetBrowserEntry::UpdateChildPaths(AssetBrowserEntry* child) const { - child->m_relativePath = m_relativePath + AZ_CORRECT_DATABASE_SEPARATOR + child->m_name; - child->m_fullPath = m_fullPath + AZ_CORRECT_DATABASE_SEPARATOR + child->m_name; + child->m_relativePath = m_relativePath / child->m_name; + child->m_fullPath = m_fullPath / child->m_name; AssetBrowserEntry::UpdateChildPaths(child); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp index 090ad0d6ca..0e132d2581 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -24,8 +25,6 @@ namespace AzToolsFramework { namespace AssetBrowser { - const char* GEMS_FOLDER_NAME = "Gems"; - RootAssetBrowserEntry::RootAssetBrowserEntry() : AssetBrowserEntry() { @@ -53,13 +52,7 @@ namespace AzToolsFramework EntryCache::GetInstance()->Clear(); m_enginePath = enginePath; - - // there is no "Gems" scan folder registered in db, create one manually - auto gemFolder = aznew FolderAssetBrowserEntry(); - gemFolder->m_name = m_enginePath + AZ_CORRECT_DATABASE_SEPARATOR + GEMS_FOLDER_NAME; - gemFolder->m_displayName = GEMS_FOLDER_NAME; - gemFolder->m_isGemsFolder = true; - AddChild(gemFolder); + m_fullPath = enginePath; } bool RootAssetBrowserEntry::IsInitialUpdate() const @@ -80,8 +73,17 @@ namespace AzToolsFramework if (AZ::IO::FileIOBase::GetInstance()->IsDirectory(scanFolderDatabaseEntry.m_scanFolder.c_str())) { - const auto scanFolder = CreateFolders(scanFolderDatabaseEntry.m_scanFolder.c_str(), this); - scanFolder->m_displayName = QString::fromUtf8(scanFolderDatabaseEntry.m_displayName.c_str()); + const auto scanFolder = CreateFolders(scanFolderDatabaseEntry.m_scanFolder, this); + // Append an "[External]" to the display if the Scan Folder is NOT relative to the Engine Root path + if (!AZ::IO::PathView(scanFolderDatabaseEntry.m_scanFolder).IsRelativeTo(m_enginePath)) + { + scanFolder->m_displayName += " [External]"; + } + else + { + scanFolder->m_displayName = QString::fromUtf8(scanFolderDatabaseEntry.m_displayName.c_str()); + } + EntryCache::GetInstance()->m_scanFolderIdMap[scanFolderDatabaseEntry.m_scanFolderID] = scanFolder; } } @@ -121,38 +123,34 @@ namespace AzToolsFramework return; } - const char* filePath = fileDatabaseEntry.m_fileName.c_str(); + AZ::IO::FixedMaxPath absoluteFilePath = AZ::IO::FixedMaxPath(AZStd::string_view{ scanFolder->GetFullPath() }) + / fileDatabaseEntry.m_fileName.c_str(); AssetBrowserEntry* file; // file can be either folder or actual file if (fileDatabaseEntry.m_isFolder) { - file = CreateFolders(filePath, scanFolder); + file = CreateFolders(absoluteFilePath.Native(), scanFolder); } else { - AZStd::string sourcePath; - AZStd::string sourceName; - AZStd::string sourceExtension; - StringFunc::Path::Split(filePath, nullptr, &sourcePath, &sourceName, &sourceExtension); // if missing create folders leading to file's location and get immediate parent // (we don't need to have fileIds for any folders created yet, they will be added later) - auto parent = CreateFolders(sourcePath.c_str(), scanFolder); + auto parent = CreateFolders(absoluteFilePath.ParentPath().Native(), scanFolder); // for simplicity in AB, files are represented as sources, but they are missing SourceDatabaseEntry-specific information such as SourceUuid auto source = aznew SourceAssetBrowserEntry(); - source->m_name = (sourceName + sourceExtension).c_str(); + source->m_name = absoluteFilePath.Filename().Native(); source->m_fileId = fileDatabaseEntry.m_fileID; source->m_displayName = QString::fromUtf8(source->m_name.c_str()); source->m_scanFolderId = fileDatabaseEntry.m_scanFolderPK; - source->m_extension = sourceExtension.c_str(); + source->m_extension = absoluteFilePath.Extension().Native(); parent->AddChild(source); file = source; } EntryCache::GetInstance()->m_fileIdMap[fileDatabaseEntry.m_fileID] = file; - AZStd::string fullPath = file->m_fullPath; - AzFramework::StringFunc::Path::Normalize(fullPath); - EntryCache::GetInstance()->m_absolutePathToFileId[fullPath] = fileDatabaseEntry.m_fileID; + AZStd::string filePath = AZ::IO::PathView(file->m_fullPath).LexicallyNormal().String(); + EntryCache::GetInstance()->m_absolutePathToFileId[filePath] = fileDatabaseEntry.m_fileID; } bool RootAssetBrowserEntry::RemoveFile(const AZ::s64& fileId) const @@ -305,116 +303,95 @@ namespace AzToolsFramework } } - FolderAssetBrowserEntry* RootAssetBrowserEntry::CreateFolder(const char* folderName, AssetBrowserEntry* parent) + AssetBrowserEntry* RootAssetBrowserEntry::GetNearestAncestor(AZ::IO::PathView absolutePathView, AssetBrowserEntry* parent, + AZStd::unordered_set& visitedSet) { - auto it = AZStd::find_if(parent->m_children.begin(), parent->m_children.end(), [folderName](AssetBrowserEntry* entry) - { - if (!azrtti_istypeof(entry)) - { - return false; - } - return AzFramework::StringFunc::Equal(entry->m_name.c_str(), folderName); - }); - if (it != parent->m_children.end()) + auto IsPathRelativeToEntry = [absolutePathView](AssetBrowserEntry* assetBrowserEntry) { - return azrtti_cast(*it); + auto& childPath = assetBrowserEntry->m_fullPath; + return absolutePathView.IsRelativeTo(AZ::IO::PathView(childPath)); + }; + + if (visitedSet.contains(parent)) + { + return {}; } - const auto folder = aznew FolderAssetBrowserEntry(); - folder->m_name = folderName; - folder->m_displayName = folderName; - parent->AddChild(folder); - return folder; - } - AssetBrowserEntry* RootAssetBrowserEntry::CreateFolders(const char* relativePath, AssetBrowserEntry* parent) - { - auto children(parent->m_children); - int n = 0; + visitedSet.insert(parent); - // check if folder with the same name already exists - // step through every character in relativePath and compare to each child's relative path of suggested parent - // if a character @n in child's rel path mismatches character at n in relativePath, remove that child from further search - while (!children.empty() && relativePath[n]) + AssetBrowserEntry* nearestAncestor{}; + for (AssetBrowserEntry* childBrowserEntry : parent->m_children) { - AZStd::vector toRemove; - for (auto child : children) + if (IsPathRelativeToEntry(childBrowserEntry)) { - auto& childPath = azrtti_istypeof(parent) ? child->m_fullPath : child->m_relativePath; - - // child's path mismatched, remove it from search candidates - if (childPath.length() == n || childPath[n] != relativePath[n]) + // Walk the AssetBrowserEntry Tree looking for a nearer ancestor to the absolute path + // If one is not found in the recursive call to GetNearestAncestor, then the childBrowserEntry + // is the current best candidate + AssetBrowserEntry* candidateAncestor = GetNearestAncestor(absolutePathView, childBrowserEntry, visitedSet); + candidateAncestor = candidateAncestor != nullptr ? candidateAncestor : childBrowserEntry; + AZ::IO::PathView candidatePathView(candidateAncestor->m_fullPath); + // If the candidate is relative to the current nearest ancestor, then it is even nearer to the path + if (!nearestAncestor || candidatePathView.IsRelativeTo(nearestAncestor->m_fullPath)) { - toRemove.push_back(child); - - // it is possible that child may be a closer parent, substitute it as new potential parent - // e.g. child->m_relativePath = 'Gems', relativePath = 'Gems/Assets', old parent = root, new parent = Gems - if (childPath.length() == n && relativePath[n] == AZ_CORRECT_DATABASE_SEPARATOR) + nearestAncestor = candidateAncestor; + // If the full path compares equal to the AssetBrowserEntry path, then no need to proceed any further + if (AZ::IO::PathView(nearestAncestor->m_fullPath) == absolutePathView) { - parent = child; - relativePath += n; // advance relative path n characters since the parent has changed - n = 0; // Once the relative path pointer is advanced, reset n + break; } } } - for (auto entry : toRemove) - { - children.erase(AZStd::remove(children.begin(), children.end(), entry), children.end()); - } - n++; } - // filter out the remaining children that don't end with '/' or '\0' - // for example if folderName = "foo", while children may still remain with names like "foo123", - // which is not the same folder - AZStd::vector toRemove; - for (auto child : children) + return nearestAncestor; + } + + FolderAssetBrowserEntry* RootAssetBrowserEntry::CreateFolder(AZStd::string_view folderName, AssetBrowserEntry* parent) + { + auto it = AZStd::find_if(parent->m_children.begin(), parent->m_children.end(), [folderName](AssetBrowserEntry* entry) { - auto& childPath = azrtti_istypeof(parent) ? child->m_fullPath : child->m_relativePath; - // check if there are non-null characters remaining @n - if (childPath.length() > n) + if (!azrtti_istypeof(entry)) { - toRemove.push_back(child); + return false; } - } - for (auto entry : toRemove) + return AZ::IO::PathView(entry->m_name) == AZ::IO::PathView(folderName); + }); + if (it != parent->m_children.end()) { - children.erase(AZStd::remove(children.begin(), children.end(), entry), children.end()); + return azrtti_cast(*it); } + const auto folder = aznew FolderAssetBrowserEntry(); + folder->m_name = folderName; + folder->m_displayName = QString::fromUtf8(folderName.data(), aznumeric_caster(folderName.size())); + parent->AddChild(folder); + return folder; + } + + AssetBrowserEntry* RootAssetBrowserEntry::CreateFolders(AZStd::string_view absolutePath, AssetBrowserEntry* parent) + { + AZ::IO::PathView absolutePathView(absolutePath); + // Find the nearest ancestor path to the absolutePath + AZStd::unordered_set visitedSet; - // at least one child remains, this means the folder with this name already exists, return it - if (!children.empty()) + if (AssetBrowserEntry* nearestAncestor = GetNearestAncestor(absolutePathView, parent, visitedSet); + nearestAncestor != nullptr) { - parent = children.front(); + parent = nearestAncestor; } - // if it's a scanfolder, then do not create folders leading to it - // e.g. instead of 'C:\dev\SampleProject' just create 'SampleProject' - else if (parent->GetEntryType() == AssetEntryType::Root) + + // If the nearest ancestor is the absolutePath, then it is already crated + if (absolutePathView == AZ::IO::PathView(parent->GetFullPath())) { - AZStd::string folderName; - AzFramework::StringFunc::Path::Split(relativePath, nullptr, nullptr, &folderName); - parent = CreateFolder(folderName.c_str(), parent); - parent->m_fullPath = relativePath; + return parent; } - // otherwise create all missing folders - else + + // create all missing folders + auto proximateToPath = absolutePathView.IsRelativeTo(parent->m_fullPath) + ? absolutePathView.LexicallyProximate(parent->m_fullPath) + : AZ::IO::FixedMaxPath(absolutePathView); + for (AZ::IO::FixedMaxPath scanFolderSegment : proximateToPath) { - n = 0; - AZStd::string folderName(strlen(relativePath) + 1, '\0'); - // iterate through relativePath until the first '/' - while (relativePath[n] && relativePath[n] != AZ_CORRECT_DATABASE_SEPARATOR) - { - folderName[n] = relativePath[n]; - n++; - } - if (n > 0) - { - parent = CreateFolder(folderName.c_str(), parent); - } - // n+1 also skips the '/' character - if (relativePath[n] && relativePath[n + 1]) - { - parent = CreateFolders(relativePath + n + 1, parent); - } + parent = CreateFolder(scanFolderSegment.c_str(), parent); } return parent; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h index 883f9dec01..62fbc7a39d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -77,12 +78,15 @@ namespace AzToolsFramework private: AZ_DISABLE_COPY_MOVE(RootAssetBrowserEntry); - AZStd::string m_enginePath; + AZ::IO::Path m_enginePath; //! Create folder entry child - FolderAssetBrowserEntry* CreateFolder(const char* folderName, AssetBrowserEntry* parent); - //! Recursively create folder structure leading to relative path from parent - AssetBrowserEntry* CreateFolders(const char* relativePath, AssetBrowserEntry* parent); + FolderAssetBrowserEntry* CreateFolder(AZStd::string_view folderName, AssetBrowserEntry* parent); + //! Recursively create folder structure leading to path from parent + AssetBrowserEntry* CreateFolders(AZStd::string_view absolutePath, AssetBrowserEntry* parent); + // Retrieves the nearest ancestor AssetBrowserEntry from the absolutePath + static AssetBrowserEntry* GetNearestAncestor(AZ::IO::PathView absolutePath, AssetBrowserEntry* parent, + AZStd::unordered_set& visitedSet); bool m_isInitialUpdate = false; }; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp index e45c234c92..1eea909f7c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp @@ -26,9 +26,7 @@ namespace AzToolsFramework if (EntryCache* cache = EntryCache::GetInstance()) { cache->m_fileIdMap.erase(m_fileId); - AZStd::string fullPath = m_fullPath; - AzFramework::StringFunc::Path::Normalize(fullPath); - cache->m_absolutePathToFileId.erase(fullPath); + cache->m_absolutePathToFileId.erase(m_fullPath.LexicallyNormal().Native()); if (m_sourceId != -1) { From 173126f5a5f1b3a1efc65e5a902c48d63b2a5ad9 Mon Sep 17 00:00:00 2001 From: Brian Herrera Date: Mon, 19 Jul 2021 16:09:47 -0700 Subject: [PATCH 012/251] Add script for license scanner (#2267) * Add script for license scanner This script will scan the source tree for license files and generate a file with the contents of all the licenses. Signed-off-by: brianherrera --- scripts/license_scanner/license_scanner.py | 129 ++++++++++++++++++++ scripts/license_scanner/scanner_config.json | 12 ++ 2 files changed, 141 insertions(+) create mode 100644 scripts/license_scanner/license_scanner.py create mode 100644 scripts/license_scanner/scanner_config.json diff --git a/scripts/license_scanner/license_scanner.py b/scripts/license_scanner/license_scanner.py new file mode 100644 index 0000000000..c0e3c1f1ba --- /dev/null +++ b/scripts/license_scanner/license_scanner.py @@ -0,0 +1,129 @@ +# +# 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 argparse +import fnmatch +import json +import os +import pathlib +import re +import sys + + +class LicenseScanner: + """Class to contain license scanner. + + Scans source tree for license files using provided filename patterns and generates a file + with the contents of all the licenses. + + :param config_file: Config file with license patterns and scanner settings + """ + + DEFAULT_CONFIG_FILE = 'scanner_config.json' + + def __init__(self, config_file=None): + self.config_file = config_file + self.config_data = self._load_config() + self.license_regex = self._load_license_regex() + + def _load_config(self): + """Load config from the provided file. Sets default file if one is not provided.""" + if self.config_file is None: + script_directory = os.path.dirname(os.path.abspath(__file__)) # Default file expected in same dir as script + self.config_file = os.path.join(script_directory, self.DEFAULT_CONFIG_FILE) + + try: + with open(self.config_file) as f: + return json.load(f) + except FileNotFoundError: + print('Config file cannot be found') + raise + + def _load_license_regex(self): + """Returns regex object with case-insensitive matching from the list of filename patterns.""" + regex_patterns = [] + for pattern in self.config_data['license_patterns']: + regex_patterns.append(fnmatch.translate(pattern)) + return re.compile('|'.join(regex_patterns), re.IGNORECASE) + + def scan(self, path=os.curdir): + """Scan directory tree for filenames matching license_regex. + + :param path: Path of the directory to run scanner + :return: Package paths and their corresponding license file contents + :rtype: dict + """ + licenses = 0 + license_files = {} + + for dirpath, dirnames, filenames in os.walk(path): + for file in filenames: + if self.license_regex.match(file): + license_file_content = self._get_license_file_contents(os.path.join(dirpath, file)) + rel_dirpath = os.path.relpath(dirpath, path) # Limit path inside scanned directory + license_files[rel_dirpath] = license_file_content + licenses += 1 + print(f'License file: {os.path.join(dirpath, file)}') + + # Remove directories that should not be scanned + for dir in self.config_data['excluded_directories']: + if dir in dirnames: + dirnames.remove(dir) + print(f'{licenses} license files found.') + return license_files + + def _get_license_file_contents(self, filepath): + try: + with open(filepath, encoding='utf8') as f: + return f.read() + except UnicodeDecodeError: + print(f'Unable to read license file: {filepath}') + pass + + def create_license_file(self, licenses, filepath='NOTICES.txt'): + """Creates file with all the provided license file contents. + + :param licenses: Dict with package paths and their corresponding license file contents + :param filepath: Path to write the file + """ + package_separator = '------------------------------------' + with open(filepath, 'w', encoding='utf8') as f: + for directory, license in licenses.items(): + license_output = '\n\n'.join([ + f'{package_separator}', + f'Package path: {directory}', + 'License:', + f'{license}\n' + ]) + f.write(license_output) + return None + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Script to run LicenseScanner and generate license file') + parser.add_argument('--config-file', '-c', type=pathlib.Path, help='Config file for LicenseScanner') + parser.add_argument('--license-file-path', '-l', type=pathlib.Path, help='Create license file in the provided path') + parser.add_argument('--scan-path', '-s', default=os.curdir, type=pathlib.Path, help='Path to scan') + return parser.parse_args() + + +def main(): + try: + args = parse_args() + ls = LicenseScanner(args.config_file) + licenses = ls.scan(args.scan_path) + + if args.license_file_path: + ls.create_license_file(licenses, args.license_file_path) + except FileNotFoundError as e: + print(f'Type: {type(e).__name__}, Error: {e}') + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/license_scanner/scanner_config.json b/scripts/license_scanner/scanner_config.json new file mode 100644 index 0000000000..b5863a7d31 --- /dev/null +++ b/scripts/license_scanner/scanner_config.json @@ -0,0 +1,12 @@ +{ + "excluded_directories": [ + ".git", + ".venv", + "build", + "license_scanner" + ], + "license_patterns": [ + "LICENSE*", + "COPYING*" + ] +} From afb57c9cf679592a209dbccdd5f38126e03d6b59 Mon Sep 17 00:00:00 2001 From: Scott Romero <24445312+AMZN-ScottR@users.noreply.github.com> Date: Mon, 19 Jul 2021 18:17:55 -0700 Subject: [PATCH 013/251] [stabliziation/2106] update 3rd party license file name to be pulled into the installer package (#2281) License file name was changed in #2267 Signed-off-by: AMZN-ScottR 24445312+AMZN-ScottR@users.noreply.github.com --- cmake/Packaging.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index a07e1ec1d3..2240ff472c 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -128,7 +128,7 @@ install(FILES ${_cmake_package_dest} # the version string and git tags are intended to be synchronized so it should be safe to use that instead # of directly calling into git which could get messy in certain scenarios if(${CPACK_PACKAGE_VERSION} VERSION_GREATER "0.0.0.0") - set(_3rd_party_license_filename SPDX-Licenses.txt) + set(_3rd_party_license_filename NOTICES.txt) set(_3rd_party_license_url "https://raw.githubusercontent.com/o3de/3p-package-source/${CPACK_PACKAGE_VERSION}/${_3rd_party_license_filename}") set(_3rd_party_license_dest ${CPACK_BINARY_DIR}/${_3rd_party_license_filename}) From abce54b3cd0a574fff1a8612be838779ab597a73 Mon Sep 17 00:00:00 2001 From: Axel Nana Date: Tue, 20 Jul 2021 01:05:09 +0100 Subject: [PATCH 014/251] Add missing `*.hxx` pattern Signed-off-by: Axel Nana --- cmake/Platform/Common/Install_common.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 5b476667e2..0a84d3ceb2 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -64,6 +64,7 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar PATTERN *.h PATTERN *.hpp PATTERN *.inl + PATTERN *.hxx ) endif() endforeach() From b58286d9b1022c3e3051c3225b7000935066fd4c Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 20 Jul 2021 20:40:04 -0500 Subject: [PATCH 015/251] Fixed RootAssetBrowserEntry setting of child AssetBrowserEntries The issue is due to RootAssetBrowserEntry::UpdateChildPaths not taking the RootAssetBrowserEntry fullpath into account when appending the child path entry Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- .../AssetBrowser/Entries/RootAssetBrowserEntry.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp index 0e132d2581..eec9970ca3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp @@ -399,7 +399,7 @@ namespace AzToolsFramework void RootAssetBrowserEntry::UpdateChildPaths(AssetBrowserEntry* child) const { child->m_relativePath = child->m_name; - child->m_fullPath = child->m_name; + child->m_fullPath = m_fullPath / child->m_name; AssetBrowserEntry::UpdateChildPaths(child); } From 3050a4db479fb2dacf59942f7b0b42d7d82fcdcd Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Wed, 21 Jul 2021 10:18:18 -0500 Subject: [PATCH 016/251] Removing obsolete Vegetation Debugger test Signed-off-by: jckand-amzn --- .../EditorScripts/Debugger_DebugCVarsWorks.py | 55 ------------------ .../largeworlds/dyn_veg/test_Debugger.py | 56 ------------------- 2 files changed, 111 deletions(-) delete mode 100755 AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py delete mode 100755 AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py deleted file mode 100755 index 40fd67d957..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py +++ /dev/null @@ -1,55 +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 -""" - -import os -import sys - -import azlmbr.legacy.general as general -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - - -class TestDebuggerDebugCVarsWorks(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="Debugger_DebugCVarsWorks", args=["level"]) - - def run_test(self): - """ - Summary: - C2789148 Vegetation Debug CVars are enabled when the Debugger component is present - - Expected Result: - The following commands are available in the Editor only when the Vegetation Debugger Level component is present: - veg_debugDumpReport (Command) - veg_debugRefreshAllAreas (Command) - - :return: None - """ - - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # Initially run the command in console without Debugger component - general.run_console("veg_debugDumpReport") - - # Add the Vegetation Debugger component to the Level Inspector - hydra.add_level_component("Vegetation Debugger") - - # Run a command again after adding the Vegetation debugger - general.run_console("veg_debugRefreshAllAreas") - - -test = TestDebuggerDebugCVarsWorks() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py deleted file mode 100755 index ed979136e0..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py +++ /dev/null @@ -1,56 +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 -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestDebugger(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - def teardown(): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - request.addfinalizer(teardown) - - @pytest.mark.test_case_id("C2789148") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_Debugger_DebugCVarsWork(self, request, editor, level, workspace, launcher_platform): - cfg_args = [level] - - expected_lines = [ - "Debugger_DebugCVarsWorks: test started", - "[Warning] Unknown command: veg_debugDumpReport", - "[CONSOLE] Executing console command 'veg_debugRefreshAllAreas'", - "Debugger_DebugCVarsWorks: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "Debugger_DebugCVarsWorks.py", - expected_lines=expected_lines, - cfg_args=cfg_args - ) From 7ebdde0be01477ba036bad7f5a1e36ae50e2d879 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Wed, 21 Jul 2021 10:25:48 -0500 Subject: [PATCH 017/251] Adding xfail mark to test_LandscapeCanvas_GraphClosed_OnEntityDelete Signed-off-by: jckand-amzn --- .../landscape_canvas/test_GeneralGraphFunctionality.py | 1 + 1 file changed, 1 insertion(+) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py index bbca71461c..e2aa222c3f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py @@ -104,6 +104,7 @@ class TestGeneralGraphFunctionality(object): @pytest.mark.test_case_id("C17488412") @pytest.mark.SUITE_periodic + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2201") def test_LandscapeCanvas_GraphClosed_OnEntityDelete(self, request, editor, level, launcher_platform): cfg_args = [level] From fc1ccb9e8574a1d997bbc791fb46a6a1325ee3a2 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 21 Jul 2021 17:17:09 -0700 Subject: [PATCH 018/251] Issues/2126 PhysX Gem can't be used as build dependency in engine SDK Part (#2337) * Applying GENEX_EVAL to 2 cases where the genex can produce another genex Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * Missing case when the folder is an external one to the engine/project (e.g. external gems) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/LauncherUnified/launcher_generator.cmake | 4 ++-- cmake/LYWrappers.cmake | 15 ++++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Code/LauncherUnified/launcher_generator.cmake b/Code/LauncherUnified/launcher_generator.cmake index 628b5fffac..28fddad1eb 100644 --- a/Code/LauncherUnified/launcher_generator.cmake +++ b/Code/LauncherUnified/launcher_generator.cmake @@ -40,9 +40,9 @@ foreach(project_name project_path IN ZIP_LISTS LY_PROJECTS_TARGET_NAME LY_PROJEC add_custom_target(${project_name}.Assets COMMENT "Processing ${project_name} assets..." COMMAND "${CMAKE_COMMAND}" - -DLY_LOCK_FILE=$/project_assets.lock + -DLY_LOCK_FILE=$>/project_assets.lock -P ${LY_ROOT_FOLDER}/cmake/CommandExecution.cmake - EXEC_COMMAND $ + EXEC_COMMAND $> --zeroAnalysisMode --project-path=${project_real_path} --platforms=${LY_ASSET_DEPLOY_ASSET_TYPE} diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 40bf6ef541..cfe6df5c81 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -391,10 +391,10 @@ function(ly_delayed_target_link_libraries) endif() if(item_type STREQUAL MODULE_LIBRARY) - target_include_directories(${target} ${visibility} $) - target_link_libraries(${target} ${visibility} $) - target_compile_definitions(${target} ${visibility} $) - target_compile_options(${target} ${visibility} $) + target_include_directories(${target} ${visibility} $>) + target_link_libraries(${target} ${visibility} $>) + target_compile_definitions(${target} ${visibility} $>) + target_compile_options(${target} ${visibility} $>) else() ly_parse_third_party_dependencies(${item}) target_link_libraries(${target} ${visibility} ${item}) @@ -659,7 +659,12 @@ function(ly_get_vs_folder_directory absolute_target_source_dir output_source_dir if(is_target_prefix_of_engine_root) cmake_path(RELATIVE_PATH absolute_target_source_dir BASE_DIRECTORY ${LY_ROOT_FOLDER} OUTPUT_VARIABLE relative_target_source_dir) else() - cmake_path(GET absolute_target_source_dir RELATIVE_PART relative_target_source_dir) + cmake_path(IS_PREFIX CMAKE_SOURCE_DIR ${absolute_target_source_dir} is_target_prefix_of_source_dir) + if(is_target_prefix_of_source_dir) + cmake_path(RELATIVE_PATH absolute_target_source_dir BASE_DIRECTORY ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE relative_target_source_dir) + else() + cmake_path(GET absolute_target_source_dir RELATIVE_PART relative_target_source_dir) + endif() endif() set(${output_source_dir} ${relative_target_source_dir} PARENT_SCOPE) From d08cbd2c339a40425c1376ba22f078196ac3b5df Mon Sep 17 00:00:00 2001 From: evanchia Date: Thu, 22 Jul 2021 13:55:55 -0700 Subject: [PATCH 019/251] Moving load level test from sandbox to smoke with fixes Signed-off-by: evanchia --- .../Gem/PythonTests/smoke/CMakeLists.txt | 13 ++- .../test_RemoteConsole_CPULoadLevel_Works.py | 105 ++++++++++++++++++ ... test_RemoteConsole_GPULoadLevel_Works.py} | 3 +- 3 files changed, 113 insertions(+), 8 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py rename AutomatedTesting/Gem/PythonTests/smoke/{test_RemoteConsole_LoadLevel_Works.py => test_RemoteConsole_GPULoadLevel_Works.py} (98%) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 600911e9f1..a6584c3de8 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -32,12 +32,12 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ) 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 @@ -45,7 +45,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) 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..ea27b14aab --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py @@ -0,0 +1,105 @@ +""" +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_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"'] + + 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=True, + 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(["-rhi=Null"]) + + # 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/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py rename to AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py index b1606e1910..6c4a22bc23 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py @@ -25,7 +25,6 @@ from ly_remote_console.remote_console_commands import ( @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): @@ -80,7 +79,7 @@ class TestRemoteConsoleLoadLevelWorks(object): return port_listening if null_renderer: - launcher.args.extend(["-NullRenderer"]) + launcher.args.extend(["-rhi=Null"]) # Start the Launcher with launcher.start(): From 05728920f7ba4490505b26fbebd691f24c443e26 Mon Sep 17 00:00:00 2001 From: evanchia Date: Thu, 22 Jul 2021 15:05:09 -0700 Subject: [PATCH 020/251] Replaced with imported functions for smoke tests Signed-off-by: evanchia --- .../Gem/PythonTests/smoke/CMakeLists.txt | 1 - .../test_RemoteConsole_CPULoadLevel_Works.py | 63 +------------------ .../test_RemoteConsole_GPULoadLevel_Works.py | 63 +------------------ 3 files changed, 4 insertions(+), 123 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index a6584c3de8..78ac85de9f 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -41,7 +41,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::PythonBindingsExample - Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets COMPONENT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py index ea27b14aab..54d7b3eb6f 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py @@ -16,6 +16,7 @@ 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 +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, @@ -42,64 +43,4 @@ class TestRemoteConsoleLoadLevelWorks(object): 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=True, - 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(["-rhi=Null"]) - - # 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}" + 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 index 6c4a22bc23..bfce7895e6 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py @@ -16,6 +16,7 @@ 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 +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, @@ -41,64 +42,4 @@ class TestRemoteConsoleLoadLevelWorks(object): 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(["-rhi=Null"]) - - # 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}" + editor_test_utils.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, null_renderer=False) From 9358428bebd7d3b0166af8cf447d58d7caf37f72 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sun, 25 Jul 2021 22:39:22 -0700 Subject: [PATCH 021/251] Added object release queue notification to the RHI Device and ObjectCollector. Signed-off-by: dmcdiar --- Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h | 4 ++ .../Code/Include/Atom/RHI/ObjectCollector.h | 60 +++++++++++++++++++ Gems/Atom/RHI/Code/Tests/Device.h | 2 + Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp | 5 ++ Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h | 1 + .../Atom/RHI/Metal/Code/Source/RHI/Device.cpp | 7 ++- Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h | 3 +- Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp | 5 ++ Gems/Atom/RHI/Null/Code/Source/RHI/Device.h | 1 + .../RHI/Vulkan/Code/Source/RHI/Device.cpp | 5 ++ Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h | 1 + Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h | 1 + 12 files changed, 93 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h index 3f79392403..4232658980 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include #include @@ -140,6 +141,9 @@ namespace AZ //! Get the memory requirements for allocating a buffer resource. virtual ResourceMemoryRequirements GetResourceMemoryRequirements(const BufferDescriptor& descriptor) = 0; + //! Notifies after all objects currently in the platform release queue are released + virtual void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) = 0; + protected: DeviceFeatures m_features; DeviceLimits m_limits; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h index cb66225286..d79a86afea 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h @@ -34,6 +34,8 @@ namespace AZ using MutexType = NullMutex; }; + using ObjectCollectorNotifyFunction = AZStd::function; + /** * Deferred-releases reference-counted objects at a specific latency. Example: Use to batch-release * objects that exist on the GPU timeline at the end of the frame after syncing the oldest GPU frame. @@ -85,6 +87,9 @@ namespace AZ /// Must not be called at collection time. size_t GetObjectCount() const; + /// Notifies after the current set of pending objects is released. + void Notify(ObjectCollectorNotifyFunction notifyFunction); + private: void QueueForCollectInternal(ObjectPtrType object); @@ -92,6 +97,7 @@ namespace AZ { AZStd::vector m_objects; uint64_t m_collectIteration; + AZStd::vector m_notifies; }; inline bool IsGarbageReady(size_t collectIteration) @@ -106,6 +112,7 @@ namespace AZ mutable typename Traits::MutexType m_mutex; AZStd::vector m_pendingObjects; AZStd::vector m_pendingGarbage; + AZStd::vector m_pendingNotifies; }; template @@ -174,6 +181,45 @@ namespace AZ } m_mutex.unlock(); + if (m_pendingNotifies.size()) + { + if (m_pendingGarbage.size()) + { + // find the newest garbage entry and add any pending notifies + Garbage& latestGarbage = m_pendingGarbage.front(); + size_t latestGarbageAge = m_currentIteration - latestGarbage.m_collectIteration; + size_t i = 1; + while (i < m_pendingGarbage.size()) + { + size_t age = m_currentIteration - m_pendingGarbage[i].m_collectIteration; + if (age < latestGarbageAge) + { + latestGarbage = m_pendingGarbage[i]; + latestGarbageAge = age; + } + } + + latestGarbage.m_notifies.insert(latestGarbage.m_notifies.end(), m_pendingNotifies.begin(), m_pendingNotifies.end()); + + m_mutex.lock(); + m_pendingNotifies.clear(); + m_mutex.unlock(); + + } + else + { + // garbage queue is empty, notify now + m_mutex.lock(); + for (auto& notifyFunction : m_pendingNotifies) + { + notifyFunction(); + } + + m_pendingNotifies.clear(); + m_mutex.unlock(); + } + } + size_t objectCount = 0; size_t i = 0; while (i < m_pendingGarbage.size()) @@ -189,6 +235,12 @@ namespace AZ } } objectCount += garbage.m_objects.size(); + + for (auto& notifyFunction : garbage.m_notifies) + { + notifyFunction(); + } + garbage = AZStd::move(m_pendingGarbage.back()); m_pendingGarbage.pop_back(); } @@ -215,5 +267,13 @@ namespace AZ return objectCount; } + + template + void ObjectCollector::Notify(ObjectCollectorNotifyFunction notifyFunction) + { + m_mutex.lock(); + m_pendingNotifies.push_back(notifyFunction); + m_mutex.unlock(); + } } } diff --git a/Gems/Atom/RHI/Code/Tests/Device.h b/Gems/Atom/RHI/Code/Tests/Device.h index 3a7c513c8b..e11bd75983 100644 --- a/Gems/Atom/RHI/Code/Tests/Device.h +++ b/Gems/Atom/RHI/Code/Tests/Device.h @@ -60,6 +60,8 @@ namespace UnitTest AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::ImageDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::BufferDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; + + void ObjectCollectionNotify(AZ::RHI::ObjectCollectorNotifyFunction notifyFunction) override {} }; AZ::RHI::Ptr MakeTestDevice(); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp index 88c9098952..9d23dfa43d 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp @@ -292,6 +292,11 @@ namespace AZ return memoryRequirements; } + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + //AZStd::vector Device::GetValidSwapChainImageFormats(const RHI::WindowHandle& windowHandle) const //{ // AZStd::vector formatsList; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h index 149508307a..9119545342 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h @@ -162,6 +162,7 @@ namespace AZ void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor & descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor & descriptor) override; + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// RHI::ResultCode InitSubPlatform(RHI::PhysicalDevice& physicalDevice); diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp index f0771d7c45..dbd2204e93 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp @@ -315,7 +315,12 @@ namespace AZ memoryRequirements.m_sizeInBytes = bufferSizeAndAlign.size; return memoryRequirements; } - + + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + void Device::InitFeatures() { diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h index d8c3092c59..9cdeee7eae 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h @@ -151,7 +151,8 @@ namespace AZ NullDescriptorManager& GetNullDescriptorManager(); RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor & descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor & descriptor) override; - + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; + private: Device() = default; diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp index 7b94efb69f..08a2c4f411 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp @@ -20,5 +20,10 @@ namespace AZ { formatsCapabilities.fill(static_cast(~0)); } + + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + notifyFunction(); + } } } diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h index 3aa045212b..cd44135e62 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h @@ -42,6 +42,7 @@ namespace AZ void PreShutdown() override {} RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const RHI::ImageDescriptor& descriptor) override { return RHI::ResourceMemoryRequirements();} RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const RHI::BufferDescriptor& descriptor) override { return RHI::ResourceMemoryRequirements();} + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// }; } diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index 6d3080dce8..05ff8bb2a6 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -652,6 +652,11 @@ namespace AZ return RHI::ResourceMemoryRequirements{ vkRequirements.alignment, vkRequirements.size }; } + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + void Device::InitFeaturesAndLimits(const PhysicalDevice& physicalDevice) { m_features.m_tessellationShader = (m_enabledDeviceFeatures.tessellationShader == VK_TRUE); diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h index d5f055f4cd..28e56d1fa9 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h @@ -134,6 +134,7 @@ namespace AZ void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor& descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor& descriptor) override; + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// void InitFeaturesAndLimits(const PhysicalDevice& physicalDevice); diff --git a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h index 1de06802b1..be362c60d6 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h +++ b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h @@ -70,6 +70,7 @@ namespace UnitTest void PreShutdown() override {} AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::ImageDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::BufferDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; + void ObjectCollectionNotify(AZ::RHI::ObjectCollectorNotifyFunction notifyFunction) override {} }; class ImageView From 46777b537e350ce4b115facebcf25533f81a0da4 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Mon, 26 Jul 2021 18:01:14 -0400 Subject: [PATCH 022/251] Brought over LY legacy imgui code Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../Debug/MultiplayerDebugByteReporter.cpp | 222 ++++++++++ .../Debug/MultiplayerDebugByteReporter.h | 96 +++++ .../MultiplayerDebugPerEntityReporter.cpp | 385 ++++++++++++++++++ .../Debug/MultiplayerDebugPerEntityReporter.h | 90 ++++ .../Debug/MultiplayerDebugSystemComponent.cpp | 11 + .../Debug/MultiplayerDebugSystemComponent.h | 4 + .../Code/multiplayer_debug_files.cmake | 4 + 7 files changed, 812 insertions(+) create mode 100644 Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp create mode 100644 Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h create mode 100644 Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp create mode 100644 Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp new file mode 100644 index 0000000000..382bc70d9b --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -0,0 +1,222 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#include "MultiplayerDebugByteReporter.h" + +#include +#include +#include + +namespace MultiplayerDiagnostics +{ + void MultiplayerDebugByteReporter::ReportBytes(size_t byteSize) + { + m_count++; + m_totalBytes += byteSize; + m_totalBytesThisSecond += byteSize; + m_minBytes = AZStd::min(m_minBytes, byteSize); + m_maxBytes = AZStd::max(m_maxBytes, byteSize); + } + + void MultiplayerDebugByteReporter::AggregateBytes(size_t byteSize) + { + m_aggregateBytes += byteSize; + } + + void MultiplayerDebugByteReporter::ReportAggregateBytes() + { + ReportBytes(m_aggregateBytes); + m_aggregateBytes = 0; + } + + float MultiplayerDebugByteReporter::GetAverageBytes() const + { + if (m_count == 0) + { + AZ_Warning("MultiplayerDebugByteReporter", m_totalBytes == 0, "Attempted to average bytes with a zero count."); + return 0.0f; + } + + return (1.0f * m_totalBytes) / m_count; + } + + size_t MultiplayerDebugByteReporter::GetMaxBytes() const + { + return m_maxBytes; + } + + size_t MultiplayerDebugByteReporter::GetMinBytes() const + { + return m_minBytes; + } + + size_t MultiplayerDebugByteReporter::GetTotalBytes() const + { + return m_totalBytes; + } + + float MultiplayerDebugByteReporter::GetKbitsPerSecond() + { + auto now = AZStd::chrono::monotonic_clock::now(); + + // Check the amount of time elapsed and update totals if necessary. + // Time here is measured in whole seconds from the epoch, providing synchronization in + // reporting intervals across all byte reporters. + AZStd::chrono::seconds nowSeconds = AZStd::chrono::duration_cast(now.time_since_epoch()); + AZStd::chrono::seconds secondsSinceLastUpdate = nowSeconds - + AZStd::chrono::duration_cast(m_lastUpdateTime.time_since_epoch()); + if (secondsSinceLastUpdate.count()) + { + // normalize over elapsed milliseconds + const int k_millisecondsPerSecond = 1000; + auto msSinceLastUpdate = AZStd::chrono::duration_cast(now - m_lastUpdateTime); + m_totalBytesLastSecond = k_millisecondsPerSecond * (1.f * m_totalBytesThisSecond / msSinceLastUpdate.count()); + m_totalBytesThisSecond = 0; + m_lastUpdateTime = now; + } + + const float k_bitsPerByte = 8.0f; + const int k_bitsPerKilobit = 1024; + return k_bitsPerByte * m_totalBytesLastSecond / k_bitsPerKilobit; + } + + void MultiplayerDebugByteReporter::Combine(const MultiplayerDebugByteReporter& other) + { + m_count += other.m_count; + m_totalBytes += other.m_totalBytes; + m_totalBytesThisSecond += other.m_totalBytesThisSecond; + m_minBytes = AZStd::GetMin(m_minBytes, other.m_minBytes); + m_maxBytes = AZStd::GetMax(m_maxBytes, other.m_maxBytes); + } + + void MultiplayerDebugByteReporter::Reset() + { + m_count = 0; + m_totalBytes = 0; + m_totalBytesThisSecond = 0; + m_totalBytesLastSecond = 0; + m_minBytes = std::numeric_limits::max(); + m_maxBytes = 0; + m_aggregateBytes = 0; + } + + void ComponentReporter::ReportField(const char* fieldName, size_t byteSize) + { + MultiplayerDebugByteReporter::AggregateBytes(byteSize); + m_fieldReports[fieldName].ReportBytes(byteSize); + } + + void ComponentReporter::ReportFragmentEnd() + { + MultiplayerDebugByteReporter::ReportAggregateBytes(); + m_componentDirtyBytes.ReportAggregateBytes(); + } + + AZStd::vector ComponentReporter::GetFieldReports() + { + AZStd::vector copy; + for (auto field = m_fieldReports.begin(); field != m_fieldReports.end(); ++field) + { + copy.emplace_back(field->first, &field->second); + } + + auto sortByFrequency = [](const Report& a, const Report& b) + { + return a.second->GetTotalCount() > b.second->GetTotalCount(); + }; + + AZStd::sort(copy.begin(), copy.end(), sortByFrequency); + + return copy; + } + + void ComponentReporter::Combine(const ComponentReporter& other) + { + MultiplayerDebugByteReporter::Combine(other); + + for (const auto& fieldIter : other.m_fieldReports) + { + m_fieldReports[fieldIter.first].Combine(fieldIter.second); + } + + m_componentDirtyBytes.Combine(other.m_componentDirtyBytes); + } + + void EntityReporter::ReportField(AZ::u32 index, const char* componentName, + const char* fieldName, size_t byteSize) + { + if (m_currentComponentReport == nullptr) + { + std::stringstream component; + component << "[" << std::setw(2) << std::setfill('0') << static_cast(index) << "]" << " " << componentName; + m_currentComponentReport = &m_componentReports[component.str().c_str()]; + } + + m_currentComponentReport->ReportField(fieldName, byteSize); + MultiplayerDebugByteReporter::AggregateBytes(byteSize); + } + + void EntityReporter::ReportDirtyBits(AZ::u32 index, const char* componentName, size_t byteSize) + { + const char* const prefix = "MB::"; + if (strncmp(prefix, componentName, 4) == 0) + { + componentName += strlen(prefix); + } + + if (m_currentComponentReport == nullptr) + { + std::stringstream component; + component << "[" << std::setw(2) << std::setfill('0') << static_cast(index) << "]" << " " << componentName; + m_currentComponentReport = &m_componentReports[component.str().c_str()]; + } + + m_currentComponentReport->ReportDirtyBits(byteSize); + m_gdeDirtyBytes.AggregateBytes(byteSize); + } + + void EntityReporter::ReportFragmentEnd() + { + if (m_currentComponentReport) + { + m_currentComponentReport->ReportFragmentEnd(); + m_currentComponentReport = nullptr; + } + + m_gdeDirtyBytes.ReportAggregateBytes(); + MultiplayerDebugByteReporter::ReportAggregateBytes(); + } + + void EntityReporter::Combine(const EntityReporter& other) + { + MultiplayerDebugByteReporter::Combine(other); + + for (const auto& componentIter : other.m_componentReports) + { + m_componentReports[componentIter.first].Combine(componentIter.second); + } + + m_gdeDirtyBytes.Combine(other.m_gdeDirtyBytes); + } + + void EntityReporter::Reset() + { + MultiplayerDebugByteReporter::Reset(); + + m_componentReports.clear(); + m_gdeDirtyBytes.Reset(); + } + + AZStd::map& EntityReporter::GetComponentReports() + { + return m_componentReports; + } +} diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h new file mode 100644 index 0000000000..7e6a04569d --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h @@ -0,0 +1,96 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once + +#include +#include +#include +#include + +namespace MultiplayerDiagnostics +{ + class MultiplayerDebugByteReporter + { + public: + MultiplayerDebugByteReporter() { MultiplayerDebugByteReporter::Reset(); } + virtual ~MultiplayerDebugByteReporter() = default; + + void ReportBytes(size_t byteSize); + void AggregateBytes(size_t byteSize); + void ReportAggregateBytes(); + + float GetAverageBytes() const; + size_t GetMaxBytes() const; + size_t GetMinBytes() const; + size_t GetTotalBytes() const; + float GetKbitsPerSecond(); + + void Combine(const MultiplayerDebugByteReporter& other); + virtual void Reset(); + + size_t GetTotalCount() const { return m_count; } + + private: + size_t m_count; + size_t m_totalBytes; + size_t m_totalBytesThisSecond; + float m_totalBytesLastSecond; + size_t m_minBytes; + size_t m_maxBytes; + size_t m_aggregateBytes; + + AZStd::chrono::monotonic_clock::time_point m_lastUpdateTime; + }; + + class ComponentReporter : public MultiplayerDebugByteReporter + { + public: + ComponentReporter() = default; + + void ReportField(const char* fieldName, size_t byteSize); + void ReportDirtyBits(size_t byteSize) { m_componentDirtyBytes.AggregateBytes(byteSize); } + void ReportFragmentEnd(); + + using Report = AZStd::pair; + AZStd::vector GetFieldReports(); + AZStd::size_t GetTotalDirtyBits() const { return m_componentDirtyBytes.GetTotalBytes(); } + float GetAvgDirtyBits() const { return m_componentDirtyBytes.GetAverageBytes(); } + + void Combine(const ComponentReporter& other); + + private: + AZStd::map m_fieldReports; + MultiplayerDebugByteReporter m_componentDirtyBytes; + }; + + class EntityReporter : public MultiplayerDebugByteReporter + { + public: + EntityReporter() = default; + + void ReportField(AZ::u32 index, const char* componentName, const char* fieldName, size_t byteSize); + void ReportDirtyBits(AZ::u32 index, const char* componentName, size_t byteSize); + void ReportFragmentEnd(); + + void Combine(const EntityReporter& other); + void Reset() override; + + AZStd::map& GetComponentReports(); + AZStd::size_t GetTotalDirtyBits() const { return m_gdeDirtyBytes.GetTotalBytes(); } + float GetAvgDirtyBits() const { return m_gdeDirtyBytes.GetAverageBytes(); } + + private: + ComponentReporter* m_currentComponentReport = nullptr; + AZStd::map m_componentReports; + MultiplayerDebugByteReporter m_gdeDirtyBytes; + }; +} diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp new file mode 100644 index 0000000000..e60b800372 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -0,0 +1,385 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#include "MultiplayerDebugPerEntityReporter.h" +#include +#include +#include + +#if defined(IMGUI_ENABLED) +#include +#endif + +namespace MultiplayerDiagnostics +{ +#if defined(IMGUI_ENABLED) + static const ImVec4 k_ImGuiTomato = ImVec4(1.0f, 0.4f, 0.3f, 1.0f); + static const ImVec4 k_ImGuiKhaki = ImVec4(0.9f, 0.8f, 0.5f, 1.0f); + static const ImVec4 k_ImGuiCyan = ImVec4(0.5f, 1.0f, 1.0f, 1.0f); + static const ImVec4 k_ImGuiDusk = ImVec4(0.7f, 0.7f, 1.0f, 1.0f); + static const ImVec4 k_ImGuiWhite = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + + // -------------------------------------------------------------------------------------------- + template + bool ReplicatedStateTreeNode(const AZStd::string& name, Reporter& report, const ImVec4& color, int depth = 0) + { + const int defaultPadAmount = 55; + const int depthReduction = 3; + ImGui::PushStyleColor(ImGuiCol_Text, color); + + const bool expanded = ImGui::TreeNode(name.c_str(), + "%-*s %7.2f kbps %7.2f B Avg. %4zu B Max %10zu B Payload", + defaultPadAmount - depthReduction * depth, + name.c_str(), + report.GetKbitsPerSecond(), + report.GetAverageBytes(), + report.GetMaxBytes(), + report.GetTotalBytes()); + ImGui::PopStyleColor(); + return expanded; + } + + // -------------------------------------------------------------------------------------------- + void DisplayReplicatedStateReport(AZStd::map& componentReports, float kbpsWarn, float maxWarn) + { + for (auto& componentPair : componentReports) + { + ImGui::Separator(); + ComponentReporter& componentReport = componentPair.second; + + if (ReplicatedStateTreeNode(componentPair.first, componentReport, k_ImGuiCyan, 1)) + { + ImGui::Separator(); + ImGui::Columns(6, "replicated_field_columns"); + ImGui::NextColumn(); + ImGui::Text("kbps"); + ImGui::NextColumn(); + ImGui::Text("Avg. Bytes"); + ImGui::NextColumn(); + ImGui::Text("Min Bytes"); + ImGui::NextColumn(); + ImGui::Text("Max Bytes"); + ImGui::NextColumn(); + ImGui::Text("Total Bytes"); + ImGui::NextColumn(); + + auto fieldReports = componentReport.GetFieldReports(); + for (auto& fieldPair : fieldReports) + { + MultiplayerDebugByteReporter& fieldReport = *fieldPair.second; + const float kbitsLastSecond = fieldReport.GetKbitsPerSecond(); + + const ImVec4* textColor = &k_ImGuiWhite; + if (fieldReport.GetMaxBytes() > maxWarn) + { + textColor = &k_ImGuiKhaki; + } + + if (kbitsLastSecond > kbpsWarn) + { + textColor = &k_ImGuiTomato; + } + + ImGui::PushStyleColor(ImGuiCol_Text, *textColor); + + ImGui::Text("%s", fieldPair.first.c_str()); + ImGui::NextColumn(); + ImGui::Text("%.2f", kbitsLastSecond); + ImGui::NextColumn(); + ImGui::Text("%.2f", fieldReport.GetAverageBytes()); + ImGui::NextColumn(); + ImGui::Text("%zu", fieldReport.GetMinBytes()); + ImGui::NextColumn(); + ImGui::Text("%zu", fieldReport.GetMaxBytes()); + ImGui::NextColumn(); + ImGui::Text("%zu", fieldReport.GetTotalBytes()); + ImGui::NextColumn(); + + ImGui::PopStyleColor(); + } + + ImGui::Columns(1); + ImGui::TreePop(); + } + } + } +#endif + + MultiplayerDebugPerEntityReporter::MultiplayerDebugPerEntityReporter () + { + GridMate::Debug::CarrierDrillerBus::Handler::BusConnect(); + } + + // -------------------------------------------------------------------------------------------- + MultiplayerDebugPerEntityReporter::~MultiplayerDebugPerEntityReporter() + { + GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); + GridMate::Debug::CarrierDrillerBus::Handler::BusDisconnect(); + } + + void MultiplayerDebugPerEntityReporter::OnReceiveReplicaBegin(GridMate::Replica*, const void*, size_t) + { + m_currentReceivingEntityReport.Reset(); + } + + void MultiplayerDebugPerEntityReporter::OnReceiveReplicaEnd(GridMate::Replica* replica) + { + m_receivingEntityReports[replica->GetDebugName()].Combine(m_currentReceivingEntityReport); + } + + void MultiplayerDebugPerEntityReporter::OnReceiveReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex) + { + AZ_UNUSED(chunk); + AZ_UNUSED(chunkIndex); + m_currentReceivingEntityReport.ReportFragmentEnd(); + } + + void MultiplayerDebugPerEntityReporter::OnReceiveDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, + GridMate::DataSetBase* dataSet, GridMate::PeerId, GridMate::PeerId, const void*, size_t len) + { + m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); + } + + void MultiplayerDebugPerEntityReporter::OnReceiveRpc (GridMate::ReplicaChunkBase* chunk, + AZ::u32 chunkIndex, + GridMate::Internal::RpcRequest* rpc, + GridMate::PeerId from, + GridMate::PeerId to, + const void* data, + size_t len) + { + AZ_UNUSED( from ); + AZ_UNUSED( to ); + AZ_UNUSED( data ); + + m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); + } + + void MultiplayerDebugPerEntityReporter::OnSendReplicaBegin (GridMate::Replica*) + { + m_currentSendingEntityReport.Reset(); + } + + void MultiplayerDebugPerEntityReporter::OnSendReplicaEnd (GridMate::Replica* replica, const void*, size_t) + { + m_sendingEntityReports[replica->GetDebugName()].Combine(m_currentSendingEntityReport); + } + + void MultiplayerDebugPerEntityReporter::OnSendReplicaChunkEnd (GridMate::ReplicaChunkBase* chunk, + AZ::u32 chunkIndex, + const void*, + size_t) + { + AZ_UNUSED(chunk); + AZ_UNUSED(chunkIndex); + m_currentSendingEntityReport.ReportFragmentEnd(); + } + + void MultiplayerDebugPerEntityReporter::OnSendDataSet (GridMate::ReplicaChunkBase* chunk, + AZ::u32 chunkIndex, + GridMate::DataSetBase* dataSet, + GridMate::PeerId, + GridMate::PeerId, + const void*, + size_t len) + { + m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); + } + + void MultiplayerDebugPerEntityReporter::OnSendRpc (GridMate::ReplicaChunkBase* chunk, + AZ::u32 chunkIndex, + GridMate::Internal::RpcRequest* rpc, + GridMate::PeerId, + GridMate::PeerId, + const void*, + size_t len) + { + m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); + } + + void MultiplayerDebugPerEntityReporter::OnIncomingConnection (GridMate::Carrier*, GridMate::ConnectionID) + { + } + + void MultiplayerDebugPerEntityReporter::OnFailedToConnect (GridMate::Carrier*, + GridMate::ConnectionID, + GridMate::CarrierDisconnectReason) + { + m_lastSecondStats.clear(); + } + + void MultiplayerDebugPerEntityReporter::OnConnectionEstablished (GridMate::Carrier*, GridMate::ConnectionID) + { + } + + void MultiplayerDebugPerEntityReporter::OnDisconnect (GridMate::Carrier*, + GridMate::ConnectionID, + GridMate::CarrierDisconnectReason) + { + /* + * CarrierDrillerBus doesn't provide enough information to correctly keep track of network traffic for all peers. + * This is a work around until that is fixed to at least not over report the bandwidth amount. + */ + m_lastSecondStats.clear(); + } + + void MultiplayerDebugPerEntityReporter::OnDriverError (GridMate::Carrier*, + GridMate::ConnectionID, + const GridMate::DriverError&) + { + m_lastSecondStats.clear(); + } + + void MultiplayerDebugPerEntityReporter::OnSecurityError (GridMate::Carrier*, + GridMate::ConnectionID, + const GridMate::SecurityError&) + { + m_lastSecondStats.clear(); + } + + void MultiplayerDebugPerEntityReporter::OnUpdateStatistics (const GridMate::string& address, + const GridMate::TrafficControl::Statistics&, + const GridMate::TrafficControl::Statistics&, + const GridMate::TrafficControl::Statistics& effectiveLastSecond, + const GridMate::TrafficControl::Statistics&) + { + m_lastSecondStats[address] = effectiveLastSecond; + } + + void MultiplayerDebugPerEntityReporter::OnConnectionStateChanged (GridMate::Carrier*, + GridMate::ConnectionID, + GridMate::Carrier::ConnectionStates) + { + m_lastSecondStats.clear(); + } + + void MultiplayerDebugPerEntityReporter::UpdateTrafficStatistics() + { +#if defined(IMGUI_ENABLED) + AZ::u32 dataReceived = 0, dataSent = 0; + + for (auto& perConnection : m_lastSecondStats) + { + dataReceived += perConnection.second.m_dataReceived; + dataSent += perConnection.second.m_dataSend; + } + + if (dataReceived !=0 || dataSent != 0) + { + ImGui::Text("Total bandwidth: Sent %u kbps Received %u kbps.", dataSent * 8 / 1000, dataReceived * 8 / 1000); + } + else + { + ImGui::Text("Total bandwidth: Sent -- kbps Received -- kbps."); + } +#endif + } + + // -------------------------------------------------------------------------------------------- + void MultiplayerDebugPerEntityReporter::OnImGuiUpdate() + { +#if defined(IMGUI_ENABLED) + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("GridMate")) + { + if (m_showServerReportWindow) + { + if (ImGui::MenuItem("Hide Multiplayer Analytics Window")) + { + m_showServerReportWindow = false; + } + } + else if (ImGui::MenuItem("Show Multiplayer Analytics Window")) + { + m_showServerReportWindow = true; + } + + ImGui::End(); + } + + ImGui::EndMainMenuBar(); + } + + if (m_showServerReportWindow) + { + if (ImGui::Begin("Multiplayer Analytics", &m_showServerReportWindow)) + { + // General carrier stats + UpdateTrafficStatistics(); + + if (ImGui::Checkbox("Analyze network traffic", &m_isTrackingMessages)) + { + if (m_isTrackingMessages) + { + GridMate::Debug::ReplicaDrillerBus::Handler::BusConnect(); + } + else + { + GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); + + m_currentReceivingEntityReport.Reset(); + m_receivingEntityReports.clear(); + + m_currentSendingEntityReport.Reset(); + m_sendingEntityReports.clear(); + } + } + + if (m_isTrackingMessages) + { + ImGui::Separator(); + + static ImGuiTextFilter filter; + filter.Draw(); + + if (ImGui::CollapsingHeader("Received replicas per type")) + { + for (auto& entityPair : m_receivingEntityReports) + { + if (!filter.PassFilter(entityPair.first.c_str())) + { + continue; + } + + ImGui::Separator(); + if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) + { + DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); + ImGui::TreePop(); + } + } + } + + if (ImGui::CollapsingHeader("Sent replicas per type")) + { + for (auto& entityPair : m_sendingEntityReports) + { + if (!filter.PassFilter(entityPair.first.c_str())) + { + continue; + } + + ImGui::Separator(); + if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) + { + DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); + ImGui::TreePop(); + } + } + } + } + } + ImGui::End(); + } +#endif + } +} diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h new file mode 100644 index 0000000000..96cfadb14d --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h @@ -0,0 +1,90 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ +#pragma once +#include +#include "MultiplayerDebugByteReporter.h" +#include + +namespace MultiplayerDiagnostics +{ + /** + * \brief GridMate network live analysis tool via ImGui. + */ + class MultiplayerDebugPerEntityReporter + : public GridMate::Debug::ReplicaDrillerBus::Handler + , public GridMate::Debug::CarrierDrillerBus::Handler + { + public: + MultiplayerDebugPerEntityReporter(); + virtual ~MultiplayerDebugPerEntityReporter(); + + // main update loop + void OnImGuiUpdate(); + + // ReplicaDrillerBus - receive + + void OnReceiveReplicaBegin(GridMate::Replica* replica, const void* data, size_t len) override; + void OnReceiveReplicaEnd(GridMate::Replica* replica) override; + void OnReceiveReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex) override; + void OnReceiveDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::DataSetBase* dataSet, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; + void OnReceiveRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; + + // ReplicaDrillerBus - sending + + void OnSendReplicaBegin(GridMate::Replica* replica) override; + void OnSendReplicaEnd(GridMate::Replica* replica, const void* data, size_t len) override; + void OnSendReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, const void* data, size_t len) override; + void OnSendDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::DataSetBase* dataSet, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; + void OnSendRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; + + // CarrierDrillerBus + void OnIncomingConnection (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; + void OnFailedToConnect (GridMate::Carrier* carrier, + GridMate::ConnectionID id, + GridMate::CarrierDisconnectReason reason) override; + void OnConnectionEstablished (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; + void OnDisconnect (GridMate::Carrier* carrier, + GridMate::ConnectionID id, + GridMate::CarrierDisconnectReason reason) override; + void OnDriverError (GridMate::Carrier* carrier, + GridMate::ConnectionID id, + const GridMate::DriverError& error) override; + void OnSecurityError (GridMate::Carrier* carrier, + GridMate::ConnectionID id, + const GridMate::SecurityError& error) override; + void OnUpdateStatistics (const GridMate::string& address, + const GridMate::TrafficControl::Statistics& lastSecond, + const GridMate::TrafficControl::Statistics& lifeTime, + const GridMate::TrafficControl::Statistics& effectiveLastSecond, + const GridMate::TrafficControl::Statistics& effectiveLifeTime) override; + void OnConnectionStateChanged (GridMate::Carrier* carrier, + GridMate::ConnectionID id, + GridMate::Carrier::ConnectionStates newState) override; + + private: + + bool m_showServerReportWindow = false; + bool m_isTrackingMessages = false; + + AZStd::map m_sendingEntityReports{}; + EntityReporter m_currentSendingEntityReport; + + AZStd::map m_receivingEntityReports{}; + EntityReporter m_currentReceivingEntityReport; + + float m_replicatedStateKbpsWarn = 10.f; + float m_replicatedStateMaxSizeWarn = 30.f; + + void UpdateTrafficStatistics(); + AZStd::map m_lastSecondStats; + }; +} diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index 1611a3213d..b97fa053b2 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -53,6 +53,11 @@ namespace Multiplayer #endif } + void MultiplayerDebugSystemComponent::OnImGuiInitialize() + { + m_reporter = AZStd::make_unique(); + } + #ifdef IMGUI_ENABLED void MultiplayerDebugSystemComponent::OnImGuiMainMenuUpdate() { @@ -318,6 +323,12 @@ namespace Multiplayer ImGui::End(); } } + + + if (m_reporter) + { + m_reporter->OnImGuiUpdate(); + } } #endif } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h index 77daaf9b7d..3dbbd06d6f 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h @@ -9,6 +9,7 @@ #pragma once #include +#include #ifdef IMGUI_ENABLED # include @@ -42,6 +43,7 @@ namespace Multiplayer #ifdef IMGUI_ENABLED //! ImGui::ImGuiUpdateListenerBus overrides //! @{ + void OnImGuiInitialize() override; void OnImGuiMainMenuUpdate() override; void OnImGuiUpdate() override; //! @} @@ -49,5 +51,7 @@ namespace Multiplayer private: bool m_displayNetworkingStats = false; bool m_displayMultiplayerStats = false; + + AZStd::unique_ptr m_reporter; }; } diff --git a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake index 62bd632e7e..37a1c91640 100644 --- a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake @@ -7,6 +7,10 @@ # set(FILES + Source/Debug/MultiplayerDebugByteReporter.cpp + Source/Debug/MultiplayerDebugByteReporter.h + Source/Debug/MultiplayerDebugPerEntityReporter.cpp + Source/Debug/MultiplayerDebugPerEntityReporter.h Source/Debug/MultiplayerDebugModule.cpp Source/Debug/MultiplayerDebugModule.h Source/Debug/MultiplayerDebugSystemComponent.cpp From f29fd86a395812f07c28998758365e9e97b68d7f Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Mon, 26 Jul 2021 19:11:28 -0400 Subject: [PATCH 023/251] More converstion in progress Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../Components/MultiplayerComponent.h | 21 +- .../Include/Multiplayer/MultiplayerStats.h | 2 + .../Source/Components/NetBindComponent.cpp | 4 + .../Debug/MultiplayerDebugByteReporter.cpp | 17 +- .../MultiplayerDebugPerEntityInterface.h | 26 ++ .../MultiplayerDebugPerEntityReporter.cpp | 328 ++++++++++-------- .../Debug/MultiplayerDebugPerEntityReporter.h | 93 ++--- .../Code/Source/MultiplayerStats.cpp | 27 ++ .../Code/multiplayer_debug_files.cmake | 1 + 9 files changed, 306 insertions(+), 213 deletions(-) create mode 100644 Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h index 8526b6c70b..48590e5393 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h @@ -105,14 +105,15 @@ namespace Multiplayer template inline void SerializeNetworkPropertyHelper ( - AzNetworking::ISerializer& serializer, - bool modifyRecord, - AzNetworking::FixedSizeBitsetView& bitset, - int32_t bitIndex, - TYPE& value, - const char* name, - NetComponentId componentId, - PropertyIndex propertyIndex, + AzNetworking::ISerializer& serializer, + bool modifyRecord, + AzNetworking::FixedSizeBitsetView& bitset, + int32_t bitIndex, + TYPE& value, + const char* name, + AZ::EntityId entityId, + NetComponentId componentId, + PropertyIndex propertyIndex, MultiplayerStats& stats ) { @@ -133,11 +134,11 @@ namespace Multiplayer { if (modifyRecord) { - stats.RecordPropertyReceived(componentId, propertyIndex, updateSize); + stats.RecordPropertyReceived(entityId, componentId, propertyIndex, updateSize); } else { - stats.RecordPropertySent(componentId, propertyIndex, updateSize); + stats.RecordPropertySent(entityId, componentId, propertyIndex, updateSize); } } } diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h index d279355d7c..133cbb7aeb 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h @@ -50,6 +50,8 @@ namespace Multiplayer AZStd::vector m_componentStats; void ReserveComponentStats(NetComponentId netComponentId, uint16_t propertyCount, uint16_t rpcCount); + void RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName); + void RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName); void RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); void RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); void RecordRpcSent(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index e8da34fc7f..74091908e2 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -447,12 +447,16 @@ namespace Multiplayer bool NetBindComponent::SerializeStateDeltaMessage(ReplicationRecord& replicationRecord, AzNetworking::ISerializer& serializer) { + GetMultiplayer()->GetStats().RecordEntitySerializeStart(GetEntityId(), GetEntity()->GetName().c_str()); + bool success = true; for (auto iter = m_multiplayerSerializationComponentVector.begin(); iter != m_multiplayerSerializationComponentVector.end(); ++iter) { success &= (*iter)->SerializeStateDeltaMessage(replicationRecord, serializer); } + GetMultiplayer()->GetStats().RecordEntitySerializeStop(GetEntityId(), GetEntity()->GetName().c_str()); + return success; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp index 382bc70d9b..fd31298ad8 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -1,14 +1,11 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * 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 "MultiplayerDebugByteReporter.h" #include diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h new file mode 100644 index 0000000000..8cd94944b2 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +namespace MultiplayerDiagnostics +{ + class MultilayerIPerEntityStats + { + public: + virtual ~MultilayerIPerEntityStats(); + + virtual void RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName) = 0; + virtual void RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName) = 0; + virtual void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); + virtual void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); + }; +} diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index e60b800372..32ed7d5a59 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -1,18 +1,16 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * 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 "MultiplayerDebugPerEntityReporter.h" #include #include #include +#include #if defined(IMGUI_ENABLED) #include @@ -115,151 +113,151 @@ namespace MultiplayerDiagnostics MultiplayerDebugPerEntityReporter::MultiplayerDebugPerEntityReporter () { - GridMate::Debug::CarrierDrillerBus::Handler::BusConnect(); + //GridMate::Debug::CarrierDrillerBus::Handler::BusConnect(); } // -------------------------------------------------------------------------------------------- MultiplayerDebugPerEntityReporter::~MultiplayerDebugPerEntityReporter() { - GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); - GridMate::Debug::CarrierDrillerBus::Handler::BusDisconnect(); - } - - void MultiplayerDebugPerEntityReporter::OnReceiveReplicaBegin(GridMate::Replica*, const void*, size_t) - { - m_currentReceivingEntityReport.Reset(); - } - - void MultiplayerDebugPerEntityReporter::OnReceiveReplicaEnd(GridMate::Replica* replica) - { - m_receivingEntityReports[replica->GetDebugName()].Combine(m_currentReceivingEntityReport); - } - - void MultiplayerDebugPerEntityReporter::OnReceiveReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex) - { - AZ_UNUSED(chunk); - AZ_UNUSED(chunkIndex); - m_currentReceivingEntityReport.ReportFragmentEnd(); + /*GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); + GridMate::Debug::CarrierDrillerBus::Handler::BusDisconnect();*/ } - void MultiplayerDebugPerEntityReporter::OnReceiveDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, - GridMate::DataSetBase* dataSet, GridMate::PeerId, GridMate::PeerId, const void*, size_t len) - { - m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); - } - - void MultiplayerDebugPerEntityReporter::OnReceiveRpc (GridMate::ReplicaChunkBase* chunk, - AZ::u32 chunkIndex, - GridMate::Internal::RpcRequest* rpc, - GridMate::PeerId from, - GridMate::PeerId to, - const void* data, - size_t len) - { - AZ_UNUSED( from ); - AZ_UNUSED( to ); - AZ_UNUSED( data ); - - m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); - } - - void MultiplayerDebugPerEntityReporter::OnSendReplicaBegin (GridMate::Replica*) - { - m_currentSendingEntityReport.Reset(); - } - - void MultiplayerDebugPerEntityReporter::OnSendReplicaEnd (GridMate::Replica* replica, const void*, size_t) - { - m_sendingEntityReports[replica->GetDebugName()].Combine(m_currentSendingEntityReport); - } - - void MultiplayerDebugPerEntityReporter::OnSendReplicaChunkEnd (GridMate::ReplicaChunkBase* chunk, - AZ::u32 chunkIndex, - const void*, - size_t) - { - AZ_UNUSED(chunk); - AZ_UNUSED(chunkIndex); - m_currentSendingEntityReport.ReportFragmentEnd(); - } - - void MultiplayerDebugPerEntityReporter::OnSendDataSet (GridMate::ReplicaChunkBase* chunk, - AZ::u32 chunkIndex, - GridMate::DataSetBase* dataSet, - GridMate::PeerId, - GridMate::PeerId, - const void*, - size_t len) - { - m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); - } - - void MultiplayerDebugPerEntityReporter::OnSendRpc (GridMate::ReplicaChunkBase* chunk, - AZ::u32 chunkIndex, - GridMate::Internal::RpcRequest* rpc, - GridMate::PeerId, - GridMate::PeerId, - const void*, - size_t len) - { - m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); - } - - void MultiplayerDebugPerEntityReporter::OnIncomingConnection (GridMate::Carrier*, GridMate::ConnectionID) - { - } - - void MultiplayerDebugPerEntityReporter::OnFailedToConnect (GridMate::Carrier*, - GridMate::ConnectionID, - GridMate::CarrierDisconnectReason) - { - m_lastSecondStats.clear(); - } - - void MultiplayerDebugPerEntityReporter::OnConnectionEstablished (GridMate::Carrier*, GridMate::ConnectionID) - { - } - - void MultiplayerDebugPerEntityReporter::OnDisconnect (GridMate::Carrier*, - GridMate::ConnectionID, - GridMate::CarrierDisconnectReason) - { - /* - * CarrierDrillerBus doesn't provide enough information to correctly keep track of network traffic for all peers. - * This is a work around until that is fixed to at least not over report the bandwidth amount. - */ - m_lastSecondStats.clear(); - } - - void MultiplayerDebugPerEntityReporter::OnDriverError (GridMate::Carrier*, - GridMate::ConnectionID, - const GridMate::DriverError&) - { - m_lastSecondStats.clear(); - } - - void MultiplayerDebugPerEntityReporter::OnSecurityError (GridMate::Carrier*, - GridMate::ConnectionID, - const GridMate::SecurityError&) - { - m_lastSecondStats.clear(); - } - - void MultiplayerDebugPerEntityReporter::OnUpdateStatistics (const GridMate::string& address, - const GridMate::TrafficControl::Statistics&, - const GridMate::TrafficControl::Statistics&, - const GridMate::TrafficControl::Statistics& effectiveLastSecond, - const GridMate::TrafficControl::Statistics&) - { - m_lastSecondStats[address] = effectiveLastSecond; - } - - void MultiplayerDebugPerEntityReporter::OnConnectionStateChanged (GridMate::Carrier*, - GridMate::ConnectionID, - GridMate::Carrier::ConnectionStates) - { - m_lastSecondStats.clear(); - } + //void MultiplayerDebugPerEntityReporter::OnReceiveReplicaBegin(GridMate::Replica*, const void*, size_t) + //{ + // m_currentReceivingEntityReport.Reset(); + //} + + //void MultiplayerDebugPerEntityReporter::OnReceiveReplicaEnd(GridMate::Replica* replica) + //{ + // m_receivingEntityReports[replica->GetDebugName()].Combine(m_currentReceivingEntityReport); + //} + + //void MultiplayerDebugPerEntityReporter::OnReceiveReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex) + //{ + // AZ_UNUSED(chunk); + // AZ_UNUSED(chunkIndex); + // m_currentReceivingEntityReport.ReportFragmentEnd(); + //} + + //void MultiplayerDebugPerEntityReporter::OnReceiveDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, + // GridMate::DataSetBase* dataSet, GridMate::PeerId, GridMate::PeerId, const void*, size_t len) + //{ + // m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); + //} + + //void MultiplayerDebugPerEntityReporter::OnReceiveRpc (GridMate::ReplicaChunkBase* chunk, + // AZ::u32 chunkIndex, + // GridMate::Internal::RpcRequest* rpc, + // GridMate::PeerId from, + // GridMate::PeerId to, + // const void* data, + // size_t len) + //{ + // AZ_UNUSED( from ); + // AZ_UNUSED( to ); + // AZ_UNUSED( data ); + + // m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); + //} + + //void MultiplayerDebugPerEntityReporter::OnSendReplicaBegin (GridMate::Replica*) + //{ + // m_currentSendingEntityReport.Reset(); + //} + + //void MultiplayerDebugPerEntityReporter::OnSendReplicaEnd (GridMate::Replica* replica, const void*, size_t) + //{ + // m_sendingEntityReports[replica->GetDebugName()].Combine(m_currentSendingEntityReport); + //} + + //void MultiplayerDebugPerEntityReporter::OnSendReplicaChunkEnd (GridMate::ReplicaChunkBase* chunk, + // AZ::u32 chunkIndex, + // const void*, + // size_t) + //{ + // AZ_UNUSED(chunk); + // AZ_UNUSED(chunkIndex); + // m_currentSendingEntityReport.ReportFragmentEnd(); + //} + + //void MultiplayerDebugPerEntityReporter::OnSendDataSet (GridMate::ReplicaChunkBase* chunk, + // AZ::u32 chunkIndex, + // GridMate::DataSetBase* dataSet, + // GridMate::PeerId, + // GridMate::PeerId, + // const void*, + // size_t len) + //{ + // m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); + //} + + //void MultiplayerDebugPerEntityReporter::OnSendRpc (GridMate::ReplicaChunkBase* chunk, + // AZ::u32 chunkIndex, + // GridMate::Internal::RpcRequest* rpc, + // GridMate::PeerId, + // GridMate::PeerId, + // const void*, + // size_t len) + //{ + // m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); + //} + + //void MultiplayerDebugPerEntityReporter::OnIncomingConnection (GridMate::Carrier*, GridMate::ConnectionID) + //{ + //} + + //void MultiplayerDebugPerEntityReporter::OnFailedToConnect (GridMate::Carrier*, + // GridMate::ConnectionID, + // GridMate::CarrierDisconnectReason) + //{ + // m_lastSecondStats.clear(); + //} + + //void MultiplayerDebugPerEntityReporter::OnConnectionEstablished (GridMate::Carrier*, GridMate::ConnectionID) + //{ + //} + + //void MultiplayerDebugPerEntityReporter::OnDisconnect (GridMate::Carrier*, + // GridMate::ConnectionID, + // GridMate::CarrierDisconnectReason) + //{ + // /* + // * CarrierDrillerBus doesn't provide enough information to correctly keep track of network traffic for all peers. + // * This is a work around until that is fixed to at least not over report the bandwidth amount. + // */ + // m_lastSecondStats.clear(); + //} + + //void MultiplayerDebugPerEntityReporter::OnDriverError (GridMate::Carrier*, + // GridMate::ConnectionID, + // const GridMate::DriverError&) + //{ + // m_lastSecondStats.clear(); + //} + + //void MultiplayerDebugPerEntityReporter::OnSecurityError (GridMate::Carrier*, + // GridMate::ConnectionID, + // const GridMate::SecurityError&) + //{ + // m_lastSecondStats.clear(); + //} + + //void MultiplayerDebugPerEntityReporter::OnUpdateStatistics (const GridMate::string& address, + // const GridMate::TrafficControl::Statistics&, + // const GridMate::TrafficControl::Statistics&, + // const GridMate::TrafficControl::Statistics& effectiveLastSecond, + // const GridMate::TrafficControl::Statistics&) + //{ + // m_lastSecondStats[address] = effectiveLastSecond; + //} + + //void MultiplayerDebugPerEntityReporter::OnConnectionStateChanged (GridMate::Carrier*, + // GridMate::ConnectionID, + // GridMate::Carrier::ConnectionStates) + //{ + // m_lastSecondStats.clear(); + //} void MultiplayerDebugPerEntityReporter::UpdateTrafficStatistics() { @@ -320,11 +318,11 @@ namespace MultiplayerDiagnostics { if (m_isTrackingMessages) { - GridMate::Debug::ReplicaDrillerBus::Handler::BusConnect(); + //GridMate::Debug::ReplicaDrillerBus::Handler::BusConnect(); } else { - GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); + //GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); m_currentReceivingEntityReport.Reset(); m_receivingEntityReports.clear(); @@ -382,4 +380,34 @@ namespace MultiplayerDiagnostics } #endif } + + void MultiplayerDebugPerEntityReporter::RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName) + { + } + + void MultiplayerDebugPerEntityReporter::RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName) + { + } + + void MultiplayerDebugPerEntityReporter::RecordPropertySent( + AZ::EntityId entityId, + Multiplayer::NetComponentId netComponentId, + Multiplayer::PropertyIndex propertyId, + uint32_t totalBytes) + { + // TODO + } + + void MultiplayerDebugPerEntityReporter::RecordPropertyReceived( + Multiplayer::NetComponentId netComponentId, + Multiplayer::PropertyIndex propertyId, + uint32_t totalBytes) + { + if (Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + { + m_currentReceivingEntityReport.ReportField(static_cast(netComponentId), + componentRegistry->GetComponentName(netComponentId), + componentRegistry->GetComponentPropertyName(netComponentId, propertyId), totalBytes); + } + } } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h index 96cfadb14d..c89c889813 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h @@ -1,18 +1,20 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * 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 "MultiplayerDebugByteReporter.h" + +#include +#include +#include #include +#include namespace MultiplayerDiagnostics { @@ -20,55 +22,60 @@ namespace MultiplayerDiagnostics * \brief GridMate network live analysis tool via ImGui. */ class MultiplayerDebugPerEntityReporter - : public GridMate::Debug::ReplicaDrillerBus::Handler - , public GridMate::Debug::CarrierDrillerBus::Handler + : public AZ::Interface::Registrar { public: MultiplayerDebugPerEntityReporter(); - virtual ~MultiplayerDebugPerEntityReporter(); + ~MultiplayerDebugPerEntityReporter() override; // main update loop void OnImGuiUpdate(); - // ReplicaDrillerBus - receive + //! MultilayerIPerEntityStats + // @{ + void RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName); + void RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName); + void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; + void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; + // }@ - void OnReceiveReplicaBegin(GridMate::Replica* replica, const void* data, size_t len) override; - void OnReceiveReplicaEnd(GridMate::Replica* replica) override; + /*void OnReceiveReplicaBegin(AZ::EntityId entityId, const void* data, size_t len) override; + void OnReceiveReplicaEnd(AZ::EntityId entityId) override; void OnReceiveReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex) override; void OnReceiveDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::DataSetBase* dataSet, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; - void OnReceiveRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; + void OnReceiveRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override;*/ // ReplicaDrillerBus - sending - void OnSendReplicaBegin(GridMate::Replica* replica) override; - void OnSendReplicaEnd(GridMate::Replica* replica, const void* data, size_t len) override; + /*void OnSendReplicaBegin(AZ::EntityId entityId) override; + void OnSendReplicaEnd(AZ::EntityId entityId, const void* data, size_t len) override; void OnSendReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, const void* data, size_t len) override; void OnSendDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::DataSetBase* dataSet, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; - void OnSendRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; + void OnSendRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override;*/ - // CarrierDrillerBus - void OnIncomingConnection (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; - void OnFailedToConnect (GridMate::Carrier* carrier, - GridMate::ConnectionID id, - GridMate::CarrierDisconnectReason reason) override; - void OnConnectionEstablished (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; - void OnDisconnect (GridMate::Carrier* carrier, - GridMate::ConnectionID id, - GridMate::CarrierDisconnectReason reason) override; - void OnDriverError (GridMate::Carrier* carrier, - GridMate::ConnectionID id, - const GridMate::DriverError& error) override; - void OnSecurityError (GridMate::Carrier* carrier, - GridMate::ConnectionID id, - const GridMate::SecurityError& error) override; - void OnUpdateStatistics (const GridMate::string& address, - const GridMate::TrafficControl::Statistics& lastSecond, - const GridMate::TrafficControl::Statistics& lifeTime, - const GridMate::TrafficControl::Statistics& effectiveLastSecond, - const GridMate::TrafficControl::Statistics& effectiveLifeTime) override; - void OnConnectionStateChanged (GridMate::Carrier* carrier, - GridMate::ConnectionID id, - GridMate::Carrier::ConnectionStates newState) override; + //// CarrierDrillerBus + //void OnIncomingConnection (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; + //void OnFailedToConnect (GridMate::Carrier* carrier, + // GridMate::ConnectionID id, + // GridMate::CarrierDisconnectReason reason) override; + //void OnConnectionEstablished (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; + //void OnDisconnect (GridMate::Carrier* carrier, + // GridMate::ConnectionID id, + // GridMate::CarrierDisconnectReason reason) override; + //void OnDriverError (GridMate::Carrier* carrier, + // GridMate::ConnectionID id, + // const GridMate::DriverError& error) override; + //void OnSecurityError (GridMate::Carrier* carrier, + // GridMate::ConnectionID id, + // const GridMate::SecurityError& error) override; + //void OnUpdateStatistics (const GridMate::string& address, + // const GridMate::TrafficControl::Statistics& lastSecond, + // const GridMate::TrafficControl::Statistics& lifeTime, + // const GridMate::TrafficControl::Statistics& effectiveLastSecond, + // const GridMate::TrafficControl::Statistics& effectiveLifeTime) override; + //void OnConnectionStateChanged (GridMate::Carrier* carrier, + // GridMate::ConnectionID id, + // GridMate::Carrier::ConnectionStates newState) override; private: diff --git a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp index 6ee9f09cf7..b3236fbf77 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp @@ -6,6 +6,7 @@ * */ +#include #include namespace Multiplayer @@ -29,8 +30,29 @@ namespace Multiplayer m_componentStats[netComponentIndex].m_rpcsRecv.resize(rpcCount); } + void MultiplayerStats::RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName) + { + if (auto* perEntityStats = AZ::Interface::Get()) + { + perEntityStats->RecordEntitySerializeStart(entityId, entityName); + } + } + + void MultiplayerStats::RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName) + { + if (auto* perEntityStats = AZ::Interface::Get()) + { + perEntityStats->RecordEntitySerializeStop(entityId, entityName); + } + } + void MultiplayerStats::RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes) { + if (auto* perEntityStats = AZ::Interface::Get()) + { + perEntityStats->RecordPropertySent(netComponentId, propertyId, totalBytes); + } + const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t propertyIndex = aznumeric_cast(propertyId); m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_totalCalls++; @@ -41,6 +63,11 @@ namespace Multiplayer void MultiplayerStats::RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes) { + if (auto* perEntityStats = AZ::Interface::Get()) + { + perEntityStats->RecordPropertyReceived(netComponentId, propertyId, totalBytes); + } + const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t propertyIndex = aznumeric_cast(propertyId); m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_totalCalls++; diff --git a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake index 37a1c91640..d333269a1d 100644 --- a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake @@ -9,6 +9,7 @@ set(FILES Source/Debug/MultiplayerDebugByteReporter.cpp Source/Debug/MultiplayerDebugByteReporter.h + Source/Debug/MultiplayerDebugPerEntityInterface.h Source/Debug/MultiplayerDebugPerEntityReporter.cpp Source/Debug/MultiplayerDebugPerEntityReporter.h Source/Debug/MultiplayerDebugModule.cpp From a2f3066fa36d0cb1e817f6a7517f067854e11ba9 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Mon, 26 Jul 2021 21:59:19 -0400 Subject: [PATCH 024/251] Imgui per entity works Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- Gems/Multiplayer/Code/CMakeLists.txt | 2 +- .../Components/MultiplayerComponent.h | 5 +- .../Include/Multiplayer/MultiplayerStats.h | 5 +- .../Source/Components/NetBindComponent.cpp | 7 +- .../Debug/MultiplayerDebugByteReporter.cpp | 2 + .../Debug/MultiplayerDebugByteReporter.h | 17 +- .../MultiplayerDebugPerEntityInterface.h | 14 +- .../MultiplayerDebugPerEntityReporter.cpp | 335 ++++-------------- .../Debug/MultiplayerDebugPerEntityReporter.h | 57 +-- .../Debug/MultiplayerDebugSystemComponent.cpp | 14 +- .../Debug/MultiplayerDebugSystemComponent.h | 1 + .../Code/Source/MultiplayerStats.cpp | 29 +- .../EntityReplication/EntityReplicator.cpp | 9 +- 13 files changed, 154 insertions(+), 343 deletions(-) diff --git a/Gems/Multiplayer/Code/CMakeLists.txt b/Gems/Multiplayer/Code/CMakeLists.txt index 96527fbfc4..e8b38c8799 100644 --- a/Gems/Multiplayer/Code/CMakeLists.txt +++ b/Gems/Multiplayer/Code/CMakeLists.txt @@ -79,7 +79,7 @@ ly_add_target( # The "Multiplayer" target is used by clients and servers, Debug is used only on clients. ly_create_alias(NAME Multiplayer.Clients NAMESPACE Gem TARGETS Gem::Multiplayer Gem::Multiplayer.Debug) -ly_create_alias(NAME Multiplayer.Servers NAMESPACE Gem TARGETS Gem::Multiplayer) +ly_create_alias(NAME Multiplayer.Servers NAMESPACE Gem TARGETS Gem::Multiplayer Gem::Multiplayer.Debug) if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h index 48590e5393..64ceb6e16f 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerComponent.h @@ -111,7 +111,6 @@ namespace Multiplayer int32_t bitIndex, TYPE& value, const char* name, - AZ::EntityId entityId, NetComponentId componentId, PropertyIndex propertyIndex, MultiplayerStats& stats @@ -134,11 +133,11 @@ namespace Multiplayer { if (modifyRecord) { - stats.RecordPropertyReceived(entityId, componentId, propertyIndex, updateSize); + stats.RecordPropertyReceived(componentId, propertyIndex, updateSize); } else { - stats.RecordPropertySent(entityId, componentId, propertyIndex, updateSize); + stats.RecordPropertySent(componentId, propertyIndex, updateSize); } } } diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h index 133cbb7aeb..1299fe174d 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h @@ -50,8 +50,9 @@ namespace Multiplayer AZStd::vector m_componentStats; void ReserveComponentStats(NetComponentId netComponentId, uint16_t propertyCount, uint16_t rpcCount); - void RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName); - void RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName); + void RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName); + void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, NetComponentId netComponentId); + void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName); void RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); void RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); void RecordRpcSent(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index 74091908e2..cfaeaedeff 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -447,15 +447,18 @@ namespace Multiplayer bool NetBindComponent::SerializeStateDeltaMessage(ReplicationRecord& replicationRecord, AzNetworking::ISerializer& serializer) { - GetMultiplayer()->GetStats().RecordEntitySerializeStart(GetEntityId(), GetEntity()->GetName().c_str()); + auto& stats = GetMultiplayer()->GetStats(); + stats.RecordEntitySerializeStart(serializer.GetSerializerMode(), GetEntityId(), GetEntity()->GetName().c_str()); bool success = true; for (auto iter = m_multiplayerSerializationComponentVector.begin(); iter != m_multiplayerSerializationComponentVector.end(); ++iter) { success &= (*iter)->SerializeStateDeltaMessage(replicationRecord, serializer); + + stats.RecordComponentSerializeEnd(serializer.GetSerializerMode(), (*iter)->GetNetComponentId()); } - GetMultiplayer()->GetStats().RecordEntitySerializeStop(GetEntityId(), GetEntity()->GetName().c_str()); + stats.RecordEntitySerializeStop(serializer.GetSerializerMode(), GetEntityId(), GetEntity()->GetName().c_str()); return success; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp index fd31298ad8..2c0a8b5db1 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -12,6 +12,8 @@ #include #include +#pragma optimize("", off) + namespace MultiplayerDiagnostics { void MultiplayerDebugByteReporter::ReportBytes(size_t byteSize) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h index 7e6a04569d..8977c2e6ba 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h @@ -1,14 +1,11 @@ /* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ + * 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 diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h index 8cd94944b2..94bc11dafa 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h @@ -13,14 +13,16 @@ namespace MultiplayerDiagnostics { - class MultilayerIPerEntityStats + class MultiplayerIPerEntityStats { public: - virtual ~MultilayerIPerEntityStats(); + AZ_RTTI(MultiplayerIPerEntityStats, "{91A1E4F0-8AE6-44B2-89DF-DA34134C408A}"); - virtual void RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName) = 0; - virtual void RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName) = 0; - virtual void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); - virtual void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); + virtual void RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) = 0; + virtual void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId) = 0; + virtual void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) = 0; + virtual void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) = 0; + virtual void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) = 0; + virtual void RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) = 0; }; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index 32ed7d5a59..c839083f63 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -7,23 +7,22 @@ */ #include "MultiplayerDebugPerEntityReporter.h" -#include -#include -#include #include #if defined(IMGUI_ENABLED) #include #endif +#pragma optimize("", off) + namespace MultiplayerDiagnostics { #if defined(IMGUI_ENABLED) static const ImVec4 k_ImGuiTomato = ImVec4(1.0f, 0.4f, 0.3f, 1.0f); - static const ImVec4 k_ImGuiKhaki = ImVec4(0.9f, 0.8f, 0.5f, 1.0f); - static const ImVec4 k_ImGuiCyan = ImVec4(0.5f, 1.0f, 1.0f, 1.0f); - static const ImVec4 k_ImGuiDusk = ImVec4(0.7f, 0.7f, 1.0f, 1.0f); - static const ImVec4 k_ImGuiWhite = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + static const ImVec4 k_ImGuiKhaki = ImVec4(0.9f, 0.8f, 0.5f, 1.0f); + static const ImVec4 k_ImGuiCyan = ImVec4(0.5f, 1.0f, 1.0f, 1.0f); + static const ImVec4 k_ImGuiDusk = ImVec4(0.7f, 0.7f, 1.0f, 1.0f); + static const ImVec4 k_ImGuiWhite = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // -------------------------------------------------------------------------------------------- template @@ -111,291 +110,103 @@ namespace MultiplayerDiagnostics } #endif - MultiplayerDebugPerEntityReporter::MultiplayerDebugPerEntityReporter () - { - //GridMate::Debug::CarrierDrillerBus::Handler::BusConnect(); - } - - // -------------------------------------------------------------------------------------------- - MultiplayerDebugPerEntityReporter::~MultiplayerDebugPerEntityReporter() - { - /*GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); - GridMate::Debug::CarrierDrillerBus::Handler::BusDisconnect();*/ - } - - //void MultiplayerDebugPerEntityReporter::OnReceiveReplicaBegin(GridMate::Replica*, const void*, size_t) - //{ - // m_currentReceivingEntityReport.Reset(); - //} - - //void MultiplayerDebugPerEntityReporter::OnReceiveReplicaEnd(GridMate::Replica* replica) - //{ - // m_receivingEntityReports[replica->GetDebugName()].Combine(m_currentReceivingEntityReport); - //} - - //void MultiplayerDebugPerEntityReporter::OnReceiveReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex) - //{ - // AZ_UNUSED(chunk); - // AZ_UNUSED(chunkIndex); - // m_currentReceivingEntityReport.ReportFragmentEnd(); - //} - - //void MultiplayerDebugPerEntityReporter::OnReceiveDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, - // GridMate::DataSetBase* dataSet, GridMate::PeerId, GridMate::PeerId, const void*, size_t len) - //{ - // m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); - //} - - //void MultiplayerDebugPerEntityReporter::OnReceiveRpc (GridMate::ReplicaChunkBase* chunk, - // AZ::u32 chunkIndex, - // GridMate::Internal::RpcRequest* rpc, - // GridMate::PeerId from, - // GridMate::PeerId to, - // const void* data, - // size_t len) - //{ - // AZ_UNUSED( from ); - // AZ_UNUSED( to ); - // AZ_UNUSED( data ); - - // m_currentReceivingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); - //} - - //void MultiplayerDebugPerEntityReporter::OnSendReplicaBegin (GridMate::Replica*) - //{ - // m_currentSendingEntityReport.Reset(); - //} - - //void MultiplayerDebugPerEntityReporter::OnSendReplicaEnd (GridMate::Replica* replica, const void*, size_t) - //{ - // m_sendingEntityReports[replica->GetDebugName()].Combine(m_currentSendingEntityReport); - //} - - //void MultiplayerDebugPerEntityReporter::OnSendReplicaChunkEnd (GridMate::ReplicaChunkBase* chunk, - // AZ::u32 chunkIndex, - // const void*, - // size_t) - //{ - // AZ_UNUSED(chunk); - // AZ_UNUSED(chunkIndex); - // m_currentSendingEntityReport.ReportFragmentEnd(); - //} - - //void MultiplayerDebugPerEntityReporter::OnSendDataSet (GridMate::ReplicaChunkBase* chunk, - // AZ::u32 chunkIndex, - // GridMate::DataSetBase* dataSet, - // GridMate::PeerId, - // GridMate::PeerId, - // const void*, - // size_t len) - //{ - // m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetDataSetName(chunk, dataSet), len); - //} - - //void MultiplayerDebugPerEntityReporter::OnSendRpc (GridMate::ReplicaChunkBase* chunk, - // AZ::u32 chunkIndex, - // GridMate::Internal::RpcRequest* rpc, - // GridMate::PeerId, - // GridMate::PeerId, - // const void*, - // size_t len) - //{ - // m_currentSendingEntityReport.ReportField(chunkIndex, chunk->GetDescriptor()->GetChunkName(), chunk->GetDescriptor()->GetRpcName(chunk, rpc->m_rpc), len); - //} - - //void MultiplayerDebugPerEntityReporter::OnIncomingConnection (GridMate::Carrier*, GridMate::ConnectionID) - //{ - //} - - //void MultiplayerDebugPerEntityReporter::OnFailedToConnect (GridMate::Carrier*, - // GridMate::ConnectionID, - // GridMate::CarrierDisconnectReason) - //{ - // m_lastSecondStats.clear(); - //} - - //void MultiplayerDebugPerEntityReporter::OnConnectionEstablished (GridMate::Carrier*, GridMate::ConnectionID) - //{ - //} - - //void MultiplayerDebugPerEntityReporter::OnDisconnect (GridMate::Carrier*, - // GridMate::ConnectionID, - // GridMate::CarrierDisconnectReason) - //{ - // /* - // * CarrierDrillerBus doesn't provide enough information to correctly keep track of network traffic for all peers. - // * This is a work around until that is fixed to at least not over report the bandwidth amount. - // */ - // m_lastSecondStats.clear(); - //} - - //void MultiplayerDebugPerEntityReporter::OnDriverError (GridMate::Carrier*, - // GridMate::ConnectionID, - // const GridMate::DriverError&) - //{ - // m_lastSecondStats.clear(); - //} - - //void MultiplayerDebugPerEntityReporter::OnSecurityError (GridMate::Carrier*, - // GridMate::ConnectionID, - // const GridMate::SecurityError&) - //{ - // m_lastSecondStats.clear(); - //} - - //void MultiplayerDebugPerEntityReporter::OnUpdateStatistics (const GridMate::string& address, - // const GridMate::TrafficControl::Statistics&, - // const GridMate::TrafficControl::Statistics&, - // const GridMate::TrafficControl::Statistics& effectiveLastSecond, - // const GridMate::TrafficControl::Statistics&) - //{ - // m_lastSecondStats[address] = effectiveLastSecond; - //} - - //void MultiplayerDebugPerEntityReporter::OnConnectionStateChanged (GridMate::Carrier*, - // GridMate::ConnectionID, - // GridMate::Carrier::ConnectionStates) - //{ - // m_lastSecondStats.clear(); - //} - - void MultiplayerDebugPerEntityReporter::UpdateTrafficStatistics() - { -#if defined(IMGUI_ENABLED) - AZ::u32 dataReceived = 0, dataSent = 0; - - for (auto& perConnection : m_lastSecondStats) - { - dataReceived += perConnection.second.m_dataReceived; - dataSent += perConnection.second.m_dataSend; - } - - if (dataReceived !=0 || dataSent != 0) - { - ImGui::Text("Total bandwidth: Sent %u kbps Received %u kbps.", dataSent * 8 / 1000, dataReceived * 8 / 1000); - } - else - { - ImGui::Text("Total bandwidth: Sent -- kbps Received -- kbps."); - } -#endif - } - // -------------------------------------------------------------------------------------------- void MultiplayerDebugPerEntityReporter::OnImGuiUpdate() { #if defined(IMGUI_ENABLED) - if (ImGui::BeginMainMenuBar()) + static ImGuiTextFilter filter; + filter.Draw(); + + if (ImGui::CollapsingHeader("Receiving Entities")) { - if (ImGui::BeginMenu("GridMate")) + for (auto& entityPair : m_receivingEntityReports) { - if (m_showServerReportWindow) + if (!filter.PassFilter(entityPair.first.c_str())) { - if (ImGui::MenuItem("Hide Multiplayer Analytics Window")) - { - m_showServerReportWindow = false; - } + continue; } - else if (ImGui::MenuItem("Show Multiplayer Analytics Window")) + + ImGui::Separator(); + if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) { - m_showServerReportWindow = true; + DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); + ImGui::TreePop(); } - - ImGui::End(); } - - ImGui::EndMainMenuBar(); } - if (m_showServerReportWindow) + if (ImGui::CollapsingHeader("Sending Entities")) { - if (ImGui::Begin("Multiplayer Analytics", &m_showServerReportWindow)) + for (auto& entityPair : m_sendingEntityReports) { - // General carrier stats - UpdateTrafficStatistics(); - - if (ImGui::Checkbox("Analyze network traffic", &m_isTrackingMessages)) + if (!filter.PassFilter(entityPair.first.c_str())) { - if (m_isTrackingMessages) - { - //GridMate::Debug::ReplicaDrillerBus::Handler::BusConnect(); - } - else - { - //GridMate::Debug::ReplicaDrillerBus::Handler::BusDisconnect(); - - m_currentReceivingEntityReport.Reset(); - m_receivingEntityReports.clear(); - - m_currentSendingEntityReport.Reset(); - m_sendingEntityReports.clear(); - } + continue; } - if (m_isTrackingMessages) + ImGui::Separator(); + if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) { - ImGui::Separator(); - - static ImGuiTextFilter filter; - filter.Draw(); - - if (ImGui::CollapsingHeader("Received replicas per type")) - { - for (auto& entityPair : m_receivingEntityReports) - { - if (!filter.PassFilter(entityPair.first.c_str())) - { - continue; - } - - ImGui::Separator(); - if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) - { - DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); - ImGui::TreePop(); - } - } - } - - if (ImGui::CollapsingHeader("Sent replicas per type")) - { - for (auto& entityPair : m_sendingEntityReports) - { - if (!filter.PassFilter(entityPair.first.c_str())) - { - continue; - } - - ImGui::Separator(); - if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) - { - DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); - ImGui::TreePop(); - } - } - } + DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); + ImGui::TreePop(); } } - ImGui::End(); } #endif } - void MultiplayerDebugPerEntityReporter::RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName) + void MultiplayerDebugPerEntityReporter::RecordEntitySerializeStart(AzNetworking::SerializerMode mode, + [[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] const char* entityName) + { + switch (mode) + { + case AzNetworking::SerializerMode::ReadFromObject: + m_currentSendingEntityReport.Reset(); + break; + case AzNetworking::SerializerMode::WriteToObject: + m_currentReceivingEntityReport.Reset(); + break; + } + } + + void MultiplayerDebugPerEntityReporter::RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, [[maybe_unused]] Multiplayer::NetComponentId netComponentId) { + switch (mode) + { + case AzNetworking::SerializerMode::ReadFromObject: + m_currentSendingEntityReport.ReportFragmentEnd(); + break; + case AzNetworking::SerializerMode::WriteToObject: + m_currentReceivingEntityReport.ReportFragmentEnd(); + break; + } } - void MultiplayerDebugPerEntityReporter::RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName) + void MultiplayerDebugPerEntityReporter::RecordEntitySerializeStop(AzNetworking::SerializerMode mode, + [[maybe_unused]] AZ::EntityId entityId, const char* entityName) { + switch (mode) + { + case AzNetworking::SerializerMode::ReadFromObject: + m_sendingEntityReports[entityName].Combine(m_currentSendingEntityReport); + break; + case AzNetworking::SerializerMode::WriteToObject: + m_receivingEntityReports[entityName].Combine(m_currentReceivingEntityReport); + break; + } } void MultiplayerDebugPerEntityReporter::RecordPropertySent( - AZ::EntityId entityId, Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) { - // TODO + if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + { + m_currentSendingEntityReport.ReportField(static_cast(netComponentId), + componentRegistry->GetComponentName(netComponentId), + componentRegistry->GetComponentPropertyName(netComponentId, propertyId), totalBytes); + } } void MultiplayerDebugPerEntityReporter::RecordPropertyReceived( @@ -403,11 +214,21 @@ namespace MultiplayerDiagnostics Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) { - if (Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) { m_currentReceivingEntityReport.ReportField(static_cast(netComponentId), componentRegistry->GetComponentName(netComponentId), componentRegistry->GetComponentPropertyName(netComponentId, propertyId), totalBytes); } } + + void MultiplayerDebugPerEntityReporter::RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) + { + if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + { + m_currentSendingEntityReport.ReportField(static_cast(netComponentId), + componentRegistry->GetComponentName(netComponentId), + componentRegistry->GetComponentRpcName(netComponentId, rpcId), totalBytes); + } + } } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h index c89c889813..121c4131ed 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h @@ -7,7 +7,6 @@ */ #pragma once -#include #include "MultiplayerDebugByteReporter.h" #include @@ -22,66 +21,27 @@ namespace MultiplayerDiagnostics * \brief GridMate network live analysis tool via ImGui. */ class MultiplayerDebugPerEntityReporter - : public AZ::Interface::Registrar + : public AZ::Interface::Registrar { public: - MultiplayerDebugPerEntityReporter(); - ~MultiplayerDebugPerEntityReporter() override; + MultiplayerDebugPerEntityReporter() = default; + ~MultiplayerDebugPerEntityReporter() override = default; // main update loop void OnImGuiUpdate(); //! MultilayerIPerEntityStats // @{ - void RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName); - void RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName); + void RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) override; + void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId) override; + void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) override; void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; + void RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) override; // }@ - /*void OnReceiveReplicaBegin(AZ::EntityId entityId, const void* data, size_t len) override; - void OnReceiveReplicaEnd(AZ::EntityId entityId) override; - void OnReceiveReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex) override; - void OnReceiveDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::DataSetBase* dataSet, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; - void OnReceiveRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override;*/ - - // ReplicaDrillerBus - sending - - /*void OnSendReplicaBegin(AZ::EntityId entityId) override; - void OnSendReplicaEnd(AZ::EntityId entityId, const void* data, size_t len) override; - void OnSendReplicaChunkEnd(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, const void* data, size_t len) override; - void OnSendDataSet(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::DataSetBase* dataSet, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override; - void OnSendRpc(GridMate::ReplicaChunkBase* chunk, AZ::u32 chunkIndex, GridMate::Internal::RpcRequest* rpc, GridMate::PeerId from, GridMate::PeerId to, const void* data, size_t len) override;*/ - - //// CarrierDrillerBus - //void OnIncomingConnection (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; - //void OnFailedToConnect (GridMate::Carrier* carrier, - // GridMate::ConnectionID id, - // GridMate::CarrierDisconnectReason reason) override; - //void OnConnectionEstablished (GridMate::Carrier* carrier, GridMate::ConnectionID id) override; - //void OnDisconnect (GridMate::Carrier* carrier, - // GridMate::ConnectionID id, - // GridMate::CarrierDisconnectReason reason) override; - //void OnDriverError (GridMate::Carrier* carrier, - // GridMate::ConnectionID id, - // const GridMate::DriverError& error) override; - //void OnSecurityError (GridMate::Carrier* carrier, - // GridMate::ConnectionID id, - // const GridMate::SecurityError& error) override; - //void OnUpdateStatistics (const GridMate::string& address, - // const GridMate::TrafficControl::Statistics& lastSecond, - // const GridMate::TrafficControl::Statistics& lifeTime, - // const GridMate::TrafficControl::Statistics& effectiveLastSecond, - // const GridMate::TrafficControl::Statistics& effectiveLifeTime) override; - //void OnConnectionStateChanged (GridMate::Carrier* carrier, - // GridMate::ConnectionID id, - // GridMate::Carrier::ConnectionStates newState) override; - private: - bool m_showServerReportWindow = false; - bool m_isTrackingMessages = false; - AZStd::map m_sendingEntityReports{}; EntityReporter m_currentSendingEntityReport; @@ -90,8 +50,5 @@ namespace MultiplayerDiagnostics float m_replicatedStateKbpsWarn = 10.f; float m_replicatedStateMaxSizeWarn = 30.f; - - void UpdateTrafficStatistics(); - AZStd::map m_lastSecondStats; }; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index b97fa053b2..73afc45271 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -13,6 +13,8 @@ #include #include +#pragma optimize("", off) + namespace Multiplayer { void MultiplayerDebugSystemComponent::Reflect(AZ::ReflectContext* context) @@ -65,6 +67,7 @@ namespace Multiplayer { ImGui::Checkbox("Networking Stats", &m_displayNetworkingStats); ImGui::Checkbox("Multiplayer Stats", &m_displayMultiplayerStats); + ImGui::Checkbox("Multiplayer Per Entity Stats", &m_displayPerEntityStats); ImGui::EndMenu(); } } @@ -324,10 +327,15 @@ namespace Multiplayer } } - - if (m_reporter) + if (m_displayPerEntityStats) { - m_reporter->OnImGuiUpdate(); + if (ImGui::Begin("Multiplayer Per Entity Analytics", &m_displayPerEntityStats)) + { + if (m_reporter) + { + m_reporter->OnImGuiUpdate(); + } + } } } #endif diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h index 3dbbd06d6f..4972ec6bdf 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h @@ -51,6 +51,7 @@ namespace Multiplayer private: bool m_displayNetworkingStats = false; bool m_displayMultiplayerStats = false; + bool m_displayPerEntityStats = false; AZStd::unique_ptr m_reporter; }; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp index b3236fbf77..fd1b6a329d 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp @@ -30,25 +30,33 @@ namespace Multiplayer m_componentStats[netComponentIndex].m_rpcsRecv.resize(rpcCount); } - void MultiplayerStats::RecordEntitySerializeStart(AZ::EntityId entityId, const char* entityName) + void MultiplayerStats::RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) { - if (auto* perEntityStats = AZ::Interface::Get()) + if (auto* perEntityStats = AZ::Interface::Get()) { - perEntityStats->RecordEntitySerializeStart(entityId, entityName); + perEntityStats->RecordEntitySerializeStart(mode, entityId, entityName); } } - void MultiplayerStats::RecordEntitySerializeStop(AZ::EntityId entityId, const char* entityName) + void MultiplayerStats::RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, NetComponentId netComponentId) { - if (auto* perEntityStats = AZ::Interface::Get()) + if (auto* perEntityStats = AZ::Interface::Get()) { - perEntityStats->RecordEntitySerializeStop(entityId, entityName); + perEntityStats->RecordComponentSerializeEnd(mode, netComponentId); + } + } + + void MultiplayerStats::RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) + { + if (auto* perEntityStats = AZ::Interface::Get()) + { + perEntityStats->RecordEntitySerializeStop(mode, entityId, entityName); } } void MultiplayerStats::RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes) { - if (auto* perEntityStats = AZ::Interface::Get()) + if (auto* perEntityStats = AZ::Interface::Get()) { perEntityStats->RecordPropertySent(netComponentId, propertyId, totalBytes); } @@ -63,7 +71,7 @@ namespace Multiplayer void MultiplayerStats::RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes) { - if (auto* perEntityStats = AZ::Interface::Get()) + if (auto* perEntityStats = AZ::Interface::Get()) { perEntityStats->RecordPropertyReceived(netComponentId, propertyId, totalBytes); } @@ -78,6 +86,11 @@ namespace Multiplayer void MultiplayerStats::RecordRpcSent(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes) { + if (auto* perEntityStats = AZ::Interface::Get()) + { + perEntityStats->RecordRpcSent(netComponentId, rpcId, totalBytes); + } + const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t rpcIndex = aznumeric_cast(rpcId); m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_totalCalls++; diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 93fd3ea652..2afadbe4a4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -30,6 +30,8 @@ #include +#pragma optimize("", off) + namespace Multiplayer { EntityReplicator::EntityReplicator @@ -441,7 +443,12 @@ namespace Multiplayer { // Received rpc metrics, log rpc sent, number of bytes, and the componentId/rpcId for bandwidth metrics MultiplayerStats& stats = GetMultiplayer()->GetStats(); + stats.RecordEntitySerializeStart(AzNetworking::SerializerMode::ReadFromObject, + GetEntityHandle().GetEntity()->GetId(), GetEntityHandle().GetEntity()->GetName().c_str()); stats.RecordRpcSent(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); + stats.RecordComponentSerializeEnd(AzNetworking::SerializerMode::ReadFromObject, entityRpcMessage.GetComponentId()); + stats.RecordEntitySerializeStop(AzNetworking::SerializerMode::ReadFromObject, + GetEntityHandle().GetEntity()->GetId(), GetEntityHandle().GetEntity()->GetName().c_str()); m_replicationManager.AddDeferredRpcMessage(entityRpcMessage); } @@ -515,7 +522,7 @@ namespace Multiplayer && (GetRemoteNetworkRole() == NetEntityRole::Server)) { // We are on a server, and we received this message from another server, therefore we should forward this to our autonomous player - // This can occur if we've recently migrated + // This can occur if we've recently migrated result = RpcValidationResult::ForwardToAutonomous; } } From 59f65f265653cc73abeb2db3b94fb8b8bf64a231 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Mon, 26 Jul 2021 23:45:09 -0400 Subject: [PATCH 025/251] Refactored to store entities by entity ids Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../Debug/MultiplayerDebugByteReporter.cpp | 20 +----------------- .../Debug/MultiplayerDebugByteReporter.h | 10 +++++++-- .../MultiplayerDebugPerEntityReporter.cpp | 21 +++++++++++-------- .../Debug/MultiplayerDebugPerEntityReporter.h | 4 ++-- 4 files changed, 23 insertions(+), 32 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp index 2c0a8b5db1..5e912612b7 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -163,25 +163,6 @@ namespace MultiplayerDiagnostics MultiplayerDebugByteReporter::AggregateBytes(byteSize); } - void EntityReporter::ReportDirtyBits(AZ::u32 index, const char* componentName, size_t byteSize) - { - const char* const prefix = "MB::"; - if (strncmp(prefix, componentName, 4) == 0) - { - componentName += strlen(prefix); - } - - if (m_currentComponentReport == nullptr) - { - std::stringstream component; - component << "[" << std::setw(2) << std::setfill('0') << static_cast(index) << "]" << " " << componentName; - m_currentComponentReport = &m_componentReports[component.str().c_str()]; - } - - m_currentComponentReport->ReportDirtyBits(byteSize); - m_gdeDirtyBytes.AggregateBytes(byteSize); - } - void EntityReporter::ReportFragmentEnd() { if (m_currentComponentReport) @@ -203,6 +184,7 @@ namespace MultiplayerDiagnostics m_componentReports[componentIter.first].Combine(componentIter.second); } + SetEntityName(other.GetEntityName()); m_gdeDirtyBytes.Combine(other.m_gdeDirtyBytes); } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h index 8977c2e6ba..3cef9caaac 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h @@ -54,7 +54,6 @@ namespace MultiplayerDiagnostics ComponentReporter() = default; void ReportField(const char* fieldName, size_t byteSize); - void ReportDirtyBits(size_t byteSize) { m_componentDirtyBytes.AggregateBytes(byteSize); } void ReportFragmentEnd(); using Report = AZStd::pair; @@ -75,12 +74,18 @@ namespace MultiplayerDiagnostics EntityReporter() = default; void ReportField(AZ::u32 index, const char* componentName, const char* fieldName, size_t byteSize); - void ReportDirtyBits(AZ::u32 index, const char* componentName, size_t byteSize); void ReportFragmentEnd(); void Combine(const EntityReporter& other); void Reset() override; + const char* GetEntityName() const { return m_entityName.c_str(); } + void SetEntityName(const char* entityName) + { + // copying because the entity might go away + m_entityName = entityName; + } + AZStd::map& GetComponentReports(); AZStd::size_t GetTotalDirtyBits() const { return m_gdeDirtyBytes.GetTotalBytes(); } float GetAvgDirtyBits() const { return m_gdeDirtyBytes.GetAverageBytes(); } @@ -89,5 +94,6 @@ namespace MultiplayerDiagnostics ComponentReporter* m_currentComponentReport = nullptr; AZStd::map m_componentReports; MultiplayerDebugByteReporter m_gdeDirtyBytes; + AZStd::string m_entityName; }; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index c839083f63..3517dfa86a 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -119,15 +119,15 @@ namespace MultiplayerDiagnostics if (ImGui::CollapsingHeader("Receiving Entities")) { - for (auto& entityPair : m_receivingEntityReports) + for (AZStd::pair& entityPair : m_receivingEntityReports) { - if (!filter.PassFilter(entityPair.first.c_str())) + if (!filter.PassFilter(entityPair.second.GetEntityName())) { continue; } ImGui::Separator(); - if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) + if (ReplicatedStateTreeNode(entityPair.second.GetEntityName(), entityPair.second, k_ImGuiDusk)) { DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); ImGui::TreePop(); @@ -137,15 +137,16 @@ namespace MultiplayerDiagnostics if (ImGui::CollapsingHeader("Sending Entities")) { - for (auto& entityPair : m_sendingEntityReports) + for (AZStd::pair& entityPair : m_sendingEntityReports) { - if (!filter.PassFilter(entityPair.first.c_str())) + const char* name = entityPair.second.GetEntityName(); + if (!filter.PassFilter(name)) { continue; } ImGui::Separator(); - if (ReplicatedStateTreeNode(entityPair.first, entityPair.second, k_ImGuiDusk)) + if (ReplicatedStateTreeNode(name, entityPair.second, k_ImGuiDusk)) { DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); ImGui::TreePop(); @@ -162,9 +163,11 @@ namespace MultiplayerDiagnostics { case AzNetworking::SerializerMode::ReadFromObject: m_currentSendingEntityReport.Reset(); + m_currentSendingEntityReport.SetEntityName(entityName); break; case AzNetworking::SerializerMode::WriteToObject: m_currentReceivingEntityReport.Reset(); + m_currentReceivingEntityReport.SetEntityName(entityName); break; } } @@ -183,15 +186,15 @@ namespace MultiplayerDiagnostics } void MultiplayerDebugPerEntityReporter::RecordEntitySerializeStop(AzNetworking::SerializerMode mode, - [[maybe_unused]] AZ::EntityId entityId, const char* entityName) + [[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] const char* entityName) { switch (mode) { case AzNetworking::SerializerMode::ReadFromObject: - m_sendingEntityReports[entityName].Combine(m_currentSendingEntityReport); + m_sendingEntityReports[entityId].Combine(m_currentSendingEntityReport); break; case AzNetworking::SerializerMode::WriteToObject: - m_receivingEntityReports[entityName].Combine(m_currentReceivingEntityReport); + m_receivingEntityReports[entityId].Combine(m_currentReceivingEntityReport); break; } } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h index 121c4131ed..f34cc2cd35 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h @@ -42,10 +42,10 @@ namespace MultiplayerDiagnostics private: - AZStd::map m_sendingEntityReports{}; + AZStd::map m_sendingEntityReports{}; EntityReporter m_currentSendingEntityReport; - AZStd::map m_receivingEntityReports{}; + AZStd::map m_receivingEntityReports{}; EntityReporter m_currentReceivingEntityReport; float m_replicatedStateKbpsWarn = 10.f; From 8fa3addda3501ee44308f15e5331b1d27d280565 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Tue, 27 Jul 2021 00:21:40 -0400 Subject: [PATCH 026/251] Added debug overlay for entitie with high network costs Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../MultiplayerDebugPerEntityReporter.cpp | 37 +++++++++++++++++++ .../Debug/MultiplayerDebugSystemComponent.cpp | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index 3517dfa86a..30e6feb2f4 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -7,6 +7,10 @@ */ #include "MultiplayerDebugPerEntityReporter.h" + +#include +#include +#include #include #if defined(IMGUI_ENABLED) @@ -117,6 +121,17 @@ namespace MultiplayerDiagnostics static ImGuiTextFilter filter; filter.Draw(); + char status[100] = {}; + + struct NetworkEntityTraffic + { + const char* m_name = nullptr; + float m_up = 0.f; + float m_down = 0.f; + }; + + AZStd::fixed_unordered_map networkEntitiesTraffic; + if (ImGui::CollapsingHeader("Receiving Entities")) { for (AZStd::pair& entityPair : m_receivingEntityReports) @@ -132,6 +147,9 @@ namespace MultiplayerDiagnostics DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); ImGui::TreePop(); } + + networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); + networkEntitiesTraffic[entityPair.first].m_down = entityPair.second.GetKbitsPerSecond(); } } @@ -151,8 +169,27 @@ namespace MultiplayerDiagnostics DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); ImGui::TreePop(); } + + networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); + networkEntitiesTraffic[entityPair.first].m_up = entityPair.second.GetKbitsPerSecond(); } } + + constexpr float trafficThreshold = 0.1f; + for (AZStd::pair& networkEntity : networkEntitiesTraffic) + { + if (networkEntity.second.m_down < trafficThreshold && networkEntity.second.m_up < trafficThreshold) + { + continue; + } + + azsprintf(status, "%s - %.0f down / %0.f up (kbps)", networkEntity.second.m_name, networkEntity.second.m_down, networkEntity.second.m_up); + AZ::Vector3 entityPosition = AZ::Vector3::CreateZero(); + constexpr bool centerText = true; + AZ::TransformBus::EventResult(entityPosition, networkEntity.first, &AZ::TransformBus::Events::GetWorldTranslation); + AzFramework::DebugDisplayRequestBus::Broadcast(&AzFramework::DebugDisplayRequestBus::Events::DrawTextLabel, + entityPosition, 1.0f, status, centerText, 0, 0); + } #endif } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index 73afc45271..44e2f9f6bf 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -329,7 +329,7 @@ namespace Multiplayer if (m_displayPerEntityStats) { - if (ImGui::Begin("Multiplayer Per Entity Analytics", &m_displayPerEntityStats)) + if (ImGui::Begin("Multiplayer Per Entity Analytics", &m_displayPerEntityStats, ImGuiWindowFlags_None)) { if (m_reporter) { From 26c9853ff9916b7216a5e01eef6b9f7be8bb4df1 Mon Sep 17 00:00:00 2001 From: moraaar Date: Tue, 27 Jul 2021 09:11:28 +0100 Subject: [PATCH 027/251] Fixed cloth tangent generation (#2440) - The output vectors were not properly filled with zeros when they already had the expected size. - The tolerance was too large and was causing patches while computing tangents and bitangents. - The handedness was inverted to what is expected in the shader (which always inverts tangent's w). Signed-off-by: moraaar --- .../ClothComponentMesh/ClothComponentMesh.cpp | 2 +- .../Code/Source/System/TangentSpaceHelper.cpp | 20 ++++++++++++------- .../ClothConstraintsTest.cpp | 12 ++++++++--- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp index b791e8a543..7e0ac2f230 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp @@ -577,7 +577,7 @@ namespace NvCloth const AZ::Vector3& renderTangent = renderTangents[renderVertexIndex]; destTangentsBuffer[index].Set( renderTangent, - 1.0f); + -1.0f); // Shader function ConstructTBN inverts w to change bitangent sign, but the bitangents passed are already corrected, so passing -1.0 to counteract. } if (destBitangentsBuffer) diff --git a/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp b/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp index b43ad1923b..e388643c00 100644 --- a/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp +++ b/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp @@ -11,7 +11,7 @@ namespace NvCloth { namespace { - const float Tolerance = 0.0001f; + const float Tolerance = 1e-7f; } bool TangentSpaceHelper::CalculateNormals( @@ -33,7 +33,8 @@ namespace NvCloth const size_t vertexCount = vertices.size(); // Reset results - outNormals.resize(vertexCount, AZ::Vector3::CreateZero()); + outNormals.resize(vertexCount); + AZStd::fill(outNormals.begin(), outNormals.end(), AZ::Vector3::CreateZero()); // calculate the normals per triangle for (size_t i = 0; i < triangleCount; ++i) @@ -114,8 +115,10 @@ namespace NvCloth const size_t vertexCount = vertices.size(); // Reset results - outTangents.resize(vertexCount, AZ::Vector3::CreateZero()); - outBitangents.resize(vertexCount, AZ::Vector3::CreateZero()); + outTangents.resize(vertexCount); + outBitangents.resize(vertexCount); + AZStd::fill(outTangents.begin(), outTangents.end(), AZ::Vector3::CreateZero()); + AZStd::fill(outBitangents.begin(), outBitangents.end(), AZ::Vector3::CreateZero()); // calculate the base vectors per triangle for (size_t i = 0; i < triangleCount; ++i) @@ -192,9 +195,12 @@ namespace NvCloth const size_t vertexCount = vertices.size(); // Reset results - outTangents.resize(vertexCount, AZ::Vector3::CreateZero()); - outBitangents.resize(vertexCount, AZ::Vector3::CreateZero()); - outNormals.resize(vertexCount, AZ::Vector3::CreateZero()); + outTangents.resize(vertexCount); + outBitangents.resize(vertexCount); + outNormals.resize(vertexCount); + AZStd::fill(outTangents.begin(), outTangents.end(), AZ::Vector3::CreateZero()); + AZStd::fill(outBitangents.begin(), outBitangents.end(), AZ::Vector3::CreateZero()); + AZStd::fill(outNormals.begin(), outNormals.end(), AZ::Vector3::CreateZero()); // calculate the base vectors per triangle for (size_t i = 0; i < triangleCount; ++i) diff --git a/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp b/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp index 5f390ed45d..50ca5c17cd 100644 --- a/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp +++ b/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp @@ -124,6 +124,9 @@ namespace UnitTest const AZStd::vector& motionConstraints = clothConstraints->GetMotionConstraints(); EXPECT_TRUE(motionConstraints.size() == SimulationParticles.size()); + EXPECT_THAT(motionConstraints[0].GetAsVector3(), IsCloseTolerance(SimulationParticles[0].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[1].GetAsVector3(), IsCloseTolerance(SimulationParticles[1].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[2].GetAsVector3(), IsCloseTolerance(SimulationParticles[2].GetAsVector3(), Tolerance)); EXPECT_NEAR(motionConstraints[0].GetW(), 6.0f, Tolerance); EXPECT_NEAR(motionConstraints[1].GetW(), 0.0f, Tolerance); EXPECT_NEAR(motionConstraints[2].GetW(), 0.0f, Tolerance); @@ -277,6 +280,9 @@ namespace UnitTest const AZStd::vector& separationConstraints = clothConstraints->GetSeparationConstraints(); EXPECT_TRUE(motionConstraints.size() == newParticles.size()); + EXPECT_THAT(motionConstraints[0].GetAsVector3(), IsCloseTolerance(newParticles[0].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[1].GetAsVector3(), IsCloseTolerance(newParticles[1].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[2].GetAsVector3(), IsCloseTolerance(newParticles[2].GetAsVector3(), Tolerance)); EXPECT_NEAR(motionConstraints[0].GetW(), 3.0f, Tolerance); EXPECT_NEAR(motionConstraints[1].GetW(), 1.5f, Tolerance); EXPECT_NEAR(motionConstraints[2].GetW(), 0.0f, Tolerance); @@ -285,8 +291,8 @@ namespace UnitTest EXPECT_NEAR(separationConstraints[0].GetW(), 3.0f, Tolerance); EXPECT_NEAR(separationConstraints[1].GetW(), 1.5f, Tolerance); EXPECT_NEAR(separationConstraints[2].GetW(), 0.3f, Tolerance); - EXPECT_THAT(separationConstraints[0].GetAsVector3(), IsCloseTolerance(AZ::Vector3(-3.03902f, 2.80752f, 3.80752f), Tolerance)); - EXPECT_THAT(separationConstraints[1].GetAsVector3(), IsCloseTolerance(AZ::Vector3(-1.41659f, 0.651243f, -0.348757f), Tolerance)); - EXPECT_THAT(separationConstraints[2].GetAsVector3(), IsCloseTolerance(AZ::Vector3(6.15313f, -0.876132f, 0.123868f), Tolerance)); + EXPECT_THAT(separationConstraints[0].GetAsVector3(), IsCloseTolerance(AZ::Vector3(0.0f, 3.53553f, 4.53553f), Tolerance)); + EXPECT_THAT(separationConstraints[1].GetAsVector3(), IsCloseTolerance(AZ::Vector3(0.0f, 2.06066f, 1.06066f), Tolerance)); + EXPECT_THAT(separationConstraints[2].GetAsVector3(), IsCloseTolerance(AZ::Vector3(1.0f, -3.74767f, -2.74767f), Tolerance)); } } // namespace UnitTest From 5ebb096d1a3420281a002f20a86351b8b7d1a690 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Tue, 27 Jul 2021 15:49:41 -0400 Subject: [PATCH 028/251] Debug overlay for kpbs per entity works Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../MultiplayerDebugPerEntityInterface.h | 1 + .../MultiplayerDebugPerEntityReporter.cpp | 140 +++++++++++++----- .../Debug/MultiplayerDebugPerEntityReporter.h | 25 +++- .../Debug/MultiplayerDebugSystemComponent.cpp | 5 +- .../Code/Source/MultiplayerStats.cpp | 5 + 5 files changed, 138 insertions(+), 38 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h index 94bc11dafa..4f177affe3 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h @@ -24,5 +24,6 @@ namespace MultiplayerDiagnostics virtual void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) = 0; virtual void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) = 0; virtual void RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) = 0; + virtual void RecordRpcReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) = 0; }; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index 30e6feb2f4..3c5495ec6a 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -19,6 +19,21 @@ #pragma optimize("", off) +AZ_CVAR(bool, net_DebugNetworkEntity_Bandwidth, true, nullptr, AZ::ConsoleFunctorFlags::Null, + "If true, prints debug text over entities that use a considerable amount of network traffic"); + +AZ_CVAR(float, net_DebugNetworkEntity_ShowAboveKbps, 1.f, nullptr, AZ::ConsoleFunctorFlags::Null, + "Prints bandwidth on network entities with higher kpbs than this value"); + +AZ_CVAR(float, net_DebugNetworkEntity_WarnAboveKbps, 10.f, nullptr, AZ::ConsoleFunctorFlags::Null, + "Prints bandwidth on network entities with higher kpbs than this value"); + +AZ_CVAR(AZ::Color, net_DebugNetworkEntity_WarningColor, AZ::Colors::Red, nullptr, AZ::ConsoleFunctorFlags::Null, + "If true, prints debug text over entities that use a considerable amount of network traffic"); + +AZ_CVAR(AZ::Color, net_DebugNetworkEntity_BelowWarningColor, AZ::Colors::Grey, nullptr, AZ::ConsoleFunctorFlags::Null, + "If true, prints debug text over entities that use a considerable amount of network traffic"); + namespace MultiplayerDiagnostics { #if defined(IMGUI_ENABLED) @@ -114,6 +129,17 @@ namespace MultiplayerDiagnostics } #endif + MultiplayerDebugPerEntityReporter::MultiplayerDebugPerEntityReporter() + : m_updateDebugOverlay([this]() { UpdateDebugOverlay(); }, AZ::Name("UpdateDebugPerEntityOverlay")) + { + m_updateDebugOverlay.Enqueue(AZ::TimeMs{ 0 }, true); + } + + MultiplayerDebugPerEntityReporter::~MultiplayerDebugPerEntityReporter() + { + m_updateDebugOverlay.RemoveFromQueue(); + } + // -------------------------------------------------------------------------------------------- void MultiplayerDebugPerEntityReporter::OnImGuiUpdate() { @@ -121,17 +147,6 @@ namespace MultiplayerDiagnostics static ImGuiTextFilter filter; filter.Draw(); - char status[100] = {}; - - struct NetworkEntityTraffic - { - const char* m_name = nullptr; - float m_up = 0.f; - float m_down = 0.f; - }; - - AZStd::fixed_unordered_map networkEntitiesTraffic; - if (ImGui::CollapsingHeader("Receiving Entities")) { for (AZStd::pair& entityPair : m_receivingEntityReports) @@ -147,9 +162,6 @@ namespace MultiplayerDiagnostics DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); ImGui::TreePop(); } - - networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); - networkEntitiesTraffic[entityPair.first].m_down = entityPair.second.GetKbitsPerSecond(); } } @@ -169,26 +181,7 @@ namespace MultiplayerDiagnostics DisplayReplicatedStateReport(entityPair.second.GetComponentReports(), m_replicatedStateKbpsWarn, m_replicatedStateMaxSizeWarn); ImGui::TreePop(); } - - networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); - networkEntitiesTraffic[entityPair.first].m_up = entityPair.second.GetKbitsPerSecond(); - } - } - - constexpr float trafficThreshold = 0.1f; - for (AZStd::pair& networkEntity : networkEntitiesTraffic) - { - if (networkEntity.second.m_down < trafficThreshold && networkEntity.second.m_up < trafficThreshold) - { - continue; } - - azsprintf(status, "%s - %.0f down / %0.f up (kbps)", networkEntity.second.m_name, networkEntity.second.m_down, networkEntity.second.m_up); - AZ::Vector3 entityPosition = AZ::Vector3::CreateZero(); - constexpr bool centerText = true; - AZ::TransformBus::EventResult(entityPosition, networkEntity.first, &AZ::TransformBus::Events::GetWorldTranslation); - AzFramework::DebugDisplayRequestBus::Broadcast(&AzFramework::DebugDisplayRequestBus::Events::DrawTextLabel, - entityPosition, 1.0f, status, centerText, 0, 0); } #endif } @@ -271,4 +264,85 @@ namespace MultiplayerDiagnostics componentRegistry->GetComponentRpcName(netComponentId, rpcId), totalBytes); } } + + void MultiplayerDebugPerEntityReporter::RecordRpcReceived( + Multiplayer::NetComponentId netComponentId, + Multiplayer::RpcIndex rpcId, + uint32_t totalBytes) + { + if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + { + m_currentReceivingEntityReport.ReportField(static_cast(netComponentId), + componentRegistry->GetComponentName(netComponentId), + componentRegistry->GetComponentRpcName(netComponentId, rpcId), totalBytes); + } + } + + void MultiplayerDebugPerEntityReporter::UpdateDebugOverlay() + { + if (net_DebugNetworkEntity_Bandwidth) + { + m_networkEntitiesTraffic.clear(); + + for (AZStd::pair& entityPair : m_receivingEntityReports) + { + m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); + m_networkEntitiesTraffic[entityPair.first].m_down = entityPair.second.GetKbitsPerSecond(); + } + + for (AZStd::pair& entityPair : m_sendingEntityReports) + { + m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); + m_networkEntitiesTraffic[entityPair.first].m_up = entityPair.second.GetKbitsPerSecond(); + } + + //get debug display interface for the viewport + if (m_debugDisplay == nullptr) + { + AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; + AzFramework::DebugDisplayRequestBus::Bind(debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); + m_debugDisplay = AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus); + } + + const AZ::u32 stateBefore = m_debugDisplay->GetState(); + + for (AZStd::pair& networkEntity : m_networkEntitiesTraffic) + { + if (networkEntity.second.m_down < net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up < net_DebugNetworkEntity_ShowAboveKbps) + { + continue; + } + + if (networkEntity.second.m_down > net_DebugNetworkEntity_WarnAboveKbps || networkEntity.second.m_up > net_DebugNetworkEntity_WarnAboveKbps) + { + m_debugDisplay->SetColor(net_DebugNetworkEntity_WarningColor); + } + else + { + m_debugDisplay->SetColor(net_DebugNetworkEntity_BelowWarningColor); + } + + if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up > net_DebugNetworkEntity_ShowAboveKbps) + { + azsprintf(m_statusBuffer, "[%s] %.0f down / %0.f up (kbps)", networkEntity.second.m_name, + networkEntity.second.m_down, networkEntity.second.m_up); + } + else if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps) + { + azsprintf(m_statusBuffer, "[%s] %.0f down (kbps)", networkEntity.second.m_name, networkEntity.second.m_down); + } + else + { + azsprintf(m_statusBuffer, "[%s] %.0f up (kbps)", networkEntity.second.m_name, networkEntity.second.m_up); + } + + AZ::Vector3 entityPosition = AZ::Vector3::CreateZero(); + constexpr bool centerText = true; + AZ::TransformBus::EventResult(entityPosition, networkEntity.first, &AZ::TransformBus::Events::GetWorldTranslation); + m_debugDisplay->DrawTextLabel(entityPosition, 1.0f, m_statusBuffer, centerText, 0, 0); + } + + m_debugDisplay->SetState(stateBefore); + } + } } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h index f34cc2cd35..23192062e3 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h @@ -10,7 +10,10 @@ #include "MultiplayerDebugByteReporter.h" #include +#include +#include #include +#include #include #include #include @@ -24,8 +27,8 @@ namespace MultiplayerDiagnostics : public AZ::Interface::Registrar { public: - MultiplayerDebugPerEntityReporter() = default; - ~MultiplayerDebugPerEntityReporter() override = default; + MultiplayerDebugPerEntityReporter(); + ~MultiplayerDebugPerEntityReporter() override; // main update loop void OnImGuiUpdate(); @@ -38,10 +41,15 @@ namespace MultiplayerDiagnostics void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; void RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) override; + void RecordRpcReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) override; // }@ + void UpdateDebugOverlay(); + private: + AZ::ScheduledEvent m_updateDebugOverlay; + AZStd::map m_sendingEntityReports{}; EntityReporter m_currentSendingEntityReport; @@ -50,5 +58,18 @@ namespace MultiplayerDiagnostics float m_replicatedStateKbpsWarn = 10.f; float m_replicatedStateMaxSizeWarn = 30.f; + + char m_statusBuffer[100] = {}; + + struct NetworkEntityTraffic + { + const char* m_name = nullptr; + float m_up = 0.f; + float m_down = 0.f; + }; + + AZStd::fixed_unordered_map m_networkEntitiesTraffic; + + AzFramework::DebugDisplayRequests* m_debugDisplay = nullptr; }; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index 44e2f9f6bf..835aae0d72 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -13,8 +13,6 @@ #include #include -#pragma optimize("", off) - namespace Multiplayer { void MultiplayerDebugSystemComponent::Reflect(AZ::ReflectContext* context) @@ -329,7 +327,8 @@ namespace Multiplayer if (m_displayPerEntityStats) { - if (ImGui::Begin("Multiplayer Per Entity Analytics", &m_displayPerEntityStats, ImGuiWindowFlags_None)) + //ImGui::SetNextWindowSize({500, 400}); + if (ImGui::Begin("Multiplayer Per Entity Stats", &m_displayPerEntityStats, ImGuiWindowFlags_AlwaysAutoResize)) { if (m_reporter) { diff --git a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp index fd1b6a329d..05be869872 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp @@ -101,6 +101,11 @@ namespace Multiplayer void MultiplayerStats::RecordRpcReceived(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes) { + if (auto* perEntityStats = AZ::Interface::Get()) + { + perEntityStats->RecordRpcReceived(netComponentId, rpcId, totalBytes); + } + const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t rpcIndex = aznumeric_cast(rpcId); m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_totalCalls++; From 416f9aecf71faf3df82bfcabb23ba87f1b13d809 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 28 Jul 2021 15:09:38 +0200 Subject: [PATCH 029/251] Removed collision mesh aabb color from render option Signed-off-by: Benjamin Jillich --- .../Source/RenderPlugin/RenderOptions.cpp | 23 ------------------- .../Source/RenderPlugin/RenderOptions.h | 6 ----- 2 files changed, 29 deletions(-) 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..5e57d64167 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,7 +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"; @@ -108,7 +107,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) @@ -169,7 +167,6 @@ namespace EMStudio SetNodeAABBColor(other.GetNodeAABBColor()); SetStaticAABBColor(other.GetStaticAABBColor()); SetMeshAABBColor(other.GetMeshAABBColor()); - SetCollisionMeshAABBColor(other.GetCollisionMeshAABBColor()); SetOBBsColor(other.GetOBBsColor()); SetLineSkeletonColor(other.GetLineSkeletonColor()); SetSkeletonColor(other.GetSkeletonColor()); @@ -206,7 +203,6 @@ 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)); @@ -275,7 +271,6 @@ 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()); @@ -393,7 +388,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) @@ -552,9 +546,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) @@ -903,15 +894,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)) @@ -1258,11 +1240,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); 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..5e12cf935f 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,7 +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; @@ -191,9 +190,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); @@ -303,7 +299,6 @@ namespace EMStudio void OnNodeAABBColorChangedCallback() const; void OnStaticAABBColorChangedCallback() const; void OnMeshAABBColorChangedCallback() const; - void OnCollisionMeshAABBColorChangedCallback() const; void OnOBBsColorChangedCallback() const; void OnLineSkeletonColorChangedCallback() const; void OnSkeletonColorChangedCallback() const; @@ -361,7 +356,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; From e9718d9ce87ceb09c209777174ca46d37ef4a288 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 28 Jul 2021 15:30:34 +0200 Subject: [PATCH 030/251] Converted the EMFX Mesh to use AZ::Aabb instead of MCore::AABB Signed-off-by: Benjamin Jillich --- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 9 +++------ Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h | 3 ++- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index 51486c39b5..60ebd9a2dc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -1372,20 +1372,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])); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index f9a9f960ce..cb929dc7db 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 @@ -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. From 462c31b5de49ffe05c1788741278d2865a685ae1 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Wed, 28 Jul 2021 09:53:44 -0400 Subject: [PATCH 031/251] Refactoring to use AZ::Events Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../Include/Multiplayer/MultiplayerStats.h | 30 ++++++++- .../Debug/MultiplayerDebugByteReporter.cpp | 38 ++++++------ .../Debug/MultiplayerDebugByteReporter.h | 20 +++--- .../MultiplayerDebugPerEntityInterface.h | 29 --------- .../MultiplayerDebugPerEntityReporter.cpp | 61 ++++++++++++++++--- .../Debug/MultiplayerDebugPerEntityReporter.h | 34 +++++------ .../Debug/MultiplayerDebugSystemComponent.cpp | 4 +- .../Debug/MultiplayerDebugSystemComponent.h | 2 +- .../Code/Source/MultiplayerStats.cpp | 59 ++++++++---------- .../EntityReplication/EntityReplicator.cpp | 11 ++-- .../Code/multiplayer_debug_files.cmake | 1 - 11 files changed, 156 insertions(+), 133 deletions(-) delete mode 100644 Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h index 1299fe174d..98a7b165f8 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h @@ -55,8 +55,8 @@ namespace Multiplayer void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName); void RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); void RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); - void RecordRpcSent(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); - void RecordRpcReceived(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); + void RecordRpcSent(AZ::EntityId entityId, const char* entityName, NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); + void RecordRpcReceived(AZ::EntityId entityId, const char* entityName, NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); void TickStats(AZ::TimeMs metricFrameTimeMs); Metric CalculateComponentPropertyUpdateSentMetrics(NetComponentId netComponentId) const; @@ -67,5 +67,31 @@ namespace Multiplayer Metric CalculateTotalPropertyUpdateRecvMetrics() const; Metric CalculateTotalRpcsSentMetrics() const; Metric CalculateTotalRpcsRecvMetrics() const; + + struct Events + { + AZ::Event m_entitySerializeStart; + AZ::Event m_componentSerializeEnd; + AZ::Event m_entitySerializeStop; + AZ::Event m_propertySent; + AZ::Event m_propertyReceived; + AZ::Event m_rpcSent; + AZ::Event m_rpcReceived; + }; + + Events m_events; + + struct EventHandlers + { + AZ::Event::Handler m_entitySerializeStart; + AZ::Event::Handler m_componentSerializeEnd; + AZ::Event::Handler m_entitySerializeStop; + AZ::Event::Handler m_propertySent; + AZ::Event::Handler m_propertyReceived; + AZ::Event::Handler m_rpcSent; + AZ::Event::Handler m_rpcReceived; + }; + + void ConnectHandlers(EventHandlers& handlers); }; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp index 5e912612b7..a29350e43a 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -14,7 +14,7 @@ #pragma optimize("", off) -namespace MultiplayerDiagnostics +namespace Multiplayer { void MultiplayerDebugByteReporter::ReportBytes(size_t byteSize) { @@ -44,7 +44,7 @@ namespace MultiplayerDiagnostics return 0.0f; } - return (1.0f * m_totalBytes) / m_count; + return aznumeric_cast(m_totalBytes) / aznumeric_cast(m_count); } size_t MultiplayerDebugByteReporter::GetMaxBytes() const @@ -64,26 +64,26 @@ namespace MultiplayerDiagnostics float MultiplayerDebugByteReporter::GetKbitsPerSecond() { - auto now = AZStd::chrono::monotonic_clock::now(); + const auto now = AZStd::chrono::monotonic_clock::now(); // Check the amount of time elapsed and update totals if necessary. // Time here is measured in whole seconds from the epoch, providing synchronization in // reporting intervals across all byte reporters. - AZStd::chrono::seconds nowSeconds = AZStd::chrono::duration_cast(now.time_since_epoch()); - AZStd::chrono::seconds secondsSinceLastUpdate = nowSeconds - + const AZStd::chrono::seconds nowSeconds = AZStd::chrono::duration_cast(now.time_since_epoch()); + const AZStd::chrono::seconds secondsSinceLastUpdate = nowSeconds - AZStd::chrono::duration_cast(m_lastUpdateTime.time_since_epoch()); if (secondsSinceLastUpdate.count()) { // normalize over elapsed milliseconds - const int k_millisecondsPerSecond = 1000; - auto msSinceLastUpdate = AZStd::chrono::duration_cast(now - m_lastUpdateTime); - m_totalBytesLastSecond = k_millisecondsPerSecond * (1.f * m_totalBytesThisSecond / msSinceLastUpdate.count()); + constexpr int k_millisecondsPerSecond = 1000; + const auto msSinceLastUpdate = AZStd::chrono::duration_cast(now - m_lastUpdateTime); + m_totalBytesLastSecond = k_millisecondsPerSecond * aznumeric_cast(m_totalBytesThisSecond) / aznumeric_cast(msSinceLastUpdate.count()); m_totalBytesThisSecond = 0; m_lastUpdateTime = now; } - const float k_bitsPerByte = 8.0f; - const int k_bitsPerKilobit = 1024; + constexpr float k_bitsPerByte = 8.0f; + constexpr int k_bitsPerKilobit = 1024; return k_bitsPerByte * m_totalBytesLastSecond / k_bitsPerKilobit; } @@ -107,19 +107,19 @@ namespace MultiplayerDiagnostics m_aggregateBytes = 0; } - void ComponentReporter::ReportField(const char* fieldName, size_t byteSize) + void MultiplayerDebugComponentReporter::ReportField(const char* fieldName, size_t byteSize) { MultiplayerDebugByteReporter::AggregateBytes(byteSize); m_fieldReports[fieldName].ReportBytes(byteSize); } - void ComponentReporter::ReportFragmentEnd() + void MultiplayerDebugComponentReporter::ReportFragmentEnd() { MultiplayerDebugByteReporter::ReportAggregateBytes(); m_componentDirtyBytes.ReportAggregateBytes(); } - AZStd::vector ComponentReporter::GetFieldReports() + AZStd::vector MultiplayerDebugComponentReporter::GetFieldReports() { AZStd::vector copy; for (auto field = m_fieldReports.begin(); field != m_fieldReports.end(); ++field) @@ -137,7 +137,7 @@ namespace MultiplayerDiagnostics return copy; } - void ComponentReporter::Combine(const ComponentReporter& other) + void MultiplayerDebugComponentReporter::Combine(const MultiplayerDebugComponentReporter& other) { MultiplayerDebugByteReporter::Combine(other); @@ -149,7 +149,7 @@ namespace MultiplayerDiagnostics m_componentDirtyBytes.Combine(other.m_componentDirtyBytes); } - void EntityReporter::ReportField(AZ::u32 index, const char* componentName, + void MultiplayerDebugEntityReporter::ReportField(AZ::u32 index, const char* componentName, const char* fieldName, size_t byteSize) { if (m_currentComponentReport == nullptr) @@ -163,7 +163,7 @@ namespace MultiplayerDiagnostics MultiplayerDebugByteReporter::AggregateBytes(byteSize); } - void EntityReporter::ReportFragmentEnd() + void MultiplayerDebugEntityReporter::ReportFragmentEnd() { if (m_currentComponentReport) { @@ -175,7 +175,7 @@ namespace MultiplayerDiagnostics MultiplayerDebugByteReporter::ReportAggregateBytes(); } - void EntityReporter::Combine(const EntityReporter& other) + void MultiplayerDebugEntityReporter::Combine(const MultiplayerDebugEntityReporter& other) { MultiplayerDebugByteReporter::Combine(other); @@ -188,7 +188,7 @@ namespace MultiplayerDiagnostics m_gdeDirtyBytes.Combine(other.m_gdeDirtyBytes); } - void EntityReporter::Reset() + void MultiplayerDebugEntityReporter::Reset() { MultiplayerDebugByteReporter::Reset(); @@ -196,7 +196,7 @@ namespace MultiplayerDiagnostics m_gdeDirtyBytes.Reset(); } - AZStd::map& EntityReporter::GetComponentReports() + AZStd::map& MultiplayerDebugEntityReporter::GetComponentReports() { return m_componentReports; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h index 3cef9caaac..934c6f3aac 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h @@ -13,7 +13,7 @@ #include #include -namespace MultiplayerDiagnostics +namespace Multiplayer { class MultiplayerDebugByteReporter { @@ -48,10 +48,10 @@ namespace MultiplayerDiagnostics AZStd::chrono::monotonic_clock::time_point m_lastUpdateTime; }; - class ComponentReporter : public MultiplayerDebugByteReporter + class MultiplayerDebugComponentReporter : public MultiplayerDebugByteReporter { public: - ComponentReporter() = default; + MultiplayerDebugComponentReporter() = default; void ReportField(const char* fieldName, size_t byteSize); void ReportFragmentEnd(); @@ -61,22 +61,22 @@ namespace MultiplayerDiagnostics AZStd::size_t GetTotalDirtyBits() const { return m_componentDirtyBytes.GetTotalBytes(); } float GetAvgDirtyBits() const { return m_componentDirtyBytes.GetAverageBytes(); } - void Combine(const ComponentReporter& other); + void Combine(const MultiplayerDebugComponentReporter& other); private: AZStd::map m_fieldReports; MultiplayerDebugByteReporter m_componentDirtyBytes; }; - class EntityReporter : public MultiplayerDebugByteReporter + class MultiplayerDebugEntityReporter : public MultiplayerDebugByteReporter { public: - EntityReporter() = default; + MultiplayerDebugEntityReporter() = default; void ReportField(AZ::u32 index, const char* componentName, const char* fieldName, size_t byteSize); void ReportFragmentEnd(); - void Combine(const EntityReporter& other); + void Combine(const MultiplayerDebugEntityReporter& other); void Reset() override; const char* GetEntityName() const { return m_entityName.c_str(); } @@ -86,13 +86,13 @@ namespace MultiplayerDiagnostics m_entityName = entityName; } - AZStd::map& GetComponentReports(); + AZStd::map& GetComponentReports(); AZStd::size_t GetTotalDirtyBits() const { return m_gdeDirtyBytes.GetTotalBytes(); } float GetAvgDirtyBits() const { return m_gdeDirtyBytes.GetAverageBytes(); } private: - ComponentReporter* m_currentComponentReport = nullptr; - AZStd::map m_componentReports; + MultiplayerDebugComponentReporter* m_currentComponentReport = nullptr; + AZStd::map m_componentReports; MultiplayerDebugByteReporter m_gdeDirtyBytes; AZStd::string m_entityName; }; diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h deleted file mode 100644 index 4f177affe3..0000000000 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityInterface.h +++ /dev/null @@ -1,29 +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 MultiplayerDiagnostics -{ - class MultiplayerIPerEntityStats - { - public: - AZ_RTTI(MultiplayerIPerEntityStats, "{91A1E4F0-8AE6-44B2-89DF-DA34134C408A}"); - - virtual void RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) = 0; - virtual void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId) = 0; - virtual void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) = 0; - virtual void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) = 0; - virtual void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) = 0; - virtual void RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) = 0; - virtual void RecordRpcReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) = 0; - }; -} diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index 3c5495ec6a..da32bbb666 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -34,7 +34,7 @@ AZ_CVAR(AZ::Color, net_DebugNetworkEntity_WarningColor, AZ::Colors::Red, nullptr AZ_CVAR(AZ::Color, net_DebugNetworkEntity_BelowWarningColor, AZ::Colors::Grey, nullptr, AZ::ConsoleFunctorFlags::Null, "If true, prints debug text over entities that use a considerable amount of network traffic"); -namespace MultiplayerDiagnostics +namespace Multiplayer { #if defined(IMGUI_ENABLED) static const ImVec4 k_ImGuiTomato = ImVec4(1.0f, 0.4f, 0.3f, 1.0f); @@ -64,12 +64,12 @@ namespace MultiplayerDiagnostics } // -------------------------------------------------------------------------------------------- - void DisplayReplicatedStateReport(AZStd::map& componentReports, float kbpsWarn, float maxWarn) + void DisplayReplicatedStateReport(AZStd::map& componentReports, float kbpsWarn, float maxWarn) { for (auto& componentPair : componentReports) { ImGui::Separator(); - ComponentReporter& componentReport = componentPair.second; + MultiplayerDebugComponentReporter& componentReport = componentPair.second; if (ReplicatedStateTreeNode(componentPair.first, componentReport, k_ImGuiCyan, 1)) { @@ -94,7 +94,7 @@ namespace MultiplayerDiagnostics const float kbitsLastSecond = fieldReport.GetKbitsPerSecond(); const ImVec4* textColor = &k_ImGuiWhite; - if (fieldReport.GetMaxBytes() > maxWarn) + if (aznumeric_cast(fieldReport.GetMaxBytes()) > maxWarn) { textColor = &k_ImGuiKhaki; } @@ -133,6 +133,37 @@ namespace MultiplayerDiagnostics : m_updateDebugOverlay([this]() { UpdateDebugOverlay(); }, AZ::Name("UpdateDebugPerEntityOverlay")) { m_updateDebugOverlay.Enqueue(AZ::TimeMs{ 0 }, true); + + m_eventHandlers.m_entitySerializeStart = decltype(m_eventHandlers.m_entitySerializeStart)([this](AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) + { + RecordEntitySerializeStart(mode, entityId, entityName); + }); + m_eventHandlers.m_componentSerializeEnd = decltype(m_eventHandlers.m_componentSerializeEnd)([this](AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId) + { + RecordComponentSerializeEnd(mode, netComponentId); + }); + m_eventHandlers.m_entitySerializeStop = decltype(m_eventHandlers.m_entitySerializeStop)([this](AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) + { + RecordEntitySerializeStop(mode, entityId, entityName); + }); + m_eventHandlers.m_propertySent = decltype(m_eventHandlers.m_propertySent)([this](Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) + { + RecordPropertySent(netComponentId, propertyId, totalBytes); + }); + m_eventHandlers.m_propertyReceived = decltype(m_eventHandlers.m_propertyReceived)([this](Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) + { + RecordPropertyReceived(netComponentId, propertyId, totalBytes); + }); + m_eventHandlers.m_rpcSent = decltype(m_eventHandlers.m_rpcSent)([this](AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) + { + RecordRpcSent(entityId, entityName, netComponentId, rpcId, totalBytes); + }); + m_eventHandlers.m_rpcReceived = decltype(m_eventHandlers.m_rpcReceived)([this](AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) + { + RecordRpcSent(entityId, entityName, netComponentId, rpcId, totalBytes); + }); + + GetMultiplayer()->GetStats().ConnectHandlers(m_eventHandlers); } MultiplayerDebugPerEntityReporter::~MultiplayerDebugPerEntityReporter() @@ -149,7 +180,7 @@ namespace MultiplayerDiagnostics if (ImGui::CollapsingHeader("Receiving Entities")) { - for (AZStd::pair& entityPair : m_receivingEntityReports) + for (AZStd::pair& entityPair : m_receivingEntityReports) { if (!filter.PassFilter(entityPair.second.GetEntityName())) { @@ -167,7 +198,7 @@ namespace MultiplayerDiagnostics if (ImGui::CollapsingHeader("Sending Entities")) { - for (AZStd::pair& entityPair : m_sendingEntityReports) + for (AZStd::pair& entityPair : m_sendingEntityReports) { const char* name = entityPair.second.GetEntityName(); if (!filter.PassFilter(name)) @@ -255,26 +286,38 @@ namespace MultiplayerDiagnostics } } - void MultiplayerDebugPerEntityReporter::RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) + void MultiplayerDebugPerEntityReporter::RecordRpcSent(AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) { if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) { + // MultiplayerDebugByteReporter requires a + RecordEntitySerializeStart(AzNetworking::SerializerMode::ReadFromObject, entityId, entityName); + m_currentSendingEntityReport.ReportField(static_cast(netComponentId), componentRegistry->GetComponentName(netComponentId), componentRegistry->GetComponentRpcName(netComponentId, rpcId), totalBytes); + + RecordComponentSerializeEnd(AzNetworking::SerializerMode::ReadFromObject, netComponentId); + RecordEntitySerializeStop(AzNetworking::SerializerMode::ReadFromObject, entityId, entityName); } } void MultiplayerDebugPerEntityReporter::RecordRpcReceived( + AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) { if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) { + RecordEntitySerializeStart(AzNetworking::SerializerMode::WriteToObject, entityId, entityName); + m_currentReceivingEntityReport.ReportField(static_cast(netComponentId), componentRegistry->GetComponentName(netComponentId), componentRegistry->GetComponentRpcName(netComponentId, rpcId), totalBytes); + + RecordComponentSerializeEnd(AzNetworking::SerializerMode::WriteToObject, netComponentId); + RecordEntitySerializeStop(AzNetworking::SerializerMode::WriteToObject, entityId, entityName); } } @@ -284,13 +327,13 @@ namespace MultiplayerDiagnostics { m_networkEntitiesTraffic.clear(); - for (AZStd::pair& entityPair : m_receivingEntityReports) + for (AZStd::pair& entityPair : m_receivingEntityReports) { m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); m_networkEntitiesTraffic[entityPair.first].m_down = entityPair.second.GetKbitsPerSecond(); } - for (AZStd::pair& entityPair : m_sendingEntityReports) + for (AZStd::pair& entityPair : m_sendingEntityReports) { m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); m_networkEntitiesTraffic[entityPair.first].m_up = entityPair.second.GetKbitsPerSecond(); diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h index 23192062e3..d6ceaaf04c 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h @@ -10,38 +10,35 @@ #include "MultiplayerDebugByteReporter.h" #include -#include #include #include #include -#include -#include +#include #include -namespace MultiplayerDiagnostics +namespace Multiplayer { /** * \brief GridMate network live analysis tool via ImGui. */ class MultiplayerDebugPerEntityReporter - : public AZ::Interface::Registrar { public: MultiplayerDebugPerEntityReporter(); - ~MultiplayerDebugPerEntityReporter() override; + ~MultiplayerDebugPerEntityReporter(); // main update loop void OnImGuiUpdate(); - //! MultilayerIPerEntityStats + //! Event handlers // @{ - void RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) override; - void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId) override; - void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) override; - void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; - void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) override; - void RecordRpcSent(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) override; - void RecordRpcReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) override; + void RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName); + void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId); + void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName); + void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); + void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); + void RecordRpcSent(AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes); + void RecordRpcReceived(AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes); // }@ void UpdateDebugOverlay(); @@ -49,12 +46,13 @@ namespace MultiplayerDiagnostics private: AZ::ScheduledEvent m_updateDebugOverlay; + Multiplayer::MultiplayerStats::EventHandlers m_eventHandlers; - AZStd::map m_sendingEntityReports{}; - EntityReporter m_currentSendingEntityReport; + AZStd::map m_sendingEntityReports{}; + MultiplayerDebugEntityReporter m_currentSendingEntityReport; - AZStd::map m_receivingEntityReports{}; - EntityReporter m_currentReceivingEntityReport; + AZStd::map m_receivingEntityReports{}; + MultiplayerDebugEntityReporter m_currentReceivingEntityReport; float m_replicatedStateKbpsWarn = 10.f; float m_replicatedStateMaxSizeWarn = 30.f; diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index 835aae0d72..03d79025f7 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -55,7 +55,7 @@ namespace Multiplayer void MultiplayerDebugSystemComponent::OnImGuiInitialize() { - m_reporter = AZStd::make_unique(); + m_reporter = AZStd::make_unique(); } #ifdef IMGUI_ENABLED @@ -65,7 +65,7 @@ namespace Multiplayer { ImGui::Checkbox("Networking Stats", &m_displayNetworkingStats); ImGui::Checkbox("Multiplayer Stats", &m_displayMultiplayerStats); - ImGui::Checkbox("Multiplayer Per Entity Stats", &m_displayPerEntityStats); + ImGui::Checkbox("Multiplayer Entity Stats", &m_displayPerEntityStats); ImGui::EndMenu(); } } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h index 4972ec6bdf..a7f76e075a 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h @@ -53,6 +53,6 @@ namespace Multiplayer bool m_displayMultiplayerStats = false; bool m_displayPerEntityStats = false; - AZStd::unique_ptr m_reporter; + AZStd::unique_ptr m_reporter; }; } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp index 05be869872..7e56cd34f3 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerStats.cpp @@ -6,7 +6,6 @@ * */ -#include #include namespace Multiplayer @@ -32,86 +31,65 @@ namespace Multiplayer void MultiplayerStats::RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) { - if (auto* perEntityStats = AZ::Interface::Get()) - { - perEntityStats->RecordEntitySerializeStart(mode, entityId, entityName); - } + m_events.m_entitySerializeStart.Signal(mode, entityId, entityName); } void MultiplayerStats::RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, NetComponentId netComponentId) { - if (auto* perEntityStats = AZ::Interface::Get()) - { - perEntityStats->RecordComponentSerializeEnd(mode, netComponentId); - } + m_events.m_componentSerializeEnd.Signal(mode, netComponentId); } void MultiplayerStats::RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) { - if (auto* perEntityStats = AZ::Interface::Get()) - { - perEntityStats->RecordEntitySerializeStop(mode, entityId, entityName); - } + m_events.m_entitySerializeStop.Signal(mode, entityId, entityName); } void MultiplayerStats::RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes) { - if (auto* perEntityStats = AZ::Interface::Get()) - { - perEntityStats->RecordPropertySent(netComponentId, propertyId, totalBytes); - } - const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t propertyIndex = aznumeric_cast(propertyId); m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_totalCalls++; m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_totalBytes += totalBytes; m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_callHistory[m_recordMetricIndex]++; m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_byteHistory[m_recordMetricIndex] += totalBytes; + + m_events.m_propertySent.Signal(netComponentId, propertyId, totalBytes); } void MultiplayerStats::RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes) { - if (auto* perEntityStats = AZ::Interface::Get()) - { - perEntityStats->RecordPropertyReceived(netComponentId, propertyId, totalBytes); - } - const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t propertyIndex = aznumeric_cast(propertyId); m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_totalCalls++; m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_totalBytes += totalBytes; m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_callHistory[m_recordMetricIndex]++; m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_byteHistory[m_recordMetricIndex] += totalBytes; + + m_events.m_propertyReceived.Signal(netComponentId, propertyId, totalBytes); } - void MultiplayerStats::RecordRpcSent(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes) + void MultiplayerStats::RecordRpcSent(AZ::EntityId entityId, const char* entityName, NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes) { - if (auto* perEntityStats = AZ::Interface::Get()) - { - perEntityStats->RecordRpcSent(netComponentId, rpcId, totalBytes); - } - const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t rpcIndex = aznumeric_cast(rpcId); m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_totalCalls++; m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_totalBytes += totalBytes; m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_callHistory[m_recordMetricIndex]++; m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_byteHistory[m_recordMetricIndex] += totalBytes; + + m_events.m_rpcSent.Signal(entityId, entityName, netComponentId, rpcId, totalBytes); } - void MultiplayerStats::RecordRpcReceived(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes) + void MultiplayerStats::RecordRpcReceived(AZ::EntityId entityId, const char* entityName, NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes) { - if (auto* perEntityStats = AZ::Interface::Get()) - { - perEntityStats->RecordRpcReceived(netComponentId, rpcId, totalBytes); - } - const uint16_t netComponentIndex = aznumeric_cast(netComponentId); const uint16_t rpcIndex = aznumeric_cast(rpcId); m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_totalCalls++; m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_totalBytes += totalBytes; m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_callHistory[m_recordMetricIndex]++; m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_byteHistory[m_recordMetricIndex] += totalBytes; + + m_events.m_rpcReceived.Signal(entityId, entityName, netComponentId, rpcId, totalBytes); } void MultiplayerStats::TickStats(AZ::TimeMs metricFrameTimeMs) @@ -231,4 +209,15 @@ namespace Multiplayer } return result; } + + void MultiplayerStats::ConnectHandlers(EventHandlers& handlers) + { + handlers.m_entitySerializeStart.Connect(m_events.m_entitySerializeStart); + handlers.m_componentSerializeEnd.Connect(m_events.m_componentSerializeEnd); + handlers.m_entitySerializeStop.Connect(m_events.m_entitySerializeStop); + handlers.m_propertySent.Connect(m_events.m_propertySent); + handlers.m_propertyReceived.Connect(m_events.m_propertyReceived); + handlers.m_rpcSent.Connect(m_events.m_rpcSent); + handlers.m_rpcReceived.Connect(m_events.m_rpcReceived); + } } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 2afadbe4a4..457ed3eed5 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -443,12 +443,8 @@ namespace Multiplayer { // Received rpc metrics, log rpc sent, number of bytes, and the componentId/rpcId for bandwidth metrics MultiplayerStats& stats = GetMultiplayer()->GetStats(); - stats.RecordEntitySerializeStart(AzNetworking::SerializerMode::ReadFromObject, - GetEntityHandle().GetEntity()->GetId(), GetEntityHandle().GetEntity()->GetName().c_str()); - stats.RecordRpcSent(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); - stats.RecordComponentSerializeEnd(AzNetworking::SerializerMode::ReadFromObject, entityRpcMessage.GetComponentId()); - stats.RecordEntitySerializeStop(AzNetworking::SerializerMode::ReadFromObject, - GetEntityHandle().GetEntity()->GetId(), GetEntityHandle().GetEntity()->GetName().c_str()); + stats.RecordRpcSent(GetEntityHandle().GetEntity()->GetId(), GetEntityHandle().GetEntity()->GetName().c_str(), + entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); m_replicationManager.AddDeferredRpcMessage(entityRpcMessage); } @@ -631,7 +627,8 @@ namespace Multiplayer { // Received rpc metrics, log rpc received, time spent, number of bytes, and the componentId/rpcId for bandwidth metrics MultiplayerStats& stats = GetMultiplayer()->GetStats(); - stats.RecordRpcReceived(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); + stats.RecordRpcReceived(GetEntityHandle().GetEntity()->GetId(), GetEntityHandle().GetEntity()->GetName().c_str(), + entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); if (!m_netBindComponent) { diff --git a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake index d333269a1d..37a1c91640 100644 --- a/Gems/Multiplayer/Code/multiplayer_debug_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_debug_files.cmake @@ -9,7 +9,6 @@ set(FILES Source/Debug/MultiplayerDebugByteReporter.cpp Source/Debug/MultiplayerDebugByteReporter.h - Source/Debug/MultiplayerDebugPerEntityInterface.h Source/Debug/MultiplayerDebugPerEntityReporter.cpp Source/Debug/MultiplayerDebugPerEntityReporter.h Source/Debug/MultiplayerDebugModule.cpp From e80931185bc0aab051eca321f3b602dca1e5e0d6 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 28 Jul 2021 15:59:11 +0200 Subject: [PATCH 032/251] Ported RenderPlugin from MCore::AABB to AZ::AaBB * Containing functionality verified. * Zoom to joints * Normals scale multiplier * View closeup * Calculating the scene aabb * Rendering the actor instance aabbs * Selection aabb Signed-off-by: Benjamin Jillich --- .../Source/RenderPlugin/RenderPlugin.cpp | 80 +++++++++---------- .../Source/RenderPlugin/RenderPlugin.h | 2 +- 2 files changed, 41 insertions(+), 41 deletions(-) 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..ab219b2b92 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 @@ -266,8 +266,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(); @@ -276,21 +275,20 @@ namespace EMStudio for (const EMotionFX::Node* joint : joints) { const AZ::Vector3 jointPosition = pose->GetWorldSpaceTransform(joint->GetNodeIndex()).mPosition; - - aabb.Encapsulate(jointPosition); + aabb.AddPoint(jointPosition); const AZ::u32 childCount = joint->GetNumChildNodes(); for (AZ::u32 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); + 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) @@ -619,35 +617,30 @@ namespace EMStudio EMotionFX::ActorInstance* actorInstance = EMotionFX::ActorInstance::Create(mActor); actorInstance->UpdateMeshDeformers(0.0f, true); - MCore::AABB aabb; - actorInstance->CalcMeshBasedAABB(0, &aabb); + AZ::Aabb aabb; + actorInstance->CalcMeshBasedAabb(0, &aabb); - if (aabb.CheckIfIsValid() == false) + if (!aabb.IsValid()) { - actorInstance->CalcNodeOBBBasedAABB(&aabb); + actorInstance->CalcNodeBasedAabb(&aabb); } - if (aabb.CheckIfIsValid() == false) - { - actorInstance->CalcNodeBasedAABB(&aabb); - } - - mCharacterHeight = aabb.CalcHeight(); + mCharacterHeight = aabb.GetExtents().GetZ(); mOffsetFromTrajectoryNode = aabb.GetMin().GetY() + (mCharacterHeight * 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; + mNormalsScaleMultiplier = 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 +648,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); } } } @@ -882,9 +875,9 @@ 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) @@ -922,20 +915,28 @@ namespace EMStudio } // get the mesh based AABB - MCore::AABB aabb; - actorInstance->CalcMeshBasedAABB(0, &aabb); + AZ::Aabb aabb; + 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); + } + } + + if (!finalAabb.IsValid()) + { + finalAabb.Set(AZ::Vector3(-1.0f, -1.0f, 0.0f), AZ::Vector3(1.0f, 1.0f, 0.0f)); } - return finalAABB; + return finalAabb; } @@ -1155,9 +1156,8 @@ namespace EMStudio settings.mNodeBasedColor = renderOptions->GetNodeAABBColor(); settings.mStaticBasedColor = renderOptions->GetStaticAABBColor(); settings.mMeshBasedColor = renderOptions->GetMeshAABBColor(); - settings.mCollisionMeshBasedColor = renderOptions->GetCollisionMeshAABBColor(); - renderUtil->RenderAABBs(actorInstance, settings); + renderUtil->RenderAabbs(actorInstance, settings); } if (widget->GetRenderFlag(RenderViewWidget::RENDER_OBB)) @@ -1169,10 +1169,10 @@ namespace EMStudio 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 +1185,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); @@ -1268,8 +1268,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..7fa0a880d0 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 @@ -154,7 +154,7 @@ namespace EMStudio MCORE_INLINE CommandSystem::SelectionList* GetCurrentSelection() const { return mCurrentSelection; } MCORE_INLINE MCommon::RenderUtil* GetRenderUtil() const { return mRenderUtil; } - MCore::AABB GetSceneAABB(bool selectedInstancesOnly); + AZ::Aabb GetSceneAabb(bool selectedInstancesOnly); MCommon::RenderUtil::TrajectoryTracePath* FindTracePath(EMotionFX::ActorInstance* actorInstance); void ResetSelectedTrajectoryPaths(); From 9c72510a4fb6dc10cba848752b1e788a19830d0f Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 23 Jun 2021 14:52:30 -0700 Subject: [PATCH 033/251] removing files that got added by rebase MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> (+1 squashed commits) Squashed commits: [a19269426] fixing more strings Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> (+1 squashed commits) Squashed commits: [d2a049324] fixing more strings Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> (+1 squashed commits) Squashed commits: [a1ff4c101] trying to build Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/CryEdit.cpp | 3 - Code/Editor/Export/ExportManager.cpp | 4 +- .../Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp | 2 - Code/Editor/Util/PathUtil.h | 6 +- Code/Editor/Util/StringHelpers.cpp | 120 - Code/Editor/Util/StringHelpers.h | 15 - Code/LauncherUnified/Launcher.h | 3 - Code/Legacy/CryCommon/CryArray.h | 13 +- Code/Legacy/CryCommon/CryCustomTypes.h | 46 +- Code/Legacy/CryCommon/CryFile.h | 11 +- Code/Legacy/CryCommon/CryFixedString.h | 2337 --------------- Code/Legacy/CryCommon/CryListenerSet.h | 2 +- Code/Legacy/CryCommon/CryName.h | 16 +- Code/Legacy/CryCommon/CryPath.h | 139 +- Code/Legacy/CryCommon/CrySizer.h | 6 +- Code/Legacy/CryCommon/CryString.h | 2523 ----------------- Code/Legacy/CryCommon/CryThread_windows.h | 2 +- Code/Legacy/CryCommon/CryTypeInfo.cpp | 81 +- Code/Legacy/CryCommon/CryTypeInfo.h | 9 +- Code/Legacy/CryCommon/IEntityRenderState.h | 2 +- Code/Legacy/CryCommon/IFont.h | 7 +- Code/Legacy/CryCommon/IRenderer.h | 3 +- Code/Legacy/CryCommon/ISerialize.h | 120 +- Code/Legacy/CryCommon/IShader.h | 37 +- Code/Legacy/CryCommon/ISystem.h | 2 +- Code/Legacy/CryCommon/IXml.h | 4 +- Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 3 - Code/Legacy/CryCommon/LyShine/UiBase.h | 1 - .../CryCommon/LyShine/UiSerializeHelpers.h | 148 - Code/Legacy/CryCommon/StlUtils.h | 2 +- Code/Legacy/CryCommon/StringUtils.h | 1358 --------- Code/Legacy/CryCommon/TypeInfo_decl.h | 5 +- Code/Legacy/CryCommon/UnicodeBinding.h | 58 +- Code/Legacy/CryCommon/WinBase.cpp | 2 +- Code/Legacy/CryCommon/crycommon_files.cmake | 3 - Code/Legacy/CryCommon/platform.h | 9 - Code/Legacy/CryCommon/platform_impl.cpp | 6 +- Code/Legacy/CrySystem/CmdLine.cpp | 20 +- Code/Legacy/CrySystem/DebugCallStack.cpp | 22 +- .../CrySystem/LevelSystem/LevelSystem.cpp | 2 +- .../CrySystem/LocalizedStringManager.cpp | 18 +- Code/Legacy/CrySystem/Log.cpp | 6 +- Code/Legacy/CrySystem/Log.h | 2 +- Code/Legacy/CrySystem/System.cpp | 2 +- Code/Legacy/CrySystem/SystemWin32.cpp | 12 +- Code/Legacy/CrySystem/XConsole.cpp | 2 +- Code/Legacy/CrySystem/XConsole.h | 42 +- .../CrySystem/XML/SerializeXMLReader.cpp | 4 +- .../Legacy/CrySystem/XML/SerializeXMLReader.h | 8 +- Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp | 2 +- Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp | 16 +- Code/Legacy/CrySystem/XML/XMLPatcher.cpp | 6 +- Code/Legacy/CrySystem/XML/XMLPatcher.h | 2 +- Code/Legacy/CrySystem/XML/xml.cpp | 8 +- .../AtomLyIntegration/AtomFont/FFont.h | 1 - .../Platform/Windows/FFontXML_Windows.cpp | 2 +- .../Components/BlastSystemComponent.cpp | 2 - Gems/LmbrCentral/Code/Source/LmbrCentral.cpp | 8 +- .../Code/Editor/Animation/UiAnimViewNodes.cpp | 2 +- .../Code/Editor/PropertyHandlerChar.cpp | 3 +- .../Code/Source/LyShineSystemComponent.h | 4 +- .../Platform/Windows/UiClipboard_Windows.cpp | 5 +- Gems/LyShine/Code/Source/StringUtfUtils.h | 3 +- .../LyShine/Code/Source/UiButtonComponent.cpp | 41 +- Gems/LyShine/Code/Source/UiImageComponent.cpp | 13 +- Gems/LyShine/Code/Source/UiSerialize.cpp | 64 - Gems/LyShine/Code/Source/UiTextComponent.cpp | 22 +- .../Code/Source/UiTextInputComponent.cpp | 51 +- Gems/LyShine/Code/Tests/SerializationTest.cpp | 1 - Gems/LyShine/Code/Tests/SpriteTest.cpp | 1 - .../Code/Source/Cinematics/CaptureTrack.cpp | 2 +- .../Code/Source/Cinematics/CommentTrack.cpp | 2 +- .../Code/Source/Cinematics/EventTrack.cpp | 2 +- .../Code/Source/Cinematics/SceneNode.cpp | 2 +- .../Source/Cinematics/TrackEventTrack.cpp | 2 +- .../Code/Source/MaestroSystemComponent.h | 4 +- Gems/Metastream/Code/Tests/MetastreamTest.cpp | 2 - .../Code/Source/SystemComponent.cpp | 2 - 78 files changed, 330 insertions(+), 7193 deletions(-) delete mode 100644 Code/Legacy/CryCommon/CryFixedString.h delete mode 100644 Code/Legacy/CryCommon/CryString.h delete mode 100644 Code/Legacy/CryCommon/StringUtils.h diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 4bfc6a319d..973a818b92 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -4150,15 +4150,12 @@ struct CryAllocatorsRAII CryAllocatorsRAII() { AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); - AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); } ~CryAllocatorsRAII() { - AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); } }; diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index 682dcf3980..03aa0bed8b 100644 --- a/Code/Editor/Export/ExportManager.cpp +++ b/Code/Editor/Export/ExportManager.cpp @@ -88,7 +88,7 @@ Export::CObject::CObject(const char* pName) nParent = -1; - cry_strcpy(name, pName); + azstrcpy(name, pName); materialName[0] = '\0'; @@ -102,7 +102,7 @@ Export::CObject::CObject(const char* pName) void Export::CObject::SetMaterialName(const char* pName) { - cry_strcpy(materialName, pName); + azstrcpy(materialName, pName); } diff --git a/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp b/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp index dd2a1d602a..630ab3eb8e 100644 --- a/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp +++ b/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp @@ -8,8 +8,6 @@ #include "FFMPEGPlugin.h" -#include "CryString.h" -typedef CryStringT string; #include "Include/ICommandManager.h" #include "Util/PathUtil.h" diff --git a/Code/Editor/Util/PathUtil.h b/Code/Editor/Util/PathUtil.h index 0f87df0d5c..98f484ec94 100644 --- a/Code/Editor/Util/PathUtil.h +++ b/Code/Editor/Util/PathUtil.h @@ -230,7 +230,7 @@ namespace Path } template - inline bool EndsWithSlash(CryStackStringT* path) + inline bool EndsWithSlash(AZStd::fixed_string* path) { if ((!path) || (path->empty())) { @@ -271,7 +271,7 @@ namespace Path } template - inline void AddBackslash(CryStackStringT* path) + inline void AddBackslash(AZstd::fixed_string* path) { if (path->empty()) { @@ -284,7 +284,7 @@ namespace Path } template - inline void AddSlash(CryStackStringT* path) + inline void AddSlash(AZstd::fixed_string* path) { if (path->empty()) { diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp index 836090e923..a6bf622ad0 100644 --- a/Code/Editor/Util/StringHelpers.cpp +++ b/Code/Editor/Util/StringHelpers.cpp @@ -380,126 +380,6 @@ bool StringHelpers::ContainsIgnoreCase(const wstring& str, const wstring& patter return false; } -bool StringHelpers::MatchesWildcards(const string& str, const string& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - -bool StringHelpers::MatchesWildcards(const wstring& str, const wstring& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - -bool StringHelpers::MatchesWildcardsIgnoreCase(const string& str, const string& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - -bool StringHelpers::MatchesWildcardsIgnoreCase(const wstring& str, const wstring& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - - -template -static inline bool MatchesWildcardsIgnoreCaseExt_Tpl(const TS& str, const TS& wildcards, std::vector& wildcardMatches) -{ - const typename TS::value_type* savedStrBegin = 0; - const typename TS::value_type* savedStrEnd = 0; - const typename TS::value_type* savedWild = 0; - size_t savedWildCount = 0; - - const typename TS::value_type* pStr = str.c_str(); - const typename TS::value_type* pWild = wildcards.c_str(); - size_t wildCount = 0; - - while ((*pStr) && (*pWild != '*')) - { - if (*pWild == '?') - { - wildcardMatches.push_back(TS(pStr, pStr + 1)); - ++wildCount; - } - else if (ToLower(*pWild) != ToLower(*pStr)) - { - wildcardMatches.resize(wildcardMatches.size() - wildCount); - return false; - } - ++pWild; - ++pStr; - } - - while (*pStr) - { - if (*pWild == '*') - { - if (!pWild[1]) - { - wildcardMatches.push_back(TS(pStr)); - return true; - } - savedWild = pWild++; - savedStrBegin = pStr; - savedStrEnd = pStr; - savedWildCount = wildCount; - wildcardMatches.push_back(TS(savedStrBegin, savedStrEnd)); - ++wildCount; - } - else if (*pWild == '?') - { - wildcardMatches.push_back(TS(pStr, pStr + 1)); - ++wildCount; - ++pWild; - ++pStr; - } - else if (ToLower(*pWild) == ToLower(*pStr)) - { - ++pWild; - ++pStr; - } - else - { - wildcardMatches.resize(wildcardMatches.size() - (wildCount - savedWildCount)); - wildCount = savedWildCount; - ++savedStrEnd; - pWild = savedWild + 1; - pStr = savedStrEnd; - wildcardMatches.push_back(TS(savedStrBegin, savedStrEnd)); - ++wildCount; - } - } - - while (*pWild == '*') - { - ++pWild; - wildcardMatches.push_back(TS()); - ++wildCount; - } - - if (*pWild) - { - wildcardMatches.resize(wildcardMatches.size() - wildCount); - return false; - } - - return true; -} - -bool StringHelpers::MatchesWildcardsIgnoreCaseExt(const string& str, const string& wildcards, std::vector& wildcardMatches) -{ - return MatchesWildcardsIgnoreCaseExt_Tpl(str, wildcards, wildcardMatches); -} - -bool StringHelpers::MatchesWildcardsIgnoreCaseExt(const wstring& str, const wstring& wildcards, std::vector& wildcardMatches) -{ - return MatchesWildcardsIgnoreCaseExt_Tpl(str, wildcards, wildcardMatches); -} - - string StringHelpers::TrimLeft(const string& s) { const size_t first = s.find_first_not_of(" \r\t"); diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h index c05063f207..da4aa9c9cc 100644 --- a/Code/Editor/Util/StringHelpers.h +++ b/Code/Editor/Util/StringHelpers.h @@ -11,8 +11,6 @@ #define CRYINCLUDE_CRYCOMMONTOOLS_STRINGHELPERS_H #pragma once -#include - namespace StringHelpers { // compares two strings to see if they are the same or different, case sensitive @@ -65,19 +63,6 @@ namespace StringHelpers bool ContainsIgnoreCase(const string& str, const string& pattern); bool ContainsIgnoreCase(const wstring& str, const wstring& pattern); - // checks to see if a string contains a wildcard string pattern, case sensitive - // returns true if the string does match the wildcard string pattern or false if it does not - bool MatchesWildcards(const string& str, const string& wildcards); - bool MatchesWildcards(const wstring& str, const wstring& wildcards); - - // checks to see if a string contains a wildcard string pattern, case is ignored - // returns true if the string does match the wildcard string pattern or false if it does not - bool MatchesWildcardsIgnoreCase(const string& str, const string& wildcards); - bool MatchesWildcardsIgnoreCase(const wstring& str, const wstring& wildcards); - - bool MatchesWildcardsIgnoreCaseExt(const string& str, const string& wildcards, std::vector& wildcardMatches); - bool MatchesWildcardsIgnoreCaseExt(const wstring& str, const wstring& wildcards, std::vector& wildcardMatches); - string TrimLeft(const string& s); wstring TrimLeft(const wstring& s); diff --git a/Code/LauncherUnified/Launcher.h b/Code/LauncherUnified/Launcher.h index e0b3abdf95..5ff6009e43 100644 --- a/Code/LauncherUnified/Launcher.h +++ b/Code/LauncherUnified/Launcher.h @@ -21,15 +21,12 @@ namespace O3DELauncher CryAllocatorsRAII() { AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); - AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); } ~CryAllocatorsRAII() { - AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); } }; diff --git a/Code/Legacy/CryCommon/CryArray.h b/Code/Legacy/CryCommon/CryArray.h index 167f1cfb57..8b0cea3de6 100644 --- a/Code/Legacy/CryCommon/CryArray.h +++ b/Code/Legacy/CryCommon/CryArray.h @@ -12,6 +12,7 @@ #pragma once #include "CryLegacyAllocator.h" +#include //--------------------------------------------------------------------------- // Convenient iteration macros @@ -58,18 +59,6 @@ struct fake_move_helper } }; -// Override for string to ensure proper construction -template <> -struct fake_move_helper -{ - static void move(string& dest, string& source) - { - ::new((void*)&dest) string(); - dest = source; - source.~string(); - } -}; - // Generic move function: transfer an existing source object to uninitialized dest address. // Addresses must not overlap (requirement on caller). // May be specialized for specific types, to provide a more optimal move. diff --git a/Code/Legacy/CryCommon/CryCustomTypes.h b/Code/Legacy/CryCommon/CryCustomTypes.h index 9594f5a333..74f3cbc9dc 100644 --- a/Code/Legacy/CryCommon/CryCustomTypes.h +++ b/Code/Legacy/CryCommon/CryCustomTypes.h @@ -16,10 +16,10 @@ #pragma once #include "CryTypeInfo.h" -#include "CryFixedString.h" #include #include #include +#include #define STATIC_CONST(T, name, val) \ static inline T name() { static T t = val; return t; } @@ -46,7 +46,7 @@ inline bool HasString(const T& val, FToString flags, const void* def_data = 0) float NumToFromString(float val, int digits, bool floating, char buffer[], int buf_size); template -string NumToString(T val, int min_digits, int max_digits, bool floating) +AZStd::string NumToString(T val, int min_digits, int max_digits, bool floating) { char buffer[64]; float f(val); @@ -68,7 +68,7 @@ struct CStructInfo { CStructInfo(cstr name, size_t size, size_t align, Array vars = Array(), Array templates = Array()); virtual bool IsType(CTypeInfo const& Info) const; - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const; + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const; virtual bool FromString(void* data, cstr str, FFromString flags = 0) const; virtual bool ToValue(const void* data, void* value, const CTypeInfo& typeVal) const; virtual bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const; @@ -86,9 +86,9 @@ struct CStructInfo } protected: - Array Vars; - CryStackStringT EndianDesc; // Encodes instructions for endian swapping. - bool HasBitfields; + Array Vars; + AZStd::fixed_string<16> EndianDesc; // Encodes instructions for endian swapping. + bool HasBitfields; Array TemplateTypes; void MakeEndianDesc(); @@ -124,11 +124,11 @@ struct TTypeInfo return false; } - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const { if (!HasString(*(const T*)data, flags, def_data)) { - return string(); + return AZStd::string(); } return ::ToString(*(const T*)data); } @@ -193,7 +193,7 @@ struct TProxyTypeInfo return false; } - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const { T val = T(*(const S*)data); T def_val = def_data ? T(*(const S*)def_data) : T(); @@ -234,32 +234,32 @@ protected: // Customisation for string. template<> -inline string TTypeInfo::ToString(const void* data, FToString flags, const void* def_data) const +inline AZStd::string TTypeInfo::ToString(const void* data, FToString flags, const void* def_data) const { - const string& val = *(const string*)data; + const AZStd::string& val = *(const AZStd::string*)data; if (def_data && flags.SkipDefault) { - if (val == *(const string*)def_data) + if (val == *(const AZStd::string*)def_data) { - return string(); + return AZStd::string(); } } return val; } template<> -inline bool TTypeInfo::FromString(void* data, cstr str, FFromString flags) const +inline bool TTypeInfo::FromString(void* data, cstr str, FFromString flags) const { if (!*str && flags.SkipEmpty) { return true; } - *(string*)data = str; + *(AZStd::string*)data = str; return true; } template<> -void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const; +void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const; //--------------------------------------------------------------------------- // @@ -632,11 +632,11 @@ protected: } // Override ToString: Limit to significant digits. - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const { if (!HasString(*(const S*)data, flags, def_data)) { - return string(); + return AZStd::string(); } static int digits = int_ceil(log10f(float(nQUANT))); return NumToString(*(const TFixed*)data, 1, digits + 3, true); @@ -907,12 +907,12 @@ struct TEnumInfo return false; } - virtual string ToString(const void* data, FToString flags, const void* def_data) const + virtual AZStd::string ToString(const void* data, FToString flags, const void* def_data) const { TInt val = *(const TInt*)(data); if (flags.SkipDefault && val == (def_data ? *(const TInt*)def_data : TInt(0))) { - return string(); + return AZStd::string(); } if (cstr sName = TEnumDef::ToName(val)) @@ -1153,13 +1153,13 @@ struct CEnumDefUuid return false; } - string ToString(const void* data, FToString flags, const void* def_data) const override + AZStd::string ToString(const void* data, FToString flags, const void* def_data) const override { const AZ::Uuid& uuidData = *reinterpret_cast(data); const AZ::Uuid& defUuidData = *reinterpret_cast(def_data); if (flags.SkipDefault && uuidData == (def_data ? defUuidData : AZ::Uuid::CreateNull())) { - return string(); + return AZStd::string(); } if (cstr sName = ToName(uuidData)) @@ -1167,7 +1167,7 @@ struct CEnumDefUuid return sName; } - return string(); + return AZStd::string(); } bool FromString(void* data, cstr str, FFromString flags) const override diff --git a/Code/Legacy/CryCommon/CryFile.h b/Code/Legacy/CryCommon/CryFile.h index a043e4fa9b..0888216f9c 100644 --- a/Code/Legacy/CryCommon/CryFile.h +++ b/Code/Legacy/CryCommon/CryFile.h @@ -18,7 +18,6 @@ #include #include #include -#include "StringUtils.h" #include ////////////////////////////////////////////////////////////////////////// @@ -222,7 +221,7 @@ inline CCryFile::~CCryFile() inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlagsEx) { char tempfilename[CRYFILE_MAX_PATH] = ""; - cry_strcpy(tempfilename, filename); + azstrcpy(tempfilename, filename); #if !defined (_RELEASE) if (gEnv && gEnv->IsEditor() && gEnv->pConsole) @@ -233,8 +232,8 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag const int lowercasePaths = pCvar->GetIVal(); if (lowercasePaths) { - const string lowerString = PathUtil::ToLower(tempfilename); - cry_strcpy(tempfilename, lowerString.c_str()); + const AZStd::string lowerString = PathUtil::ToLower(tempfilename); + azstrcpy(tempfilename, lowerString.c_str()); } } } @@ -243,7 +242,7 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag { Close(); } - cry_strcpy(m_filename, tempfilename); + azstrcpy(m_filename, tempfilename); if (m_pIArchive) { @@ -430,7 +429,7 @@ inline const char* CCryFile::GetAdjustedFilename() const // Returns standard path otherwise. if (gameUrl != &szAdjustedFile[0]) { - cry_strcpy(szAdjustedFile, gameUrl); + azstrcpy(szAdjustedFile, gameUrl); } return szAdjustedFile; } diff --git a/Code/Legacy/CryCommon/CryFixedString.h b/Code/Legacy/CryCommon/CryFixedString.h deleted file mode 100644 index 299a5718a7..0000000000 --- a/Code/Legacy/CryCommon/CryFixedString.h +++ /dev/null @@ -1,2337 +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 : Stack-based fixed-size String class, similar to CryString. -// will switch to heap-based allocation when string does no longer fit -// Can easily be substituted instead of CryString. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H -#define CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "CryString.h" - -#ifndef CRY_STRING_DEBUG -#define CRY_STRING_DEBUG(s) -#endif - -#define UNITTEST_CRYFIXEDSTRING (0) - -template -class CharTraits; - -// traits for char -template <> -class CharTraits -{ -public: - typedef size_t size_type; - typedef char value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - ILINE int _isspace(value_type c) const - { - return ::isspace((int)c); - } - - ILINE value_type _traits_toupper(value_type c) const - { - return static_cast(toupper(c)); - } - - ILINE value_type _traits_tolower(value_type c) const - { - return static_cast(tolower(c)); - } - - ILINE value_type _ascii_tolower(value_type c) const - { - return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; - } - - ILINE value_type _ascii_toupper(value_type c) const - { - return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; - } - - ILINE int _strcmp (const_str a, const_str b) const - { - return ::strcmp(a, b); - } - - ILINE int _strncmp (const_str a, const_str b, size_type n) const - { - return ::strncmp(a, b, n); - } - - ILINE int _stricmp (const_str a, const_str b) const - { - return ::azstricmp(a, b); - } - - ILINE int _strnicmp (const_str a, const_str b, size_type n) const - { - return ::azstrnicmp(a, b, n); - } - - ILINE size_type _strspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::strspn(str, strCharSet); - } - - ILINE size_type _strcspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::strcspn(str, strCharSet); - } - - static ILINE size_type _strlen(const_str str) - { - return (str == NULL) ? 0 : (size_type)::strlen(str); - } - - ILINE const_str _strchr(const_str str, value_type c) const - { - return (str == NULL) ? 0 : ::strchr(str, c); - } - - ILINE value_type* _strstr(value_type* str, const_str strSearch) const - { - return (str == NULL) ? 0 : (value_type*) ::strstr(str, strSearch); - } - - ILINE void _copy(value_type* dest, const value_type* src, size_type count) - { - memcpy(dest, src, count * sizeof(value_type)); - } - - ILINE void _move(value_type* dest, const value_type* src, size_type count) - { - memmove(dest, src, count * sizeof(value_type)); - } - - ILINE void _set(value_type* dest, value_type ch, size_type count) - { - memset(dest, ch, count * sizeof(value_type)); - } - - ILINE int _vsnprintf(value_type* str, size_type size, const_str format, va_list ap) - { - return ::azvsnprintf(str, size, format, ap); - } -}; - -// traits for wchar_t -template <> -class CharTraits -{ -public: - typedef size_t size_type; - typedef wchar_t value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - ILINE int _isspace(value_type c) const - { - return iswspace(c); - } - - ILINE value_type _traits_toupper(value_type c) const - { - return towupper(c); - } - - ILINE value_type _traits_tolower(value_type c) const - { - return towlower(c); - } - - ILINE value_type _ascii_tolower(value_type c) const - { - return ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)); - } - - ILINE value_type _ascii_toupper(value_type c) const - { - return ((((c) >= 'a') && ((c) <= 'z')) ? ((c) - 'a' + 'A') : (c)); - } - - ILINE int _strcmp (const_str a, const_str b) const - { - return wcscmp (a, b); - } - - ILINE int _strncmp (const_str a, const_str b, size_type n) const - { - return wcsncmp (a, b, n); - } - - ILINE int _stricmp (const_str a, const_str b) const - { - return azwcsicmp(a, b); - } - - ILINE int _strnicmp (const_str a, const_str b, size_type n) const - { - return azwcsnicmp(a, b, n); - } - - ILINE size_type _strspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::wcsspn(str, strCharSet); - } - - ILINE size_type _strcspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::wcscspn(str, strCharSet); - } - - static ILINE size_type _strlen(const_str str) - { - return (str == NULL) ? 0 : (size_type)::wcslen(str); - } - - ILINE const_str _strchr(const_str str, value_type c) const - { - return (str == NULL) ? 0 : ::wcschr(str, c); - } - - ILINE value_type* _strstr(value_type* str, const_str strSearch) const - { - return (str == NULL) ? 0 : ::wcsstr(str, strSearch); - } - - ILINE void _copy(value_type* dest, const value_type* src, size_type count) - { - memcpy(dest, src, count * sizeof(value_type)); - } - - ILINE void _move(value_type* dest, const value_type* src, size_type count) - { - memmove(dest, src, count * sizeof(value_type)); - } - - ILINE void _set(value_type* dest, value_type ch, size_type count) - { - wmemset(dest, ch, count); - } - - ILINE int _vsnprintf(value_type* str, size_type size, const_str format, va_list ap) - { - return ::_vsnwprintf_s(str, size + 1, size, format, ap); - } -}; - -template -class CryStackStringT - : public CharTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // Types compatible with STL string. - ////////////////////////////////////////////////////////////////////////// - typedef CryStackStringT _Self; - typedef size_t size_type; - typedef T value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - - enum _npos_type - { - npos = (size_type) ~0 - }; - - ////////////////////////////////////////////////////////////////////////// - // Constructors - ////////////////////////////////////////////////////////////////////////// - CryStackStringT(); - -public: - - CryStackStringT(const _Self& str); - CryStackStringT(const _Self& str, size_type nOff, size_type nCount); - CryStackStringT(size_type nRepeat, value_type ch); - - // The reason of making this constructor unavailable (for a while) is - // explained in comments in front of the declaration of - // CryStringT::CryStringT(size_type nRepeat, value_type ch) - // (see CryString.h). -private: - CryStackStringT(value_type ch, size_type nRepeat); - -public: - - CryStackStringT(const_str str); - CryStackStringT(const CryStringT& str); - CryStackStringT(const_str str, size_type nLength); - CryStackStringT(const_iterator _First, const_iterator _Last); - ~CryStackStringT(); - - ////////////////////////////////////////////////////////////////////////// - // STL string like interface. - ////////////////////////////////////////////////////////////////////////// - //! Operators. - size_type length() const; - size_type size() const; - bool empty() const; - void clear(); // free up the data - - //! Returns the storage currently allocated to hold the string, a value at least as large as length(). - // Also: capacity is always >= (MAX_SIZE-1) - size_type capacity() const; - - // Sets the capacity of the string to a number at least as great as a specified number. - // nCount = 0 is shrinking string to fit number of characters in it. - // Shrink to fit post-cond: capacity() >= (MAX_SIZE-1) - void reserve(size_type nCount = 0); - - _Self& append(const value_type* _Ptr); - _Self& append(const value_type* _Ptr, size_type nCount); - _Self& append(const _Self& _Str, size_type nOff, size_type nCount); - _Self& append(const _Self& _Str); - _Self& append(size_type nCount, value_type _Ch); - _Self& append(const_iterator _First, const_iterator _Last); - - _Self& assign(const_str _Ptr); - _Self& assign(const_str _Ptr, size_type nCount); - _Self& assign(const _Self& _Str, size_type off, size_type nCount); - _Self& assign(const _Self& _Str); - _Self& assign(size_type nCount, value_type _Ch); - _Self& assign(const_iterator _First, const_iterator _Last); - - value_type at(size_type index) const; - //value_type& at( size_type index ); - - const_iterator begin() const { return m_str; }; - const_iterator end() const { return m_str + length(); }; - - iterator begin() { return m_str; }; - iterator end() { return m_str + length(); }; - - //! cast to C string operator. - operator const_str() const { - return m_str; - } - - //! cast to C string. - const value_type* c_str() const { return m_str; } - const value_type* data() const { return m_str; }; - - ////////////////////////////////////////////////////////////////////////// - // string comparison. - ////////////////////////////////////////////////////////////////////////// - int compare(const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compare(const value_type* _Ptr) const; - int compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Case insensitive comparison - int compareNoCase(const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compareNoCase(const value_type* _Ptr) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Copies at most a specified number of characters from an indexed position in a source string to a target character array. - size_type copy(value_type* _Ptr, size_type nCount, size_type nOff = 0) const; - - void push_back(value_type _Ch) { _ConcatenateInPlace(&_Ch, 1); } - void resize(size_type nCount, value_type _Ch = ' '); - - //! simple sub-string extraction - _Self substr(size_type pos, size_type count = npos) const; - - // replace part of string. - _Self& replace(value_type chOld, value_type chNew); - _Self& replace(const_str strOld, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew, size_type count2); - _Self& replace(size_type pos, size_type count, size_type nNumChars, value_type chNew); - - // insert new elements to string. - _Self& insert(size_type nIndex, value_type ch); - _Self& insert(size_type nIndex, size_type nCount, value_type ch); - _Self& insert(size_type nIndex, const_str pstr); - _Self& insert(size_type nIndex, const_str pstr, size_type nCount); - - //! delete count characters starting at zero-based index - _Self& erase(size_type nIndex, size_type count = npos); - - //! searching (return starting index, or -1 if not found) - //! look for a single character match - //! like "C" strchr - size_type find(value_type ch, size_type pos = 0) const; - //! look for a specific sub-string - //! like "C" strstr - size_type find(const_str subs, size_type pos = 0) const; - size_type rfind(value_type ch, size_type pos = npos) const; - - size_type find_first_of(value_type _Ch, size_type nOff = 0) const; - size_type find_first_of(const_str charSet, size_type nOff = 0) const; - //size_type find_first_of( const value_type* _Ptr,size_type _Off,size_type _Count ) const; - size_type find_first_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_first_not_of(value_type _Ch, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_first_not_of(const _Self& _Str, size_type _Off = 0) const; - - void swap(_Self& _Str); - - ////////////////////////////////////////////////////////////////////////// - // overloaded operators. - ////////////////////////////////////////////////////////////////////////// - // overloaded indexing. - value_type operator[](size_type index) const; - // value_type& operator[]( size_type index ); // same as at() - - // overloaded assignment - _Self& operator=(const _Self& str); - _Self& operator=(value_type ch); - _Self& operator=(const_str str); - _Self& operator=(const CryStringT& str); - - void move(_Self& src); - -#if defined(LINUX) || defined(APPLE) - template - _Self& operator=(const CryStackStringT& str) - { - _Assign(str.c_str(), str.size()); - return *this; - } -#endif - - // string concatenation - _Self& operator+=(const _Self& str); - _Self& operator+=(value_type ch); - _Self& operator+=(const_str str); - _Self& operator+=(const CryStringT& str); - - size_t GetAllocatedMemory() const - { - size_t size = sizeof(*this); - if (m_str != m_strBuf) - { - size += (m_nAllocSize + 1) * sizeof(value_type); - } - return size; - } - - ////////////////////////////////////////////////////////////////////////// - // Extended functions. - // This functions are not in the STL string. - // They have an ATL CString interface. - ////////////////////////////////////////////////////////////////////////// - //! Format string, use (sprintf) - _Self& Format(const value_type* format, ...); - - //! Format string fast, directly formats into string's buffer. - // Make sure there is enough space to hold the string - _Self& FormatFast (const value_type* format, ...); - - //! Converts the string to lower-case. - // This function uses the "C" locale for case-conversion (ie, A-Z only). - _Self& MakeLower(); - - //! Converts the string to upper-case. - // This function uses the "C" locale for case-conversion (ie, A-Z only). - _Self& MakeUpper(); - - _Self& Trim(); - _Self& Trim(value_type ch); - _Self& Trim(const value_type* sCharSet); - - _Self& TrimLeft(); - _Self& TrimLeft(value_type ch); - _Self& TrimLeft(const value_type* sCharSet); - - _Self& TrimRight(); - _Self& TrimRight(value_type ch); - _Self& TrimRight(const value_type* sCharSet); - - _Self SpanIncluding(const_str charSet) const; - _Self SpanExcluding(const_str charSet) const; - _Self Tokenize(const_str charSet, int& nStart) const; - _Self Mid(size_type nFirst, size_type nCount = npos) const { return substr(nFirst, nCount); }; - - _Self Left(size_type count) const; - _Self Right(size_type count) const; - ////////////////////////////////////////////////////////////////////////// - - // public utilities. - static bool _IsValidString(const_str str); - -public: - ////////////////////////////////////////////////////////////////////////// - // Only used for debugging statistics. - ////////////////////////////////////////////////////////////////////////// - static size_t _usedMemory(size_t size) - { - static size_t s_used_memory = 0; - s_used_memory += size; - return s_used_memory; - } - - //private: -public: - size_type m_nLength; - size_type m_nAllocSize; - value_type* m_str; // pointer to ref counted string data - value_type m_strBuf[MAX_SIZE]; - - // implementation helpers - void _AllocData(size_type nLen); - void _FreeData(value_type* pData); - void _Free(); - void _Initialize(); - - void _Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2); - void _ConcatenateInPlace(const_str sStr, size_type nLen); - void _Assign(const_str sStr, size_type nLen); - void _MakeUnique(); -}; - - -///////////////////////////////////////////////////////////////////////////// -// CryStackStringT Implementation -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -template -inline bool CryStackStringT::_IsValidString(const_str) -{ - return true; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Assign(const_str sStr, size_type nLen) -{ - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (nLen > capacity()) - { - _Free(); - _AllocData(nLen); - } - // Copy characters from new string to this buffer. - CharTraits::_copy(m_str, sStr, nLen); - // Set new length. - m_nLength = nLen; - // Make null terminated string. - m_str[nLen] = 0; - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2) -{ - size_type nLen = nLen1 + nLen2; - if (nLen1 * 2 > nLen) - { - nLen = nLen1 * 2; - } - if (nLen != 0) - { - if (nLen < 8) - { - nLen = 8; - } - _AllocData(nLen); - CharTraits::_copy(m_str, sStr1, nLen1); - CharTraits::_copy(m_str + nLen1, sStr2, nLen2); - m_nLength = nLen1 + nLen2; - m_str[nLen1 + nLen2] = 0; - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_ConcatenateInPlace(const_str sStr, size_type nLen) -{ - if (nLen != 0) - { - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (length() + nLen > capacity()) - { - value_type* pOldData = m_str; - _Concatenate(m_str, length(), sStr, nLen); - _FreeData(pOldData); - } - else - { - CharTraits::_copy(m_str + length(), sStr, nLen); - m_nLength += nLen; - m_str[m_nLength] = 0; // Make null terminated string. - } - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_MakeUnique() -{ -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Initialize() -{ - m_strBuf[0] = 0; - m_str = m_strBuf; - m_nLength = 0; - m_nAllocSize = MAX_SIZE - 1; // 0 termination not counted! -} - -// always allocate one extra character for '\0' termination -// assumes [optimistically] that data length will equal allocation length -template -inline void CryStackStringT::_AllocData(size_type nLen) -{ - assert(nLen >= 0); - assert(nLen <= INT_MAX - 1); // max size (enough room for 1 extra) - - if (nLen == 0) - { - _Initialize(); - } - else - { - size_type allocLen = (nLen + 1) * sizeof(value_type); - value_type* pData = m_strBuf; - if (allocLen > MAX_SIZE) - { - pData = (value_type*)CryModuleMalloc(allocLen); - _usedMemory(allocLen); // For statistics. - m_nAllocSize = nLen; - } - else - { - m_nAllocSize = MAX_SIZE - 1; - } - m_nLength = nLen; - m_str = pData; - m_str[nLen] = 0; // null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Free() -{ - _FreeData(m_str); - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_FreeData(value_type* pData) -{ - if (pData != m_strBuf) - { - size_t allocLen = (m_nAllocSize + 1) * sizeof(value_type); - _usedMemory(-check_cast(allocLen)); // For statistics. - CryModuleFree(pData); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT() -{ - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStackStringT& str) -{ - _Initialize(); - _Assign(str.c_str(), str.length()); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStackStringT& str, size_type nOff, size_type nCount) -{ - _Initialize(); - assign(str, nOff, nCount); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_str str) -{ - _Initialize(); - // Make a copy of C string. - size_type nLen = this->_strlen(str); - if (nLen != 0) - { - _AllocData(nLen); - CharTraits::_copy(m_str, str, nLen); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStringT& str) -{ - _Initialize(); - size_t nLength = str.size(); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, str.c_str(), nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_str str, size_type nLength) -{ - _Initialize(); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -// The reason of making this constructor unavailable (for a while) is -// explained in comments in front of the declaration of -// CryStringT::CryStringT(size_type nRepeat, value_type ch) -// (see CryString.h). -template -inline CryStackStringT::CryStackStringT(size_type nRepeat, value_type ch) -{ - _Initialize(); - if (nRepeat > 0) - { - _AllocData(nRepeat); - CharTraits::_set(m_str, ch, nRepeat); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_iterator _First, const_iterator _Last) -{ - _Initialize(); - size_type nLength = (size_type)(_Last - _First); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, _First, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::~CryStackStringT() -{ - _FreeData(m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::length() const -{ - return m_nLength; -} -template -inline typename CryStackStringT::size_type CryStackStringT::size() const -{ - return m_nLength; -} -template -inline typename CryStackStringT::size_type CryStackStringT::capacity() const -{ - return m_nAllocSize; -} - -template -inline bool CryStackStringT::empty() const -{ - return length() == 0; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::clear() -{ - if (length() == 0) - { - return; - } - _Free(); - assert(length() == 0); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::reserve(size_type nCount) -{ - // Reserve of 0 is shrinking container to fit number of characters in it.. - if (nCount > capacity()) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - _AllocData(nCount); - CharTraits::_copy(m_str, pOldData, nOldLength); - m_nLength = nOldLength; - m_str[m_nLength] = 0; - _FreeData(pOldData); - } - else if (nCount == 0) - { - if (length() != capacity()) - { - value_type* pOldData = m_str; - if (pOldData != m_strBuf) // in case we fit into our static buffer, we cannot shrink anyway - { - size_type nOldLength = m_nLength; - _AllocData(m_nLength); - // if (pOldData != m_strBuf || m_str != m_strBuf) // actually always true - // { - CharTraits::_copy(m_str, pOldData, nOldLength); // we can safely use CharTraits::_copy, as we never overlap here (in case of static buffer, we don't shrink anyway) - _FreeData(pOldData); - // } - } - } - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_str _Ptr) -{ - *this += _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_str _Ptr, size_type nCount) -{ - _ConcatenateInPlace(_Ptr, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const CryStackStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _ConcatenateInPlace(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const CryStackStringT& _Str) -{ - *this += _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(size_type nCount, value_type _Ch) -{ - if (nCount > 0) - { - if (length() + nCount >= capacity()) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - _AllocData(length() + nCount); - CharTraits::_copy(m_str, pOldData, nOldLength); - CharTraits::_set(m_str + nOldLength, _Ch, nCount); - _FreeData(pOldData); - } - else - { - size_type nOldLength = length(); - CharTraits::_set(m_str + nOldLength, _Ch, nCount); - m_nLength = nOldLength + nCount; - m_str[length()] = 0; // Make null terminated string. - } - } - CRY_STRING_DEBUG(m_str) - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_iterator _First, const_iterator _Last) -{ - append(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_str _Ptr) -{ - *this = _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_str _Ptr, size_type nCount) -{ - size_type len = this->_strlen(_Ptr); - _Assign(_Ptr, (nCount < len) ? nCount : len); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const CryStackStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _Assign(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const CryStackStringT& _Str) -{ - *this = _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(size_type nCount, value_type _Ch) -{ - if (nCount >= 1) - { - _AllocData(nCount); - CharTraits::_set(m_str, _Ch, nCount); - CRY_STRING_DEBUG(m_str) - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_iterator _First, const_iterator _Last) -{ - assign(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::value_type CryStackStringT::at(size_type index) const -{ - assert(index >= 0 && index < length()); - return m_str[index]; -} - -/* -inline value_type& CryStackStringT::at( size_type index ) -{ -// same as GetAt -assert( index >= 0 && index < length() ); -return m_str[index]; -} -*/ - -template -inline typename CryStackStringT::value_type CryStackStringT::operator[](size_type index) const -{ - assert(index < length()); - return m_str[index]; -} - - -/* -inline value_type& CryStackStringT::operator[]( size_type index ) -{ -// same as GetAt -assert( index >= 0 && index < length() ); -return m_str[index]; -} -*/ - - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStackStringT::compare(const CryStackStringT& _Str) const -{ - return CharTraits::_strcmp(m_str, _Str.m_str); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str) const -{ - return compare(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str, size_type nOff, size_type nCount) const -{ - assert(nOff < _Str.length()); - return compare(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStackStringT::compare(const value_type* _Ptr) const -{ - return CharTraits::_strcmp(m_str, _Ptr); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - assert(_Pos1 < length()); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : CharTraits::_strncmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStackStringT::compareNoCase(const CryStackStringT& _Str) const -{ - return CharTraits::_stricmp(m_str, _Str.m_str); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str) const -{ - return compareNoCase(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str, size_type nOff, size_type nCount) const -{ - assert(nOff < _Str.length()); - return compareNoCase(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStackStringT::compareNoCase(const value_type* _Ptr) const -{ - return CharTraits::_stricmp(m_str, _Ptr); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - assert(_Pos1 < length()); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : CharTraits::_strnicmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::copy(value_type* _Ptr, size_type nCount, size_type nOff) const -{ - assert(nOff < length()); - if (nCount < 0) - { - nCount = 0; - } - if (nOff + nCount > length()) // trim to offset. - { - nCount = length() - nOff; - } - - CharTraits::_copy(_Ptr, m_str + nOff, nCount); - return nCount; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::resize(size_type nCount, value_type _Ch) -{ - _MakeUnique(); - if (nCount > length()) - { - size_type numToAdd = nCount - length(); - append(numToAdd, _Ch); - } - else if (nCount < length()) - { - m_nLength = nCount; - m_str[length()] = 0; // Make null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -//! compare helpers -template -inline bool operator==(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) == 0; } -template -inline bool operator!=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) != 0; } -template -inline bool operator<(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) > 0; } -template -inline bool operator>(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) < 0; } -template -inline bool operator<=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) >= 0; } -template -inline bool operator>=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) <= 0; } - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::operator=(value_type ch) -{ - _Assign(&ch, 1); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& string1, typename CryStackStringT::value_type ch) -{ - CryStackStringT s(string1); - s.append(1, ch); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(typename CryStackStringT::value_type ch, const CryStackStringT& str) -{ - CryStackStringT s; - s.reserve(str.size() + 1); - s.append(1, ch); - s.append(str); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& string1, const CryStackStringT& string2) -{ - CryStackStringT s(string1); - s.append(string2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& str1, const typename CryStackStringT::value_type* str2) -{ - CryStackStringT s(str1); - s.append(str2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const typename CryStackStringT::value_type* str1, const CryStackStringT& str2) -{ - assert(str1 == NULL || (CryStackStringT::_IsValidString(str1))); - CryStackStringT s; - s.reserve(CharTraits::_strlen(str1) + str2.size()); - s.append(str1); - s.append(str2); - return s; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const CryStackStringT& str) -{ - _Assign (str.c_str(), str.length()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const_str str) -{ - assert(str == NULL || _IsValidString(str)); - _Assign(str, this->_strlen(str)); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const CryStringT& str) -{ - _Assign(str.c_str(), str.size()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const CryStringT& str) -{ - _ConcatenateInPlace(str.c_str(), str.size()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const_str str) -{ - assert(str == NULL || _IsValidString(str)); - _ConcatenateInPlace(str, this->_strlen(str)); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(value_type ch) -{ - _ConcatenateInPlace(&ch, 1); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const CryStackStringT& str) -{ - _ConcatenateInPlace(str.m_str, str.length()); - return *this; -} - -//! find first single character -template -inline typename CryStackStringT::size_type CryStackStringT::find(value_type ch, size_type pos) const -{ - if (!(/*pos >= 0 && */ pos <= length())) - { - return (typename CryStackStringT::size_type)npos; - } - const_str str = CharTraits::_strchr(m_str + pos, ch); - // return npos if not found and index otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find a sub-string (like strstr) -template -inline typename CryStackStringT::size_type CryStackStringT::find(const_str subs, size_type pos) const -{ - assert(_IsValidString(subs)); - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - // find first matching substring - const_str str = CharTraits::_strstr(m_str + pos, subs); - - // return npos for not found, distance from beginning otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find last single character -template -inline typename CryStackStringT::size_type CryStackStringT::rfind(value_type ch, size_type pos) const -{ - const_str str; - if (pos == npos) - { - // find last single character - str = strrchr(m_str, ch); - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); - } - else - { - if (pos == npos) - { - pos = length(); - } - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - value_type tmp = m_str[pos + 1]; - m_str[pos + 1] = 0; - str = strrchr(m_str, ch); - m_str[pos + 1] = tmp; - } - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(const CryStackStringT& _Str, size_type _Off) const -{ - return find_first_of(_Str.m_str, _Off); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(value_type _Ch, size_type nOff) const -{ - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - value_type charSet[2] = { _Ch, 0 }; - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? -1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(const_str charSet, size_type nOff) const -{ - assert(_IsValidString(charSet)); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -//size_type find_first_not_of(const _Self& __s, size_type __pos = 0) const -//{ return find_first_not_of(__s._M_start, __pos, __s.size()); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const -//{ _STLP_FIX_LITERAL_BUG(__s) return find_first_not_of(__s, __pos, _Traits::length(__s)); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const; - -//size_type find_first_not_of(_CharT __c, size_type __pos = 0) const; - - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const value_type* _Ptr, size_type _Off) const -{ return find_first_not_of(_Ptr, _Off, this->_strlen(_Ptr)); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const CryStackStringT& _Str, size_type _Off) const -{ return find_first_not_of(_Str.m_str, _Off); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(value_type _Ch, size_type _Off) const -{ - if (_Off > length()) - { - return npos; - } - else - { - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - if (*str != _Ch) - { - return size_type(str - begin()); // Character found! - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - if (_Off > length()) - { - return npos; - } - else - { - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - const value_type* c; - for (c = charsFirst; c != charsLast; ++c) - { - if (*c == *str) - { - break; - } - } - if (c == charsLast) - { - return size_type(str - begin());// Current character not in char set. - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT CryStackStringT::substr(size_type pos, size_type count) const -{ - if (pos >= length()) - { - return CryStackStringT(); - } - if (count == npos) - { - count = length() - pos; - } - if (pos + count > length()) - { - count = length() - pos; - } - return CryStackStringT(m_str + pos, count); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::erase(size_type nIndex, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - if (nCount < 0 || nCount > length() - nIndex) - { - nCount = length() - nIndex; - } - if (nCount > 0 && nIndex < length()) - { - _MakeUnique(); - size_type nNumToCopy = length() - (nIndex + nCount) + 1; - CharTraits::_move(m_str + nIndex, m_str + nIndex + nCount, nNumToCopy); - m_nLength = length() - nCount; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, value_type ch) -{ - return insert(nIndex, 1, ch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, size_type nCount, value_type ch) -{ - _MakeUnique(); - - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nNewLength = length(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nCount; - - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - const_str pstr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pstr, nOldLength + 1); - _FreeData(pOldData); - } - - CharTraits::_move(m_str + nIndex + nCount, m_str + nIndex, (nNewLength - nIndex)); - CharTraits::_set(m_str + nIndex, ch, nCount); - m_nLength = nNewLength; - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, const_str pstr, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nInsertLength = nCount; - size_type nNewLength = length(); - if (nInsertLength > 0) - { - _MakeUnique(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nInsertLength; - - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - const_str pOldStr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pOldStr, (nOldLength + 1)); - _FreeData(pOldData); - } - - CharTraits::_move(m_str + nIndex + nInsertLength, m_str + nIndex, (nNewLength - nIndex - nInsertLength + 1)); - CharTraits::_copy(m_str + nIndex, pstr, nInsertLength); - m_nLength = nNewLength; - m_str[length()] = 0; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, const_str pstr) -{ - return insert(nIndex, pstr, this->_strlen(pstr)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, const_str strNew) -{ - return replace(pos, count, strNew, this->_strlen(strNew)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, const_str strNew, size_type count2) -{ - erase(pos, count); - insert(pos, strNew, count2); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, size_type nNumChars, value_type chNew) -{ - erase(pos, count); - insert(pos, nNumChars, chNew); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(value_type chOld, value_type chNew) -{ - if (chOld != chNew) - { - _MakeUnique(); - value_type* strend = m_str + length(); - for (value_type* str = m_str; str != strend; ++str) - { - if (*str == chOld) - { - *str = chNew; - } - } - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(const_str strOld, const_str strNew) -{ - size_type nSourceLen = this->_strlen(strOld); - if (nSourceLen == 0) - { - return *this; - } - size_type nReplacementLen = this->_strlen(strNew); - - size_type nCount = 0; - value_type* strStart = m_str; - value_type* strEnd = m_str + length(); - value_type* strTarget; - while (strStart < strEnd) - { - while ((strTarget = CharTraits::_strstr(strStart, strOld)) != NULL) - { - nCount++; - strStart = strTarget + nSourceLen; - } - strStart += this->_strlen(strStart) + 1; - } - - if (nCount > 0) - { - _MakeUnique(); - - size_type nOldLength = length(); - size_type nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nPrevLength = m_nLength; - const_str pstr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pstr, nPrevLength); - _FreeData(pOldData); - } - strStart = m_str; - strEnd = m_str + length(); - - while (strStart < strEnd) - { - while ((strTarget = CharTraits::_strstr(strStart, strOld)) != NULL) - { - size_type nBalance = nOldLength - ((size_type)(strTarget - m_str) + nSourceLen); - CharTraits::_move(strTarget + nReplacementLen, strTarget + nSourceLen, nBalance); - CharTraits::_copy(strTarget, strNew, nReplacementLen); - strStart = strTarget + nReplacementLen; - strStart[nBalance] = 0; - nOldLength += (nReplacementLen - nSourceLen); - } - strStart += this->_strlen(strStart) + 1; - } - m_nLength = nNewLength; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::move(CryStackStringT& str) -{ - memcpy(this, &str, sizeof(*this)); - if (str.m_str == str.m_strBuf) - { - m_str = m_strBuf; - } -} - -template -inline void CryStackStringT::swap(CryStackStringT& _Str) -{ - CryStackStringT temp; - temp.move(*this); - move(_Str); - _Str.move(temp); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Format(const_str format, ...) -{ - assert(_IsValidString(format)); - - value_type temp[4096]; // Limited to 4096 characters! - va_list argList; - va_start(argList, format); - this->_vsnprintf(temp, 4095, format, argList); - temp[4095] = '\0'; - va_end(argList); - *this = temp; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::FormatFast(const_str format, ...) -{ - assert(_IsValidString(format)); - - va_list argList; - va_start(argList, format); - - int newLength = this->_vsnprintf(m_str, capacity(), format, argList); - if (newLength >= 0) - { - m_nLength = (size_type)newLength; - } - else - { - m_nLength = capacity(); - m_str[capacity()] = '\0'; - } - - va_end(argList); - - return *this; -} - - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::MakeLower() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - *s = this->_ascii_tolower(*s); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::MakeUpper() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - *s = this->_ascii_toupper(*s); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim() -{ - return TrimRight().TrimLeft(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim(value_type ch) -{ - _MakeUnique(); - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset).TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim(const value_type* sCharSet) -{ - _MakeUnique(); - return TrimRight(sCharSet).TrimLeft(sCharSet); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet) || length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (CharTraits::_strchr(sCharSet, *str) != 0)) - { - str--; - } - - if (str != last) - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight() -{ - if (length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (CharTraits::_isspace(*str) != 0)) - { - str--; - } - - if (str != last) // something changed? - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet)) - { - return *this; - } - - const value_type* str = m_str; - while ((*str != 0) && (CharTraits::_strchr(sCharSet, *str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - CharTraits::_move(m_str, m_str + nOff, nNewLength + 1); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft() -{ - const value_type* str = m_str; - while ((*str != 0) && (CharTraits::_isspace(*str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - CharTraits::_move(m_str, m_str + nOff, nNewLength + 1); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -template -inline CryStackStringT CryStackStringT::Right(size_type count) const -{ - if (count == npos) - { - return CryStackStringT(); - } - else if (count > length()) - { - return *this; - } - - return CryStackStringT(m_str + length() - count, count); -} - -template -inline CryStackStringT CryStackStringT::Left(size_type count) const -{ - if (count == npos) - { - return CryStackStringT(); - } - else if (count > length()) - { - count = length(); - } - - return CryStackStringT(m_str, count); -} - -// strspn equivalent -template -inline CryStackStringT CryStackStringT::SpanIncluding(const_str charSet) const -{ - assert(_IsValidString(charSet)); - return Left((size_type)this->_strspn(m_str, charSet)); -} - -// strcspn equivalent -template -inline CryStackStringT CryStackStringT::SpanExcluding(const_str charSet) const -{ - assert(_IsValidString(charSet)); - return Left((size_type)this->_strcspn(m_str, charSet)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT CryStackStringT::Tokenize(const_str charSet, int& nStart) const -{ - if (nStart < 0) - { - return CryStackStringT(); - } - - if (!charSet) - { - return *this; - } - - const_str sPlace = m_str + nStart; - const_str sEnd = m_str + length(); - if (sPlace < sEnd) - { - int nIncluding = (int)this->_strspn(sPlace, charSet); - - if ((sPlace + nIncluding) < sEnd) - { - sPlace += nIncluding; - int nExcluding = (int)this->_strcspn(sPlace, charSet); - int nFrom = nStart + nIncluding; - nStart = nFrom + nExcluding + 1; - - return substr(nFrom, nExcluding); - } - } - // Return empty string. - nStart = -1; - return CryStackStringT(); -} - -#if defined(_RELEASE) -#define ASSERT_LEN (void)(0) -#define ASSERT_WLEN (void)(0) -#else -#define ASSERT_LEN CRY_ASSERT_TRACE(this->length() <= S, ("String '%s' is %u character(s) longer than MAX_SIZE=%u", this->c_str(), this->length() - S, S)) -#define ASSERT_WLEN CRY_ASSERT_TRACE(this->length() <= S, ("Wide-char string '%ls' is %u character(s) longer than MAX_SIZE=%u", this->c_str(), this->length() - S, S)) -#endif - -// a template specialization for char -template -class CryFixedStringT - : public CryStackStringT -{ -public: - typedef CryStackStringT _parentType; - typedef CryFixedStringT _Self; - typedef size_t size_type; - typedef char value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - CryFixedStringT() - : _parentType() {} - CryFixedStringT(const _parentType& str) - : _parentType(str) {ASSERT_LEN; } - CryFixedStringT(const _parentType& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_LEN; } - CryFixedStringT(const _Self& str) - : _parentType(str) {ASSERT_LEN; } - CryFixedStringT(const _Self& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_LEN; } - CryFixedStringT(size_type nRepeat, value_type ch) - : _parentType(nRepeat, ch) {ASSERT_LEN; } - CryFixedStringT(const_str str) - : _parentType (str) {ASSERT_LEN; } - CryFixedStringT(const_str str, size_type nLength) - : _parentType(str, nLength) {ASSERT_LEN; } - CryFixedStringT(const_iterator _First, const_iterator _Last) - : _parentType(_First, _Last) {ASSERT_LEN; } - - template - _Self& operator=(const CryFixedStringT& str) - { - _parentType::operator = (str); - ASSERT_LEN; - return *this; - } - template - _Self& operator=(const CryStackStringT& str) - { - _parentType::operator = (str); - ASSERT_LEN; - return *this; - } - _Self& operator=(value_type ch) - { - _parentType::operator = (ch); - ASSERT_LEN; - return *this; - } - - void GetMemoryUsage(class ICrySizer* pSizer) const{} -}; - -// a template specialization for a fixed list of CryFixedString [Jan M.] -template -class CCryFixedStringListT -{ -public: - CCryFixedStringListT() - { Clear(); } - - void Clear() - { - m_currentAmount = -1; - for (int a = 0; a < NUM_MAX_ELEMENTS; ++a) - { - m_data[a] = ""; - } - } - - void Add(const char* name) - { - m_data[++m_currentAmount] = name; - if (m_currentAmount == NUM_MAX_ELEMENTS) - { - m_currentAmount = -1; - } - } - - const char* operator[](int index) - { - if (index <= m_currentAmount) - { - return m_data[index].c_str(); - } - return NULL; - } - - ILINE int Size() { return m_currentAmount + 1; } - - CryFixedStringT<32>* GetData(int& amount) - { - amount = m_currentAmount + 1; - return m_data; - } -private: - const static int NUM_MAX_ELEMENTS = maxElements; - CryFixedStringT m_data[NUM_MAX_ELEMENTS]; - int32 m_currentAmount; -}; - -// a template specialization for wchar_t -template -class CryFixedWStringT - : public CryStackStringT -{ -public: - typedef CryStackStringT _parentType; - typedef CryFixedWStringT _Self; - typedef size_t size_type; - typedef wchar_t value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - CryFixedWStringT() - : _parentType() {} - CryFixedWStringT(const _parentType& str) - : _parentType(str) {ASSERT_WLEN; } - CryFixedWStringT(const _parentType& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_WLEN; } - CryFixedWStringT(const _Self& str) - : _parentType(str) {ASSERT_WLEN; } - CryFixedWStringT(const _Self& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_WLEN; } - CryFixedWStringT(size_type nRepeat, value_type ch) - : _parentType(nRepeat, ch) {ASSERT_WLEN; } - CryFixedWStringT(const_str str) - : _parentType (str) {ASSERT_WLEN; } - CryFixedWStringT(const_str str, size_type nLength) - : _parentType(str, nLength) {ASSERT_WLEN; } - CryFixedWStringT(const_iterator _First, const_iterator _Last) - : _parentType(_First, _Last) {ASSERT_WLEN; } - - template - _Self& operator=(const CryFixedWStringT& str) - { - _parentType::operator = (str); - ASSERT_WLEN; - return *this; - } - template - _Self& operator=(const CryStackStringT& str) - { - _parentType::operator = (str); - ASSERT_WLEN; - return *this; - } -}; -#undef ASSERT_LEN -#undef ASSERT_WLEN -typedef CryStackStringT stack_string; - -// Special string type used for specifying file paths. -typedef CryStackStringT CryPathString; - - -#if UNITTEST_CRYFIXEDSTRING - -struct SUnitTest_FixedString -{ - bool UnitAssert(const char* message, const char* value, const char* refValue) - { - int res = strcmp(value, refValue); - CRY_ASSERT_MESSAGE(res == 0, message); - return res == 0; - } - - bool UnitAssert(const char* message, const wchar_t* value, const wchar_t* refValue) - { - int res = wcscmp(value, refValue); - CRY_ASSERT_MESSAGE(res == 0, message); - return res == 0; - } - - bool UnitAssert(const char* message, bool cond) - { - CRY_ASSERT_MESSAGE(cond, message); - return cond; - } - - bool UnitAssert(const char* message, size_t a, size_t b) - { - CRY_ASSERT_MESSAGE(a == b, message); - return a == b; - } - - int UnitTest() - { - CryStackStringT str1; - CryStackStringT str2; - CryStackStringT str3; - CryStackStringT str4; - CryStackStringT str5; - CryStackStringT wstr1; - CryStackStringT wstr2; - CryFixedStringT<100> fixedString100; - CryFixedStringT<200> fixedString200; - - typedef CryStackStringT T; - T* pStr = new T; - * pStr = "adads"; - delete pStr; - - str1 = "abcd"; - UnitAssert ("Assignment1-EnoughSpace", str1, "abcd"); - - str2 = "efg"; - UnitAssert ("Assignment2-EnoughSpace", str2, "efg"); - - str2 = str1; - UnitAssert ("Assignment3-EnoughSpace", str2, "abcd"); - - str3 = str1; - UnitAssert ("Assignment4-NotEnoughSpace", str3, "abcd"); - - str1 += "XY"; - UnitAssert ("Concatenate-EnoughSpace", str1, "abcdXY"); - - str2 += "efghijk"; - UnitAssert ("Concatenate-NotEnoughSpace", str2, "abcdefghijk"); - - str1.replace("bc", ""); - UnitAssert ("Replace-Shrink-EnoughSpace", str1, "adXY"); - - str1.replace("XY", "1234"); - UnitAssert ("Replace-Grow-EnoughSpace", str1, "ad1234"); - - str1.replace("1234", "1234567890"); - UnitAssert ("Replace-Grow-NotEnoughSpace", str1, "ad1234567890"); - - str1.reserve(200); - UnitAssert ("Reserve200-SameString", str1, "ad1234567890"); - UnitAssert ("Reserve200-Capacity", str1.capacity() == 200); - - str1.reserve(0); - UnitAssert ("Reserve0-SameString", str1, "ad1234567890"); - UnitAssert ("Reserve0-Capacity==Length", str1.capacity() == str1.length()); - - str1.erase(7); // doesn't change capacity - UnitAssert ("Erase-SameString", str1, "ad12345"); - - str4.assign("abc"); - UnitAssert ("Str4 Assignment", str4, "abc"); - str4.reserve(9); - UnitAssert ("Str4", str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - str4.reserve(0); - UnitAssert ("Str4-Shrink", str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - - size_t idx = str1.find("123"); - UnitAssert ("Str1-Find", idx == 2); - - idx = str1.find("123", 3); - UnitAssert ("Str1-Find", idx == str1.npos); - - wstr1 = L"abc"; - UnitAssert ("WStr1-Assign", wstr1, L"abc"); - UnitAssert ("WStr1-CompareCaseGT", wstr1.compare(L"aBc") > 0); - UnitAssert ("WStr1-CompareCaseLT", wstr1.compare(L"babc") < 0); - UnitAssert ("WStr1-CompareNoCase", wstr1.compareNoCase(L"aBc") == 0); - - str1.Format("This is a %s %S with %d params", "mixed", L"string", 3); - str2.Format("This is a %S %s with %d params", L"mixed", "string", 3); - UnitAssert ("Str1-Format1", str1, "This is a mixed string with 3 params"); - UnitAssert ("Str1-Format2", str1, str2); - - wstr1.Format(L"This is a %s %S with %d params", L"mixed", "string", 3); - wstr2.Format(L"This is a %S %s with %d params", "mixed", L"string", 3); - UnitAssert ("WStr1-Format1", wstr1, L"This is a mixed string with 3 params"); - UnitAssert ("WStr1-Format2", wstr1, wstr2); - - str5.FormatFast("%s", "12345"); - UnitAssert ("Str5-FormatFast", str5, "12345"); - - str5.FormatFast("%s", "012345"); - UnitAssert ("Str5-FormatFast-Truncate", str5, "01234"); - - fixedString100 = str5; - str2 = fixedString200; - fixedString200 = fixedString100; - UnitAssert ("FixedString-Test2", fixedString100, "01234"); - UnitAssert ("FixedString-Test1", fixedString100, fixedString200); - - CryStackStringT testStr; - CryFixedStringT<100> testStr2; - CryFixedWStringT<100> testWStr1; - string normalString; - wstring normalWString; - normalString = string(testStr); - normalString = string(testStr2); - normalString.assign(testStr2.c_str()); - // normalString = testStr; // <- must NOT compile, as we don't allow it! - // normalWString = testWStr1; // <- must NOT compile, as we don't allow it! - normalWString = wstring(testWStr1); - return 0; - } -}; -#endif // #if UNITTEST_CRYFIXEDSTRING - -#endif // CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H diff --git a/Code/Legacy/CryCommon/CryListenerSet.h b/Code/Legacy/CryCommon/CryListenerSet.h index 6addfa384e..6857cf7e5d 100644 --- a/Code/Legacy/CryCommon/CryListenerSet.h +++ b/Code/Legacy/CryCommon/CryListenerSet.h @@ -182,7 +182,7 @@ private: // DO NOT REMOVE - following methods only to be accessed only via CN }; typedef std::vector TListenerVec; - typedef std::vector TAllocatedNameVec; + typedef std::vector TAllocatedNameVec; inline void StartNotificationScope(); inline void EndNotificationScope(); diff --git a/Code/Legacy/CryCommon/CryName.h b/Code/Legacy/CryCommon/CryName.h index 0495ad78f1..8e62a52517 100644 --- a/Code/Legacy/CryCommon/CryName.h +++ b/Code/Legacy/CryCommon/CryName.h @@ -395,13 +395,13 @@ inline bool CCryName::operator>(const CCryName& n) const return m_str > n.m_str; } -inline bool operator==(const string& s, const CCryName& n) +inline bool operator==(const AZStd::string& s, const CCryName& n) { - return n == s; + return s == n; } -inline bool operator!=(const string& s, const CCryName& n) +inline bool operator!=(const AZStd::string& s, const CCryName& n) { - return n != s; + return s != n; } inline bool operator==(const char* s, const CCryName& n) @@ -543,13 +543,13 @@ inline bool CCryNameCRC::operator>(const CCryNameCRC& n) const return m_nID > n.m_nID; } -inline bool operator==(const string& s, const CCryNameCRC& n) +inline bool operator==(const AZStd::string& s, const CCryNameCRC& n) { - return n == s; + return s == n; } -inline bool operator!=(const string& s, const CCryNameCRC& n) +inline bool operator!=(const AZStd::string& s, const CCryNameCRC& n) { - return n != s; + return s != n; } inline bool operator==(const char* s, const CCryNameCRC& n) diff --git a/Code/Legacy/CryCommon/CryPath.h b/Code/Legacy/CryCommon/CryPath.h index 32db308a85..e01e7a2e4b 100644 --- a/Code/Legacy/CryCommon/CryPath.h +++ b/Code/Legacy/CryCommon/CryPath.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include "platform.h" @@ -31,26 +33,28 @@ #define CRY_NATIVE_PATH_SEPSTR DOS_PATH_SEP_STR #endif +typedef AZStd::fixed_string<512> stack_string; + namespace PathUtil { const static int maxAliasLength = 32; - inline string GetLocalizationFolder() + inline AZStd::string GetLocalizationFolder() { return gEnv->pCryPak->GetLocalizationFolder(); } - inline string GetLocalizationRoot() + inline AZStd::string GetLocalizationRoot() { return gEnv->pCryPak->GetLocalizationRoot(); } //! Convert a path to the uniform form. - inline string ToUnixPath(const string& strPath) + inline AZStd::string ToUnixPath(const AZStd::string& strPath) { - if (strPath.find(DOS_PATH_SEP_CHR) != string::npos) + if (strPath.find(DOS_PATH_SEP_CHR) != AZStd::string::npos) { - string path = strPath; - path.replace(DOS_PATH_SEP_CHR, UNIX_PATH_SEP_CHR); + AZStd::string path = strPath; + AZ::StringFunc::Replace(path, DOS_PATH_SEP_CHR, UNIX_PATH_SEP_CHR); return path; } return strPath; @@ -73,19 +77,19 @@ namespace PathUtil } //! Convert a path to the DOS form. - inline string ToDosPath(const string& strPath) + inline AZStd::string ToDosPath(const AZStd::string& strPath) { - if (strPath.find(UNIX_PATH_SEP_CHR) != string::npos) + if (strPath.find(UNIX_PATH_SEP_CHR) != AZStd::string::npos) { - string path = strPath; - path.replace(UNIX_PATH_SEP_CHR, DOS_PATH_SEP_CHR); + AZStd::string path = strPath; + AZ::StringFunc::Replace(path, UNIX_PATH_SEP_CHR, DOS_PATH_SEP_CHR); return path; } return strPath; } //! Convert a path to the Native form. - inline string ToNativePath(const string& strPath) + inline AZStd::string ToNativePath(const AZStd::string& strPath) { #if AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS return ToUnixPath(strPath); @@ -95,10 +99,10 @@ namespace PathUtil } //! Convert a path to lowercase form - inline string ToLower(const string& strPath) + inline AZStd::string ToLower(const AZStd::string& strPath) { - string path = strPath; - path.MakeLower(); + AZStd::string path = strPath; + AZStd::to_lower(path.begin(), path.end()); return path; } @@ -108,9 +112,9 @@ namespace PathUtil //! @param path [OUT] Extracted file path. //! @param filename [OUT] Extracted file (without extension). //! @param ext [OUT] Extracted files extension. - inline void Split(const string& filepath, string& path, string& filename, string& fext) + inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& filename, AZStd::string& fext) { - path = filename = fext = string(); + path = filename = fext = AZStd::string(); if (filepath.empty()) { return; @@ -142,16 +146,16 @@ namespace PathUtil //! @param filepath [IN] Full file name inclusing path. //! @param path [OUT] Extracted file path. //! @param file [OUT] Extracted file (with extension). - inline void Split(const string& filepath, string& path, string& file) + inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& file) { - string fext; + AZStd::string fext; Split(filepath, path, file, fext); file += fext; } // Extract extension from full specified file path // Returns - // pointer to the extension (without .) or pointer to an empty 0-terminated string + // pointer to the extension (without .) or pointer to an empty 0-terminated AZStd::string inline const char* GetExt(const char* filepath) { const char* str = filepath; @@ -174,7 +178,7 @@ namespace PathUtil } //! Extract path from full specified file path. - inline string GetPath(const string& filepath) + inline AZStd::string GetPath(const AZStd::string& filepath) { const char* str = filepath.c_str(); for (const char* p = str + filepath.length() - 1; p >= str; --p) @@ -191,9 +195,9 @@ namespace PathUtil } //! Extract path from full specified file path. - inline string GetPath(const char* filepath) + inline AZStd::string GetPath(const char* filepath) { - return GetPath(string(filepath)); + return GetPath(AZStd::string(filepath)); } //! Extract path from full specified file path. @@ -214,7 +218,7 @@ namespace PathUtil } //! Extract file name with extension from full specified file path. - inline string GetFile(const string& filepath) + inline AZStd::string GetFile(const AZStd::string& filepath) { const char* str = filepath.c_str(); for (const char* p = str + filepath.length() - 1; p >= str; --p) @@ -247,7 +251,7 @@ namespace PathUtil } //! Replace extension for given file. - inline void RemoveExtension(string& filepath) + inline void RemoveExtension(AZStd::string& filepath) { const char* str = filepath.c_str(); for (const char* p = str + filepath.length() - 1; p >= str; --p) @@ -291,15 +295,15 @@ namespace PathUtil } //! Extract file name without extension from full specified file path. - inline string GetFileName(const string& filepath) + inline AZStd::string GetFileName(const AZStd::string& filepath) { - string file = filepath; + AZStd::string file = filepath; RemoveExtension(file); return GetFile(file); } //! Removes the trailing slash or backslash from a given path. - inline string RemoveSlash(const string& path) + inline AZStd::string RemoveSlash(const AZStd::string& path) { if (path.empty() || (path[path.length() - 1] != '/' && path[path.length() - 1] != '\\')) { @@ -309,13 +313,13 @@ namespace PathUtil } //! get slash - inline string GetSlash() + inline AZStd::string GetSlash() { return CRY_NATIVE_PATH_SEPSTR; } //! add a backslash if needed - inline string AddSlash(const string& path) + inline AZStd::string AddSlash(const AZStd::string& path) { if (path.empty() || path[path.length() - 1] == '/') { @@ -343,9 +347,9 @@ namespace PathUtil } //! add a backslash if needed - inline string AddSlash(const char* path) + inline AZStd::string AddSlash(const char* path) { - return AddSlash(string(path)); + return AddSlash(AZStd::string(path)); } inline stack_string ReplaceExtension(const stack_string& filepath, const char* ext) @@ -364,9 +368,9 @@ namespace PathUtil } //! Replace extension for given file. - inline string ReplaceExtension(const string& filepath, const char* ext) + inline AZStd::string ReplaceExtension(const AZStd::string& filepath, const char* ext) { - string str = filepath; + AZStd::string str = filepath; if (ext != 0) { RemoveExtension(str); @@ -380,29 +384,30 @@ namespace PathUtil } //! Replace extension for given file. - inline string ReplaceExtension(const char* filepath, const char* ext) + inline AZStd::string ReplaceExtension(const char* filepath, const char* ext) { - return ReplaceExtension(string(filepath), ext); + return ReplaceExtension(AZStd::string(filepath), ext); } //! Makes a fully specified file path from path and file name. - inline string Make(const string& path, const string& file) + inline AZStd::string Make(const AZStd::string& path, const AZStd::string& file) { return AddSlash(path) + file; } //! Makes a fully specified file path from path and file name. - inline string Make(const string& dir, const string& filename, const string& ext) + inline AZStd::string Make(const AZStd::string& dir, const AZStd::string& filename, const AZStd::string& ext) { - string path = ReplaceExtension(filename, ext); + AZStd::string path = filename; + AZ::StringFunc::Path::ReplaceExtension(path, ext.c_str()); path = AddSlash(dir) + path; return path; } //! Makes a fully specified file path from path and file name. - inline string Make(const string& dir, const string& filename, const char* ext) + inline AZStd::string Make(const AZStd::string& dir, const AZStd::string& filename, const char* ext) { - return Make(dir, filename, string(ext)); + return Make(dir, filename, AZStd::string(ext)); } //! Makes a fully specified file path from path and file name. @@ -414,42 +419,43 @@ namespace PathUtil //! Makes a fully specified file path from path and file name. inline stack_string Make(const stack_string& dir, const stack_string& filename, const stack_string& ext) { - stack_string path = ReplaceExtension(filename, ext); - path = AddSlash(dir) + path; - return path; + AZStd::string path = filename; + AZ::StringFunc::Path::ReplaceExtension(path, ext.c_str()); + path = AddSlash(dir.c_str()) + path; + return stack_string(path.c_str()); } //! Makes a fully specified file path from path and file name. - inline string Make(const char* path, const string& file) + inline AZStd::string Make(const char* path, const AZStd::string& file) { - return Make(string(path), file); + return Make(AZStd::string(path), file); } //! Makes a fully specified file path from path and file name. - inline string Make(const string& path, const char* file) + inline AZStd::string Make(const AZStd::string& path, const char* file) { - return Make(path, string(file)); + return Make(path, AZStd::string(file)); } //! Makes a fully specified file path from path and file name. - inline string Make(const char path[], const char file[]) + inline AZStd::string Make(const char path[], const char file[]) { - return Make(string(path), string(file)); + return Make(AZStd::string(path), AZStd::string(file)); } //! Makes a fully specified file path from path and file name. - inline string Make(const char* path, const char* file, const char* ext) + inline AZStd::string Make(const char* path, const char* file, const char* ext) { - return Make(string(path), string(file), string(ext)); + return Make(AZStd::string(path), AZStd::string(file), AZStd::string(ext)); } //! Makes a fully specified file path from path and file name. - inline string MakeFullPath(const string& relativePath) + inline AZStd::string MakeFullPath(const AZStd::string& relativePath) { return relativePath; } - inline string GetParentDirectory (const string& strFilePath, int nGeneration = 1) + inline AZStd::string GetParentDirectory (const AZStd::string& strFilePath, int nGeneration = 1) { for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent p >= strFilePath.c_str(); @@ -458,23 +464,23 @@ namespace PathUtil switch (*p) { case ':': - return string (strFilePath.c_str(), p); + return AZStd::string(strFilePath.c_str(), p); case '/': case '\\': // we've reached a path separator - return everything before it. if (!--nGeneration) { - return string(strFilePath.c_str(), p); + return AZStd::string(strFilePath.c_str(), p); } break; } } // it seems the file name is a pure name, without path or extension - return string(); + return AZStd::string(); } template - inline CryStackStringT GetParentDirectoryStackString(const CryStackStringT& strFilePath, int nGeneration = 1) + inline AZStd::basic_fixed_string GetParentDirectoryStackString(const AZStd::basic_fixed_string& strFilePath, int nGeneration = 1) { for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent p >= strFilePath.c_str(); @@ -483,19 +489,19 @@ namespace PathUtil switch (*p) { case ':': - return CryStackStringT (strFilePath.c_str(), p); + return AZStd::basic_fixed_string (strFilePath.c_str(), p); case '/': case '\\': // we've reached a path separator - return everything before it. if (!--nGeneration) { - return CryStackStringT(strFilePath.c_str(), p); + return AZStd::basic_fixed_string(strFilePath.c_str(), p); } break; } } // it seems the file name is a pure name, without path or extension - return CryStackStringT(); + return AZStd::basic_fixed_string(); } ////////////////////////////////////////////////////////////////////////// @@ -503,7 +509,8 @@ namespace PathUtil // Make a game correct path out of any input path. inline stack_string MakeGamePath(const stack_string& path) { - stack_string relativePath(ToUnixPath(path)); + stack_string relativePath = path; + ToUnixPath(relativePath); if ((!gEnv) || (!gEnv->pFileIO)) { @@ -512,7 +519,7 @@ namespace PathUtil unsigned int index = 0; if (relativePath.length() && relativePath[index] == '@') // already aliased { - if (relativePath.compareNoCase(0, 9, "@assets@/") == 0) + if (AZ::StringFunc::Equal(relativePath.c_str(), "@assets@/", false, 9)) { return relativePath.substr(9); // assets is assumed. } @@ -526,7 +533,7 @@ namespace PathUtil if ( (rootPath.size() > 0) && (rootPath.size() < relativePath.size()) && - (relativePath.compareNoCase(0, rootPath.size(), rootPath) == 0) + (AZ::StringFunc::Equal(relativePath.c_str(), rootPath.c_str(), false, rootPath.size())) ) { stack_string chopped_string = relativePath.substr(rootPath.size()); @@ -543,13 +550,13 @@ namespace PathUtil ////////////////////////////////////////////////////////////////////////// // Description: // Make a game correct path out of any input path. - inline string MakeGamePath(const string& path) + inline AZStd::string MakeGamePath(const AZStd::string& path) { stack_string stackPath(path.c_str()); return MakeGamePath(stackPath).c_str(); } - // returns true if the string matches the wildcard + // returns true if the AZStd::string matches the wildcard inline bool MatchWildcard (const char* szString, const char* szWildcard) { const char* pString = szString, * pWildcard = szWildcard; @@ -595,7 +602,7 @@ namespace PathUtil if (!*pWildcard) { - return true; // the rest of the string doesn't matter: the wildcard ends with * + return true; // the rest of the AZStd::string doesn't matter: the wildcard ends with * } for (; *pString; ++pString) { diff --git a/Code/Legacy/CryCommon/CrySizer.h b/Code/Legacy/CryCommon/CrySizer.h index 9301360bd5..add2cdd397 100644 --- a/Code/Legacy/CryCommon/CrySizer.h +++ b/Code/Legacy/CryCommon/CrySizer.h @@ -208,9 +208,7 @@ public: this->AddObject(rPair.first); this->AddObject(rPair.second); } - void AddObject(const string& rString) {this->AddObject(rString.c_str(), rString.capacity()); } - void AddObject(const CryStringT& rString) {this->AddObject(rString.c_str(), rString.capacity()); } - void AddObject(const CryFixedStringT<32>&){} + void AddObject(const AZStd::string& rString) {this->AddObject(rString.c_str(), rString.capacity()); } void AddObject(const wchar_t&) {} void AddObject(const char&) {} void AddObject(const unsigned char&) {} @@ -427,7 +425,7 @@ public: #endif #ifndef NOT_USE_CRY_STRING - bool Add (const string& strText) + bool Add (const AZStd::string& strText) { AddString(strText); return true; diff --git a/Code/Legacy/CryCommon/CryString.h b/Code/Legacy/CryCommon/CryString.h deleted file mode 100644 index 72469e3dca..0000000000 --- a/Code/Legacy/CryCommon/CryString.h +++ /dev/null @@ -1,2523 +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 : Custom reference counted string class. -// Can easily be substituted instead of string - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYSTRING_H -#define CRYINCLUDE_CRYCOMMON_CRYSTRING_H -#pragma once - -#include -#include - -#if !defined(NOT_USE_CRY_STRING) - -#include -#include -#include -#include -#include -#include "LegacyAllocator.h" - -#define CRY_STRING - -// forward declaration of CryStackString -template -class CryStackStringT; - - -class CConstCharWrapper; //forward declaration for special const char * without memory allocations - -//extern void CryDebugStr( const char *format,... ); -//#define CRY_STRING_DEBUG(s) { if (*s) CryDebugStr( "[%6d] %s",_usedMemory(0),(s) );} -#define CRY_STRING_DEBUG(s) - -class CryStringAllocator - : public AZ::SimpleSchemaAllocator -{ -public: - AZ_TYPE_INFO(CryStringAllocator, "{763DFC83-8A6E-4FD9-B6BC-BBF56E93E4EE}"); - - using Base = AZ::SimpleSchemaAllocator; - using Descriptor = Base::Descriptor; - - CryStringAllocator() - : Base("CryStringAllocator", "Allocator for CryString") - { - Descriptor desc; - desc.m_systemChunkSize = 4 * 1024 * 1024; // grow by 4 MB at a time - desc.m_subAllocator = &AZ::AllocatorInstance::Get(); - Create(desc); - } -}; - -////////////////////////////////////////////////////////////////////////// -// CryStringT class. -////////////////////////////////////////////////////////////////////////// -template -class CryStringT -{ -public: - ////////////////////////////////////////////////////////////////////////// - // Types compatible with STL string. - ////////////////////////////////////////////////////////////////////////// - typedef CryStringT _Self; - typedef size_t size_type; - typedef T value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - enum _npos_type - { - npos = (size_type) ~0 - }; - - ////////////////////////////////////////////////////////////////////////// - // Constructors - ////////////////////////////////////////////////////////////////////////// - CryStringT(); - -protected: - CryStringT(const CConstCharWrapper& str); //ctor for strings without memory allocations - friend class CConstCharWrapper; -public: - - CryStringT(const _Self& str); - CryStringT(const _Self& str, size_type nOff, size_type nCount); - - // Before September 2012 this constructor looked like this: - // explicit CryStringT( value_type ch, size_type nRepeat = 1 ); - // It was very error-prone, because the matching constructor - // std::string constructor is different: - // std::string( size_type nRepeat, value_type ch ); - // - // To prevent hard-to-catch bugs, we removed all calls of this - // constructor in the existing CryEngine code (in September 2012) - // and started using proper order of parameters (matching std::). - // - // To catch calls using the reversed arguments in other projects, - // we retain the previous function with reversed arguments, - // and declare it private. - CryStringT(size_type nRepeat, value_type ch); -private: - CryStringT(value_type ch, size_type nRepeat); - -public: - - CryStringT(const_str str); - CryStringT(const_str str, size_type nLength); - CryStringT(const_iterator _First, const_iterator _Last); - ~CryStringT(); - - ////////////////////////////////////////////////////////////////////////// - // STL string like interface. - ////////////////////////////////////////////////////////////////////////// - //! Operators. - size_type length() const; - size_type size() const; - bool empty() const; - void clear(); // free up the data - - //! Returns the storage currently allocated to hold the string, a value at least as large as length(). - size_type capacity() const; - - // Sets the capacity of the string to a number at least as great as a specified number. - // nCount = 0 is shrinking string to fit number of characters in it. - void reserve(size_type nCount = 0); - - _Self& append(const value_type* _Ptr); - _Self& append(const value_type* _Ptr, size_type nCount); - _Self& append(const _Self& _Str, size_type nOff, size_type nCount); - _Self& append(const _Self& _Str); - _Self& append(size_type nCount, value_type _Ch); - _Self& append(const_iterator _First, const_iterator _Last); - - _Self& assign(const_str _Ptr); - _Self& assign(const_str _Ptr, size_type nCount); - _Self& assign(const _Self& _Str, size_type off, size_type nCount); - _Self& assign(const _Self& _Str); - _Self& assign(size_type nCount, value_type _Ch); - _Self& assign(const_iterator _First, const_iterator _Last); - - value_type at(size_type index) const; - - const_iterator begin() const { return m_str; }; - const_iterator end() const { return m_str + length(); }; - - iterator begin() { return m_str; }; - iterator end() { return m_str + length(); }; - - // Following functions are commented out because they provide direct write access to - // the string and such access doesn't work properly with our current reference-count - // implementation. - // If you really need write access to your string's elements, please consider - // using CryStackStringT<> instead of CryString<>. Alternatively, you can modify - // your string by multiple calls of erase() and append(). - // Note: If you need *linear memory read* access to your string's elements, use data() - // or c_str(). If you need *linear memory write* access to your string's elements, - // use a non-string class (std::vector<>, DynArray<>, etc.) instead of CryString<>. - //value_type& at( size_type index ); - //iterator begin() { return m_str; }; - //iterator end() { return m_str+length(); }; - - //! cast to C string operator. - operator const_str() const { - return m_str; - } - - //! cast to C string. - const value_type* c_str() const { return m_str; } - const value_type* data() const { return m_str; }; - - ////////////////////////////////////////////////////////////////////////// - // string comparison. - ////////////////////////////////////////////////////////////////////////// - int compare(const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compare(const char* _Ptr) const; - int compare(const wchar_t* _Ptr) const; - int compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Case insensitive comparison - int compareNoCase(const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compareNoCase(const value_type* _Ptr) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Copies at most a specified number of characters from an indexed position in a source string to a target character array. - size_type copy(value_type* _Ptr, size_type nCount, size_type nOff = 0) const; - - void push_back(value_type _Ch) { _ConcatenateInPlace(&_Ch, 1); } - void resize(size_type nCount, value_type _Ch = ' '); - - //! simple sub-string extraction - _Self substr(size_type pos, size_type count = npos) const; - - // replace part of string. - _Self& replace(value_type chOld, value_type chNew); - _Self& replace(const_str strOld, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew, size_type count2); - _Self& replace(size_type pos, size_type count, size_type nNumChars, value_type chNew); - - // insert new elements to string. - _Self& insert(size_type nIndex, value_type ch); - _Self& insert(size_type nIndex, size_type nCount, value_type ch); - _Self& insert(size_type nIndex, const_str pstr); - _Self& insert(size_type nIndex, const_str pstr, size_type nCount); - - //! delete count characters starting at zero-based index - _Self& erase(size_type nIndex, size_type count = npos); - - //! searching (return starting index, or -1 if not found) - //! look for a single character match - //! like "C" strchr - size_type find(value_type ch, size_type pos = 0) const; - //! look for a specific sub-string - //! like "C" strstr - size_type find(const_str subs, size_type pos = 0) const; - size_type rfind(value_type ch, size_type pos = npos) const; - size_type rfind(const _Self& subs, size_type pos = 0) const; - - size_type find_first_of(value_type _Ch, size_type nOff = 0) const; - size_type find_first_of(const_str charSet, size_type nOff = 0) const; - //size_type find_first_of( const value_type* _Ptr,size_type _Off,size_type _Count ) const; - size_type find_first_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_first_not_of(value_type _Ch, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_first_not_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_last_of(value_type _Ch, size_type _Off = npos) const; - size_type find_last_of(const value_type* _Ptr, size_type _Off = npos) const; - size_type find_last_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_last_of(const _Self& _Str, size_type _Off = npos) const; - - size_type find_last_not_of(value_type _Ch, size_type _Off = npos) const; - size_type find_last_not_of(const value_type* _Ptr, size_type _Off = npos) const; - size_type find_last_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_last_not_of(const _Self& _Str, size_type _Off = npos) const; - - - void swap(_Self& _Str); - - ////////////////////////////////////////////////////////////////////////// - // overloaded operators. - ////////////////////////////////////////////////////////////////////////// - // overloaded indexing. - //value_type operator[]( size_type index ) const; // same as at() - // value_type& operator[]( size_type index ); // same as at() - - // overloaded assignment - _Self& operator=(const _Self& str); - _Self& operator=(value_type ch); - _Self& operator=(const_str str); - - template - CryStringT(const CryStackStringT& str); - -protected: - // we prohibit an implicit conversion from CryStackString to make user aware of allocation! - // -> use string(stackedString) instead - // as the private statement seems to be ignored (VS C++), we add a compile time error, see below - template - _Self& operator=(const CryStackStringT& str) - { - // we add a compile-time error as the Visual C++ compiler seems to ignore the private statement? -#if defined(__clang__) - //CLANG_TODO: clang verifies things differently -#else - static_assert(false, "Use explicit string assignment when assigning from_StackString"); -#endif - // not reached, as above will generate a compile time error - _Assign(str.c_str(), str.length()); - return *this; - } - -public: - // string concatenation - _Self& operator+=(const _Self& str); - _Self& operator+=(value_type ch); - _Self& operator+=(const_str str); - - //template friend CryStringT operator+( const CryStringT& str1, const CryStringT& str2 ); - //template friend CryStringT operator+( const CryStringT& str, value_type ch ); - //template friend CryStringT operator+( value_type ch, const CryStringT& str ); - //template friend CryStringT operator+( const CryStringT& str1, const_str str2 ); - //template friend CryStringT operator+( const_str str1, const CryStringT& str2 ); - - size_t GetAllocatedMemory() const - { - StrHeader* header = _header(); - if (header == _emptyHeader()) - { - return 0; - } - return sizeof(StrHeader) + (header->nAllocSize + 1) * sizeof(value_type); - } - - ////////////////////////////////////////////////////////////////////////// - // Extended functions. - // This functions are not in the STL string. - // They have an ATL CString interface. - ////////////////////////////////////////////////////////////////////////// - //! Format string, use (sprintf) - _Self& Format(const value_type* format, ...); - - //! Converts the string to lower-case - // This function uses the "C" locale for case-conversion (ie, A-Z only) - _Self& MakeLower(); - - //! Converts the string to upper-case - // This function uses the "C" locale for case-conversion (ie, A-Z only) - _Self& MakeUpper(); - - _Self& Trim(); - _Self& Trim(value_type ch); - _Self& Trim(const value_type* sCharSet); - - _Self& TrimLeft(); - _Self& TrimLeft(value_type ch); - _Self& TrimLeft(const value_type* sCharSet); - - _Self& TrimRight(); - _Self& TrimRight(value_type ch); - _Self& TrimRight(const value_type* sCharSet); - - _Self SpanIncluding(const_str charSet) const; - _Self SpanExcluding(const_str charSet) const; - _Self Tokenize(const_str charSet, int& nStart) const; - _Self Mid(size_type nFirst, size_type nCount = npos) const { return substr(nFirst, nCount); }; - - _Self Left(size_type count) const; - _Self Right(size_type count) const; - ////////////////////////////////////////////////////////////////////////// - - // public utilities. - static size_type _strlen(const_str str); - static size_type _strnlen(const_str str, size_type maxLen); - static const_str _strchr(const_str str, value_type c); - static const_str _strrchr(const_str str, value_type c); - static value_type* _strstr(value_type* str, const_str strSearch); - static bool _IsValidString(const_str str); - -#if defined(WIN32) || defined(WIN64) - static int _vscpf(const_str format, va_list args); -#endif - static int _vsnpf(value_type* buf, int cnt, const_str format, va_list args); - - -public: - ////////////////////////////////////////////////////////////////////////// - // Only used for debugging statistics. - ////////////////////////////////////////////////////////////////////////// - static size_t _usedMemory(ptrdiff_t size) - { - static size_t s_used_memory = 0; - s_used_memory += size; - return s_used_memory; - } - -protected: - value_type* m_str; // pointer to ref counted string data - - // String header. Immediately after this header in memory starts actual string data. - struct StrHeader - { - int nRefCount; - int nLength; - int nAllocSize; // Size of memory allocated at the end of this class. - - value_type* GetChars() { return (value_type*)(this + 1); } - void AddRef() { nRefCount++; /*InterlockedIncrement(&_header()->nRefCount);*/}; - int Release() { return --nRefCount; }; - }; - static StrHeader* _emptyHeader() - { - // Define 2 static buffers in a row. The 2nd is a dummy object to hold a single empty char string. - static StrHeader sEmptyStringBuffer[2] = { - {-1, 0, 0}, {0, 0, 0} - }; - return &sEmptyStringBuffer[0]; - } - - // implementation helpers - StrHeader* _header() const; - - void _AllocData(size_type nLen); - static void _FreeData(StrHeader* pData); - void _Free(); - void _Initialize(); - - void _Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2); - void _ConcatenateInPlace(const_str sStr, size_type nLen); - void _Assign(const_str sStr, size_type nLen); - void _MakeUnique(); - - static void _copy(value_type* dest, const value_type* src, size_type count); - static void _move(value_type* dest, const value_type* src, size_type count); - static void _set(value_type* dest, value_type ch, size_type count); -}; - -// Variant of CryStringT which does not share memory with other strings. -template -class CryStringLocalT - : public CryStringT -{ -public: - typedef CryStringT BaseType; - typedef typename BaseType::const_str const_str; - typedef typename BaseType::value_type value_type; - typedef typename BaseType::size_type size_type; - typedef typename BaseType::iterator iterator; - - CryStringLocalT() - {} - CryStringLocalT(const CryStringLocalT& str) - : BaseType(str.c_str()) - {} - CryStringLocalT(const BaseType& str) - : BaseType(str.c_str()) - {} - template - CryStringLocalT(const CryStackStringT& str) - : BaseType(str.c_str()) - {} - CryStringLocalT(const_str str) - : BaseType(str) - {} - CryStringLocalT(const_str str, size_t len) - : BaseType(str, len) - {} - CryStringLocalT(const_str begin, const_str end) - : BaseType(begin, end) - {} - CryStringLocalT(size_type nRepeat, value_type ch) - : BaseType(nRepeat, ch) - {} - - CryStringLocalT(const typename CryStringT::_Self& str, size_type nOff, size_type nCount) - : BaseType(str, nOff, nCount) - {} - - CryStringLocalT& operator=(const BaseType& str) - { - BaseType::operator=(str.c_str()); - return *this; - } - CryStringLocalT& operator=(const CryStringLocalT& str) - { - BaseType::operator=(str.c_str()); - return *this; - } - CryStringLocalT& operator=(const_str str) - { - BaseType::operator=(str); - return *this; - } - iterator begin() { return BaseType::m_str; } - using BaseType::begin; // const version - iterator end() { return BaseType::m_str + BaseType::length(); } - using BaseType::end; // const version -}; - -typedef CryStringLocalT CryStringLocal; - - -// wrapper class for creation of strings without memory allocation -// it creates a string with pointer pointing to const char* location -// destructor sets the string to empty -// NOTE: never copy a string from it, just use it as function parameters instead of const char* itself -class CConstCharWrapper -{ -public: - //passing *this is safe since the char pointer is already set and therefore is the this-ptr constructed complete enough -#pragma warning (push) -#pragma warning (disable : 4355) - CConstCharWrapper(const char* const cpString) - : cpChar(cpString) - , str(*this){AZ_Assert(cpString, "c-string parameter cannot be nullptr"); } //create stack string -#pragma warning (pop) - ~CConstCharWrapper(){str.m_str = CryStringT::_emptyHeader()->GetChars(); }//reset string - operator const CryStringT&() const { - return str; - } //cast operator to const string reference -private: - const char* const cpChar; - CryStringT str; - - char* GetCharPointer() const {return const_cast(cpChar); } //access function for string ctor - - friend class CryStringT; //both are bidirectional friends to avoid any other accesses -}; - - -//macro needed because compiler somehow cannot find the cast operator when not invoked directly -#define CONST_TEMP_STRING(a) ((const string&)CConstCharWrapper(a)) - -///////////////////////////////////////////////////////////////////////////// -// CryStringT Implementation -////////////////////////////////////////////////////////////////////////// - -template -inline typename CryStringT::StrHeader * CryStringT::_header() const -{ - AZ_Assert(m_str != nullptr, "string header is nullptr"); - return ((StrHeader*)m_str) - 1; -} - -template -inline typename CryStringT::size_type CryStringT::_strlen(const_str str) -{ - return (str == NULL) ? 0 : (size_type)::strlen(str); -} - -template <> -inline CryStringT::size_type CryStringT::_strlen(const_str str) -{ - return (str == NULL) ? 0 : (size_type)::wcslen(str); -} - -template -inline typename CryStringT::size_type CryStringT::_strnlen(const_str str, size_type maxLen) -{ - size_type len = 0; - if (str) - { - while (len < maxLen && *str != '\0') - { - len++; - str++; - } - } - return len; -} - -template -inline typename CryStringT::const_str CryStringT::_strchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::strchr(str, c); -} - -template <> -inline CryStringT::const_str CryStringT::_strchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::wcschr(str, c); -} - -template -inline typename CryStringT::const_str CryStringT::_strrchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::strrchr(str, c); -} - -template <> -inline CryStringT::const_str CryStringT::_strrchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::wcsrchr(str, c); -} - -template -inline typename CryStringT::value_type * CryStringT::_strstr(value_type * str, const_str strSearch) -{ - return (str == NULL) ? 0 : (value_type*)::strstr(str, strSearch); -} - -template <> -inline CryStringT::value_type * CryStringT::_strstr(value_type * str, const_str strSearch) -{ - return (str == NULL) ? 0 : ::wcsstr(str, strSearch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_copy(value_type* dest, const value_type* src, size_type count) -{ - if (dest != src) - { - memcpy(dest, src, count * sizeof(value_type)); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_move(value_type* dest, const value_type* src, size_type count) -{ - memmove(dest, src, count * sizeof(value_type)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_set(value_type* dest, value_type ch, size_type count) -{ - static_assert(sizeof(value_type) == sizeof(T)); - static_assert(sizeof(value_type) == 1); - memset(dest, ch, count); -} - -////////////////////////////////////////////////////////////////////////// -template <> -inline void CryStringT::_set(value_type* dest, value_type ch, size_type count) -{ - static_assert(sizeof(value_type) == sizeof(wchar_t)); - wmemset(dest, ch, count); -} - -#if defined(WIN32) || defined(WIN64) - -template<> -inline int CryStringT::_vscpf(const_str format, va_list args) -{ - return _vscprintf(format, args); -} - -template<> -inline int CryStringT::_vscpf(const_str format, va_list args) -{ - return _vscwprintf(format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return azvsnprintf(buf, cnt, format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return azvsnwprintf(buf, cnt, format, args); -} - -#else - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return vsnprintf(buf, cnt, format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return vswprintf(buf, cnt, format, args); -} - -#endif - -////////////////////////////////////////////////////////////////////////// -template -inline bool CryStringT::_IsValidString(const_str) -{ - /* - if (str == NULL) - return false; - int nLength = _strlen(str); - return !::IsBadStringPtrA(str, nLength); - */ - return true; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Assign(const_str sStr, size_type nLen) -{ - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (_header()->nRefCount > 1 || nLen > capacity()) - { - _Free(); - _AllocData(nLen); - } - // Copy characters from new string to this buffer. - _copy(m_str, sStr, nLen); - // Set new length. - _header()->nLength = aznumeric_cast(nLen); - // Make null terminated string. - m_str[nLen] = 0; - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2) -{ - size_type nLen = nLen1 + nLen2; - - if (nLen1 * 2 > nLen) - { - nLen = nLen1 * 2; - } - - if (nLen != 0) - { - if (nLen < 8) - { - nLen = 8; - } - - _AllocData(nLen); - _copy(m_str, sStr1, nLen1); - _copy(m_str + nLen1, sStr2, nLen2); - _header()->nLength = aznumeric_cast(nLen1 + nLen2); - m_str[nLen1 + nLen2] = 0; - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_ConcatenateInPlace(const_str sStr, size_type nLen) -{ - if (nLen != 0) - { - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (_header()->nRefCount > 1 || length() + nLen > capacity()) - { - StrHeader* pOldData = _header(); - _Concatenate(m_str, length(), sStr, nLen); - _FreeData(pOldData); - } - else - { - _copy(m_str + length(), sStr, nLen); - _header()->nLength = aznumeric_cast(_header()->nLength + nLen); - m_str[_header()->nLength] = 0; // Make null terminated string. - } - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_MakeUnique() -{ - if (_header()->nRefCount > 1) - { - // If string is shared, make a copy of string buffer. - StrHeader* pOldData = _header(); - // This will not free header because reference count is greater then 1. - _Free(); - // Allocate a new string buffer. - _AllocData(pOldData->nLength); - // Full copy of null terminated string. - _copy(m_str, pOldData->GetChars(), pOldData->nLength + 1); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Initialize() -{ - m_str = _emptyHeader()->GetChars(); -} - -// always allocate one extra character for '\0' termination -// assumes [optimistically] that data length will equal allocation length -template -inline void CryStringT::_AllocData(size_type nLen) -{ - AZ_Assert(nLen <= (std::numeric_limits::max)() - 1, "New string allocation size %zu is greater than the max allowed size of %d", - nLen, (std::numeric_limits::max)() - 1); // max size (enough room for 1 extra) - - if (nLen == 0) - { - _Initialize(); - } - else - { - size_type allocLen = sizeof(StrHeader) + (nLen + 1) * sizeof(value_type); - - StrHeader* pData = (StrHeader*)azmalloc(allocLen, 32, CryStringAllocator); - - _usedMemory(allocLen); // For statistics. - pData->nRefCount = 1; - m_str = pData->GetChars(); - pData->nLength = aznumeric_cast(nLen); - pData->nAllocSize = aznumeric_cast(nLen); - m_str[nLen] = 0; // null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Free() -{ - if (_header()->nRefCount >= 0) // Not empty string. - { - _FreeData(_header()); - _Initialize(); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_FreeData(StrHeader* pData) -{ - //Cry uses -1 to represent strings on the stack. - if (pData->nRefCount < 0) - { - return; - } - - if (pData->nRefCount == 0 || pData->Release() <= 0) - { - azfree((void*)pData, CryStringAllocator); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT() -{ - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const CryStringT& str) -{ - AZ_Assert(str._header()->nRefCount != 0, "Reference count input cry string should be greater than 0"); - if (str._header()->nRefCount >= 0) - { - m_str = str.m_str; - _header()->AddRef(); - } - else - { - _Initialize(); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const CryStringT& str, size_type nOff, size_type nCount) -{ - _Initialize(); - assign(str, nOff, nCount); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_str str) -{ - _Initialize(); - // Make a copy of C string. - size_type nLen = _strlen(str); - if (nLen != 0) - { - _AllocData(nLen); - _copy(m_str, str, nLen); - CRY_STRING_DEBUG(m_str) - } -} - -template -inline CryStringT::CryStringT(const CConstCharWrapper& str) -{ - _Initialize(); - m_str = const_cast(str.GetCharPointer()); -} - -template -template -inline CryStringT::CryStringT(const CryStackStringT& str) -{ - _Initialize(); - const size_type nLength = str.length(); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_str str, size_type nLength) -{ - _Initialize(); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(size_type nRepeat, value_type ch) -{ - _Initialize(); - if (nRepeat > 0) - { - _AllocData(nRepeat); - _set(m_str, ch, nRepeat); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_iterator _First, const_iterator _Last) -{ - _Initialize(); - size_type nLength = (size_type)(_Last - _First); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, _First, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::~CryStringT() -{ - _FreeData(_header()); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::length() const -{ - return _header()->nLength; -} -template -inline typename CryStringT::size_type CryStringT::size() const -{ - return _header()->nLength; -} -template -inline typename CryStringT::size_type CryStringT::capacity() const -{ - return _header()->nAllocSize; -} - -template -inline bool CryStringT::empty() const -{ - return length() == 0; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::clear() -{ - if (length() == 0) - { - return; - } - if (_header()->nRefCount >= 0) - { - _Free(); - } - else - { - resize(0); - } - AZ_Assert(length() == 0, "Cleared string should have a length of 0"); - AZ_Assert(_header()->nRefCount < 0 || capacity() == 0, - "Cleared string should have a reference count or capacity of 0"); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::reserve(size_type nCount) -{ - // Reserve of 0 is shrinking container to fit number of characters in it.. - if (nCount > capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(nCount); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _header()->nLength = pOldData->nLength; - m_str[pOldData->nLength] = 0; - _FreeData(pOldData); - } - else if (nCount == 0) - { - if (length() != capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(length()); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _FreeData(pOldData); - } - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_str _Ptr) -{ - *this += _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_str _Ptr, size_type nCount) -{ - _ConcatenateInPlace(_Ptr, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const CryStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _ConcatenateInPlace(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const CryStringT& _Str) -{ - *this += _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(size_type nCount, value_type _Ch) -{ - if (nCount > 0) - { - if (_header()->nRefCount > 1 || length() + nCount > capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(length() + nCount); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _set(m_str + pOldData->nLength, _Ch, nCount); - _FreeData(pOldData); - } - else - { - size_type nOldLength = length(); - _set(m_str + nOldLength, _Ch, nCount); - _header()->nLength = aznumeric_cast(nOldLength + nCount); - m_str[length()] = 0; // Make null terminated string. - } - } - CRY_STRING_DEBUG(m_str) - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_iterator _First, const_iterator _Last) -{ - append(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_str _Ptr) -{ - *this = _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_str _Ptr, size_type nCount) -{ - size_type len = _strnlen(_Ptr, nCount); - _Assign(_Ptr, len); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const CryStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _Assign(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const CryStringT& _Str) -{ - *this = _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(size_type nCount, value_type _Ch) -{ - if (nCount >= 1) - { - _AllocData(nCount); - _set(m_str, _Ch, nCount); - CRY_STRING_DEBUG(m_str) - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_iterator _First, const_iterator _Last) -{ - assign(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::value_type CryStringT::at(size_type index) const -{ - AZ_Assert(index >= 0 && index < length(), "index into CryString is out of range"); - return m_str[index]; -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStringT::compare(const CryStringT& _Str) const -{ - return compare(_Str.m_str); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const CryStringT& _Str) const -{ - return compare(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const CryStringT& _Str, size_type nOff, size_type nCount) const -{ - AZ_Assert(nOff < _Str.length(), "Offset into input string is larger than the index range"); - return compare(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStringT::compare(const char* _Ptr) const -{ - return strcmp(m_str, _Ptr); -} - -template -inline int CryStringT::compare(const wchar_t* _Ptr) const -{ - return wcscmp(m_str, _Ptr); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - AZ_Assert(_Pos1 < length(), "position index to compare is larger than the length of this string"); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : strncmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStringT::compareNoCase(const CryStringT& _Str) const -{ - return _stricmp(m_str, _Str.m_str); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStringT& _Str) const -{ - return compareNoCase(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStringT& _Str, size_type nOff, size_type nCount) const -{ - AZ_Assert(nOff < _Str.length(), "offset to start comparison within input string is larger than the string index range"); - return compareNoCase(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStringT::compareNoCase(const value_type* _Ptr) const -{ - return _stricmp(m_str, _Ptr); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - AZ_Assert(_Pos1 < length(), "Position to start case-insensitive search is larger the indexable range"); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : _strnicmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::copy(value_type* _Ptr, size_type nCount, size_type nOff) const -{ - AZ_Assert(nOff < length(), "Offset to copy from string to output address is outside the indexable range"); - if (nCount < 0) - { - nCount = 0; - } - if (nOff + nCount > length()) // trim to offset. - { - nCount = length() - nOff; - } - - _copy(_Ptr, m_str + nOff, nCount); - return nCount; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::resize(size_type nCount, value_type _Ch) -{ - _MakeUnique(); - if (nCount > length()) - { - size_type numToAdd = nCount - length(); - append(numToAdd, _Ch); - } - else if (nCount < length()) - { - _header()->nLength = nCount; - m_str[length()] = 0; // Make null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -//! compare helpers -template -inline bool operator==(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) == 0; } -template -inline bool operator!=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) != 0; } -template -inline bool operator<(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) > 0; } -template -inline bool operator>(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) < 0; } -template -inline bool operator<=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) >= 0; } -template -inline bool operator>=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) <= 0; } - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::operator=(value_type ch) -{ - _Assign(&ch, 1); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& string1, typename CryStringT::value_type ch) -{ - CryStringT s(string1); - s.append(1, ch); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(typename CryStringT::value_type ch, const CryStringT& str) -{ - CryStringT s; - s.reserve(str.size() + 1); - s.append(1, ch); - s.append(str); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& string1, const CryStringT& string2) -{ - CryStringT s(string1); - s.append(string2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& str1, const typename CryStringT::value_type* str2) -{ - CryStringT s(str1); - s.append(str2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const typename CryStringT::value_type* str1, const CryStringT& str2) -{ - AZ_Assert(str1 == nullptr || CryStringT::_IsValidString(str1), "Input string is not valid"); - CryStringT s; - s.reserve(CryStringT::_strlen(str1) + str2.size()); - s.append(str1); - s.append(str2); - return s; -} - -template -inline CryStringT& CryStringT::operator=(const CryStringT& str) -{ - if (m_str != str.m_str) - { - if (_header()->nRefCount < 0) - { - // Empty string. - // _Assign( str.m_str,str.length() ); - if (str._header()->nRefCount < 0) - { - ; // two empty strings... - } - else - { - m_str = str.m_str; - _header()->AddRef(); - } - } - else if (str._header()->nRefCount < 0) - { - // If source string is empty. - _Free(); - m_str = str.m_str; - } - else - { - // Copy string reference. - _Free(); - m_str = str.m_str; - _header()->AddRef(); - } - } - return *this; -} - -template -inline CryStringT& CryStringT::operator=(const_str str) -{ - AZ_Assert(str == nullptr || _IsValidString(str), "Input string is not valid"); - _Assign(str, _strlen(str)); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(const_str str) -{ - AZ_Assert(str == nullptr || _IsValidString(str), "Input string is not valid"); - _ConcatenateInPlace(str, _strlen(str)); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(value_type ch) -{ - _ConcatenateInPlace(&ch, 1); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(const CryStringT& str) -{ - _ConcatenateInPlace(str.m_str, str.length()); - return *this; -} - -//! find first single character -template -inline typename CryStringT::size_type CryStringT::find(value_type ch, size_type pos) const -{ - if (!(pos >= 0 && pos <= length())) - { - return (typename CryStringT::size_type)npos; - } - const_str str = _strchr(m_str + pos, ch); - // return npos if not found and index otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find a sub-string (like strstr) -template -inline typename CryStringT::size_type CryStringT::find(const_str subs, size_type pos) const -{ - AZ_Assert(_IsValidString(subs), "Input string is not valid"); - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - // find first matching substring - const_str str = _strstr(m_str + pos, subs); - - // return npos for not found, distance from beginning otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find last single character -template -inline typename CryStringT::size_type CryStringT::rfind(value_type ch, size_type pos) const -{ - const_str str; - if (pos == npos) - { - // find last single character - str = _strrchr(m_str, ch); - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); - } - else - { - if (pos == npos) - { - pos = length(); - } - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - value_type tmp = m_str[pos + 1]; - m_str[pos + 1] = 0; - str = _strrchr(m_str, ch); - m_str[pos + 1] = tmp; - } - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -template -inline typename CryStringT::size_type CryStringT::rfind(const CryStringT& subs, size_type pos) const -{ - size_type res = npos; - for (int i = (int)size(); i >= (int)pos; --i) - { - size_type findRes = find(subs, i); - if (findRes != npos) - { - res = findRes; - break; - } - } - return res; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(const CryStringT& _Str, size_type _Off) const -{ - return find_first_of(_Str.m_str, _Off); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(value_type _Ch, size_type nOff) const -{ - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - value_type charSet[2] = { _Ch, 0 }; - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(const_str charSet, size_type nOff) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -template <> -inline CryStringT::size_type CryStringT::find_first_of(const_str charSet, size_type nOff) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = wcspbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -//size_type find_first_not_of(const _Self& __s, size_type __pos = 0) const -//{ return find_first_not_of(__s._M_start, __pos, __s.size()); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const -//{ _STLP_FIX_LITERAL_BUG(__s) return find_first_not_of(__s, __pos, _Traits::length(__s)); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const; - -//size_type find_first_not_of(_CharT __c, size_type __pos = 0) const; - - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const value_type* _Ptr, size_type _Off) const -{ return find_first_not_of(_Ptr, _Off, _strlen(_Ptr)); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const CryStringT& _Str, size_type _Off) const -{ return find_first_not_of(_Str.m_str, _Off); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(value_type _Ch, size_type _Off) const -{ - if (_Off > length()) - { - return npos; - } - else - { - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - if (*str != _Ch) - { - return size_type(str - begin()); // Character found! - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - if (_Off > length()) - { - return npos; - } - else - { - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - const value_type* c; - for (c = charsFirst; c != charsLast; ++c) - { - if (*c == *str) - { - break; - } - } - if (c == charsLast) - { - return size_type(str - begin());// Current character not in char set. - } - } - return npos; - } -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(value_type _Ch, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // We found a character in the string which matches the input character. - if (*str == _Ch) - { - return size_type(str - begin()); // Character found! - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // We found nothing. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const value_type* _Ptr, size_type _Off) const -{ - // This function is actually a convenience alias... - // BTW: what will happeb if wchar_t is used here? - return find_last_of(_Ptr, _Off, _strlen(_Ptr)); -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - // From the character at the offset position, going to to the direction of the first character. - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; true; --str) - { - const value_type* c; - // For every character in the character set. - for (c = charsFirst; c != charsLast; ++c) - { - // If the current character matches any of the charcaters in the input string... - if (*c == *str) - { - // This is the value we must return. - return size_type(str - begin()); - } - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - // We couldn't find any character of the input string in the current string. - return npos; -} -///////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const _Self& strCharSet, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // We check every character of the input string. - for (const value_type* strInputCharacter = strCharSet.begin(); strInputCharacter != strCharSet.end(); ++strInputCharacter) - { - // If any character matches. - if (*str == *strInputCharacter) - { - // We return the position where we found it. - return size_type(str - begin()); // Character found! - } - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(value_type _Ch, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // If the current character being analyzed is different of the input character. - if (*str != _Ch) - { - // We found the last item which is not the input character before the given offset. - return size_type(str - begin()); // Character found! - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const value_type* _Ptr, size_type _Off) const -{ - // This function is actually a convenience alias... - // BTW: what will happeb if wchar_t is used here? - return find_last_not_of(_Ptr, _Off, _strlen(_Ptr)); -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; true; --str) - { - bool boFoundAny(false); - const value_type* c; - // For every character in the character set. - for (c = charsFirst; c != charsLast; ++c) - { - // If the current character matches any of the charcaters in the input string... - if (*c == *str) - { - // So we signal it was found and stop this search. - boFoundAny = true; - break; - } - } - - // Using a different solution of the other similar methods - // to make it easier to read. - // If the character being analyzed is not in the set... - if (!boFoundAny) - { - //.. we return the position where we found it. - return size_type(str - begin()); - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - // We couldn't find any character of the input string not in the character set. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const _Self& _Str, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - bool boFoundAny(false); - for (const value_type* strInputCharacter = _Str.begin(); strInputCharacter != _Str.end(); ++strInputCharacter) - { - // The character matched one of the character set... - if (*strInputCharacter == *str) - { - // So we signal it was found and stop this search. - boFoundAny = true; - break; - } - } - - // Using a different solution of the other similar methods - // to make it easier to read. - // If the character being analyzed is not in the set... - if (!boFoundAny) - { - //.. we return the position where we found it. - return size_type(str - begin()); - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT CryStringT::substr(size_type pos, size_type count) const -{ - if (pos >= length()) - { - return CryStringT(); - } - if (count == npos) - { - count = length() - pos; - } - if (pos + count > length()) - { - count = length() - pos; - } - return CryStringT(m_str + pos, count); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::erase(size_type nIndex, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - if (nCount < 0 || nCount > length() - nIndex) - { - nCount = length() - nIndex; - } - if (nCount > 0 && nIndex < length()) - { - _MakeUnique(); - size_type nNumToCopy = length() - (nIndex + nCount) + 1; - _move(m_str + nIndex, m_str + nIndex + nCount, nNumToCopy); - _header()->nLength = length() - nCount; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, value_type ch) -{ - return insert(nIndex, 1, ch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, size_type nCount, value_type ch) -{ - _MakeUnique(); - - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nNewLength = length(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nCount; - - if (capacity() < nNewLength) - { - StrHeader* pOldData = _header(); - const_str pstr = m_str; - _AllocData(nNewLength); - _copy(m_str, pstr, pOldData->nLength + 1); - _FreeData(pOldData); - } - - _move(m_str + nIndex + nCount, m_str + nIndex, (nNewLength - nIndex - nCount) + 1); - _set(m_str + nIndex, ch, nCount); - _header()->nLength = nNewLength; - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, const_str pstr, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nInsertLength = nCount; - size_type nNewLength = length(); - if (nInsertLength > 0) - { - _MakeUnique(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nInsertLength; - - if (capacity() < nNewLength) - { - StrHeader* pOldData = _header(); - const_str pOldStr = m_str; - _AllocData(nNewLength); - _copy(m_str, pOldStr, (pOldData->nLength + 1)); - _FreeData(pOldData); - } - - _move(m_str + nIndex + nInsertLength, m_str + nIndex, (nNewLength - nIndex - nInsertLength + 1)); - _copy(m_str + nIndex, pstr, nInsertLength); - _header()->nLength = nNewLength; - m_str[length()] = 0; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, const_str pstr) -{ - return insert(nIndex, pstr, _strlen(pstr)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, const_str strNew) -{ - return replace(pos, count, strNew, _strlen(strNew)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, const_str strNew, size_type count2) -{ - erase(pos, count); - insert(pos, strNew, count2); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, size_type nNumChars, value_type chNew) -{ - erase(pos, count); - insert(pos, nNumChars, chNew); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(value_type chOld, value_type chNew) -{ - if (chOld != chNew) - { - _MakeUnique(); - value_type* strend = m_str + length(); - for (value_type* str = m_str; str != strend; ++str) - { - if (*str == chOld) - { - *str = chNew; - } - } - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(const_str strOld, const_str strNew) -{ - size_type nSourceLen = _strlen(strOld); - if (nSourceLen == 0) - { - return *this; - } - size_type nReplacementLen = _strlen(strNew); - - size_type nCount = 0; - value_type* strStart = m_str; - value_type* strEnd = m_str + length(); - value_type* strTarget; - while (strStart < strEnd) - { - while ((strTarget = _strstr(strStart, strOld)) != NULL) - { - nCount++; - strStart = strTarget + nSourceLen; - } - strStart += _strlen(strStart) + 1; - } - - if (nCount > 0) - { - _MakeUnique(); - - size_type nOldLength = length(); - size_type nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; - if (capacity() < nNewLength || _header()->nRefCount > 1) - { - StrHeader* pOldData = _header(); - const_str pstr = m_str; - _AllocData(nNewLength); - _copy(m_str, pstr, pOldData->nLength); - _FreeData(pOldData); - } - strStart = m_str; - strEnd = m_str + length(); - - while (strStart < strEnd) - { - while ((strTarget = _strstr(strStart, strOld)) != NULL) - { - size_type nBalance = nOldLength - ((size_type)(strTarget - m_str) + nSourceLen); - _move(strTarget + nReplacementLen, strTarget + nSourceLen, nBalance); - _copy(strTarget, strNew, nReplacementLen); - strStart = strTarget + nReplacementLen; - strStart[nBalance] = 0; - nOldLength += (nReplacementLen - nSourceLen); - } - strStart += _strlen(strStart) + 1; - } - _header()->nLength = nNewLength; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::swap(CryStringT& _Str) -{ - value_type* temp = _Str.m_str; - _Str.m_str = m_str; - m_str = temp; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Format(const_str format, ...) -{ - AZ_Assert(_IsValidString(format), "format c-string must not be nullptr"); - -#if defined(WIN32) || defined(WIN64) - va_list argList; - va_start(argList, format); - int n = _vscpf(format, argList); - if (n < 0) - { - n = 0; - } - resize(n); //this will actually allocate n+1 elements to accommodate the null terminator - _vsnpf(m_str, n, format, argList); - va_end(argList); - return *this; -#else - value_type temp[4096]; // Limited to 4096 characters! - va_list argList; - va_start(argList, format); - _vsnpf(temp, 4096, format, argList); - temp[4095] = '\0'; - va_end(argList); - *this = temp; - return *this; -#endif -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::MakeLower() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - const value_type c = *s; - *s = (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; // ASCII only, standard "C" locale - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::MakeUpper() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - const value_type c = *s; - *s = (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; // ASCII only, standard "C" locale - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim() -{ - return TrimRight().TrimLeft(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim(value_type ch) -{ - _MakeUnique(); - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset).TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim(const value_type* sCharSet) -{ - _MakeUnique(); - return TrimRight(sCharSet).TrimLeft(sCharSet); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet) || length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (_strchr(sCharSet, *str) != 0)) - { - str--; - } - - if (str != last) - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight() -{ - if (length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (isspace((unsigned char)*str) != 0)) - { - str--; - } - - if (str != last) // something changed? - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet)) - { - return *this; - } - - const value_type* str = m_str; - while ((*str != 0) && (_strchr(sCharSet, *str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - _move(m_str, m_str + nOff, nNewLength + 1); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft() -{ - const value_type* str = m_str; - while ((*str != 0) && (isspace((unsigned char)*str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - _move(m_str, m_str + nOff, nNewLength + 1); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -template -inline CryStringT CryStringT::Right(size_type count) const -{ - if (count == npos) - { - return CryStringT(); - } - else if (count > length()) - { - return *this; - } - - return CryStringT(m_str + length() - count, count); -} - -template -inline CryStringT CryStringT::Left(size_type count) const -{ - if (count == npos) - { - return CryStringT(); - } - else if (count > length()) - { - count = length(); - } - - return CryStringT(m_str, count); -} - -// strspn equivalent -template -inline CryStringT CryStringT::SpanIncluding(const_str charSet) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - return Left((size_type)strspn(m_str, charSet)); -} - -// strcspn equivalent -template -inline CryStringT CryStringT::SpanExcluding(const_str charSet) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - return Left((size_type)strcspn(m_str, charSet)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT CryStringT::Tokenize(const_str charSet, int& nStart) const -{ - if (nStart < 0) - { - return CryStringT(); - } - - if (!charSet) - { - return *this; - } - - const_str sPlace = m_str + nStart; - const_str sEnd = m_str + length(); - if (sPlace < sEnd) - { - int nIncluding = (int)strspn(sPlace, charSet); - - if ((sPlace + nIncluding) < sEnd) - { - sPlace += nIncluding; - int nExcluding = (int)strcspn(sPlace, charSet); - int nFrom = nStart + nIncluding; - nStart = nFrom + nExcluding + 1; - - return substr(nFrom, nExcluding); - } - } - // Return empty string. - nStart = -1; - return CryStringT(); -} - -////////////////////////////////////////////////////////////////////////// -// This code prevents std::string compiling in Win32 with STLPort -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) && !defined(WIN64) && defined(_STLP_BEGIN_NAMESPACE) && !defined(DONT_BAN_STD_STRING) -#define CRYINCLUDE_STLP_STRING_FWD_H -#define CRYINCLUDE_STLP_INTERNAL_STRING_H -namespace std -{ - //const char* __get_c_string( const CryStringT &str ) { return str.c_str(); }; - class string - { - // std::string must not be used if CryString included. - // Use string instead. - }; -} -////////////////////////////////////////////////////////////////////////// -#endif // WIN64 - -typedef CryStringT string; -typedef CryStringT wstring; - -#else // !defined(NOT_USE_CRY_STRING) - -#include // STL string -typedef std::string string; -typedef std::wstring wstring; - -#endif // !defined(NOT_USE_CRY_STRING) - -namespace AZStd -{ - template <> - struct hash<::string> - { - typedef ::string argument_type; - typedef size_t result_type; - inline result_type operator()(const argument_type& value) const - { - return hash_string(value.c_str(), value.length()); - } - - static size_t hash_string(const char* str, size_t length) - { - size_t hash = 14695981039346656037ULL; - const size_t fnvPrime = 1099511628211ULL; - const char* cptr = str; - for (; length; --length) - { - hash ^= static_cast(*cptr++); - hash *= fnvPrime; - } - return hash; - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRYSTRING_H diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h index b80666ce73..f85ddf763c 100644 --- a/Code/Legacy/CryCommon/CryThread_windows.h +++ b/Code/Legacy/CryCommon/CryThread_windows.h @@ -260,7 +260,7 @@ private: volatile bool m_bIsStarted; volatile bool m_bIsRunning; volatile bool m_bCreatedThread; - string m_name; + AZStd::string m_name; protected: virtual void Terminate() diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp index bd2bfb8bb2..ffadc732b0 100644 --- a/Code/Legacy/CryCommon/CryTypeInfo.cpp +++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp @@ -114,7 +114,7 @@ TYPE_INFO_INT(uint64) TYPE_INFO_BASIC(float) TYPE_INFO_BASIC(double) -TYPE_INFO_BASIC(string) +TYPE_INFO_BASIC(AZStd::string) const CTypeInfo&PtrTypeInfo() @@ -129,9 +129,9 @@ const CTypeInfo&PtrTypeInfo() // String conversion functions needed by TypeInfo. // bool -string ToString(bool const& val) +AZStd::string ToString(bool const& val) { - static string sTrue = "true", sFalse = "false"; + static AZStd::string sTrue = "true", sFalse = "false"; return val ? sTrue : sFalse; } @@ -151,14 +151,14 @@ bool FromString(bool& val, cstr s) } // int64 -string ToString(int64 const& val) +AZStd::string ToString(int64 const& val) { char buffer[64]; _i64toa_s(val, buffer, sizeof(buffer), 10); return buffer; } // uint64 -string ToString(uint64 const& val) +AZStd::string ToString(uint64 const& val) { char buffer[64]; sprintf_s(buffer, "%" PRIu64, val); @@ -168,7 +168,7 @@ string ToString(uint64 const& val) // long -string ToString(long const& val) +AZStd::string ToString(long const& val) { char buffer[64]; _ltoa_s(val, buffer, sizeof(buffer), 10); @@ -176,7 +176,7 @@ string ToString(long const& val) } // ulong -string ToString(unsigned long const& val) +AZStd::string ToString(unsigned long const& val) { char buffer[64]; _ultoa_s(val, buffer, sizeof(buffer), 10); @@ -233,33 +233,33 @@ bool FromString(uint64& val, const char* s) { return Clamped bool FromString(long& val, const char* s) { return ClampedIntFromString(val, s); } bool FromString(unsigned long& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(int const& val) { return ToString(long(val)); } +AZStd::string ToString(int const& val) { return ToString(long(val)); } bool FromString(int& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(unsigned int const& val) { return ToString((unsigned long)(val)); } +AZStd::string ToString(unsigned int const& val) { return ToString((unsigned long)(val)); } bool FromString(unsigned int& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(short const& val) { return ToString(long(val)); } +AZStd::string ToString(short const& val) { return ToString(long(val)); } bool FromString(short& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(unsigned short const& val) { return ToString((unsigned long)(val)); } +AZStd::string ToString(unsigned short const& val) { return ToString((unsigned long)(val)); } bool FromString(unsigned short& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(char const& val) { return ToString(long(val)); } +AZStd::string ToString(char const& val) { return ToString(long(val)); } bool FromString(char& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(wchar_t const& val) { return ToString(long(val)); } +AZStd::string ToString(wchar_t const& val) { return ToString(long(val)); } bool FromString(wchar_t& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(signed char const& val) { return ToString(long(val)); } +AZStd::string ToString(signed char const& val) { return ToString(long(val)); } bool FromString(signed char& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(unsigned char const& val) { return ToString((unsigned long)(val)); } +AZStd::string ToString(unsigned char const& val) { return ToString((unsigned long)(val)); } bool FromString(unsigned char& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(const AZ::Uuid& val) +AZStd::string ToString(const AZ::Uuid& val) { - return val.ToString(); + return val.ToString(); } bool FromString(AZ::Uuid& val, const char* s) @@ -295,7 +295,7 @@ float NumToFromString(float val, int digits, bool floating, char buffer[], int b } // double -string ToString(double const& val) +AZStd::string ToString(double const& val) { char buffer[64]; sprintf_s(buffer, "%.16g", val); @@ -307,7 +307,7 @@ bool FromString(double& val, const char* s) } // float -string ToString(float const& val) +AZStd::string ToString(float const& val) { char buffer[64]; for (int digits = 7; digits < 10; digits++) @@ -329,11 +329,11 @@ bool FromString(float& val, const char* s) // string override. template <> -void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const +void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const { // CRAIG: just a temp hack to try and get things working #if !defined(LINUX) && !defined(APPLE) - pSizer->AddString(*(string*)data); + pSizer->AddString(*(AZStd::string*)data); #endif } @@ -343,7 +343,7 @@ struct STypeInfoTest { STypeInfoTest() { - TestType(string("well")); + TestType(AZStd::string("well")); TestType(true); @@ -435,7 +435,7 @@ bool CTypeInfo::CVarInfo::GetAttr(cstr name) const return FindAttr(Attrs, name) != 0; } -bool CTypeInfo::CVarInfo::GetAttr(cstr name, string& val) const +bool CTypeInfo::CVarInfo::GetAttr(cstr name, AZStd::string& val) const { cstr valstr = FindAttr(Attrs, name); if (!valstr) @@ -459,7 +459,7 @@ bool CTypeInfo::CVarInfo::GetAttr(cstr name, string& val) const end--; } } - val = string(valstr, end - valstr); + val = AZStd::string(valstr, end - valstr); return true; } @@ -735,7 +735,7 @@ bool CStructInfo::ToValue(const void* data, void* value, const CTypeInfo& typeVa Nameless , 1, ,2 1,2 ; */ -static void StripCommas(string& str) +static void StripCommas(AZStd::string& str) { size_t nLast = str.size(); while (nLast > 0 && str[nLast - 1] == ',') @@ -745,9 +745,9 @@ static void StripCommas(string& str) str.resize(nLast); } -string CStructInfo::ToString(const void* data, FToString flags, const void* def_data) const +AZStd::string CStructInfo::ToString(const void* data, FToString flags, const void* def_data) const { - string str; // Return str. + AZStd::string str; // Return str. for (int i = 0; i < Vars.size(); i++) { @@ -763,7 +763,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ str += ","; } - string substr = var.ToString(data, FToString(flags).Sub(0), def_data); + AZStd::string substr = var.ToString(data, FToString(flags).Sub(0), def_data); if (flags.SkipDefault && substr.empty()) { @@ -772,7 +772,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ if (flags.NamedFields) { - if (*str) + if (*str.c_str()) { str += ","; } @@ -782,7 +782,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ str += "="; } } - if (substr.find(',') != string::npos || substr.find('=') != string::npos) + if (substr.find(',') != AZStd::string::npos || substr.find('=') != AZStd::string::npos) { // Encase nested composite types in parens. str += "("; @@ -811,7 +811,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ // Retrieve and return one subelement from src, advancing the pointer. // Copy to tempstr if necessary. -typedef CryStackStringT CTempStr; +typedef AZStd::fixed_string<256> CTempStr; void ParseElement(cstr& src, cstr& varname, cstr& val, CTempStr& tempstr) { @@ -882,21 +882,24 @@ void ParseElement(cstr& src, cstr& varname, cstr& val, CTempStr& tempstr) if (*end) { // Must copy sub string to temp. - val = (cstr)tempstr + (val - varname); - eq = (cstr)tempstr + (eq - varname); - varname = tempstr.assign(varname, end); + val = tempstr.c_str() + (val - varname); + eq = tempstr.c_str() + (eq - varname); + tempstr.assign(varname, end); + varname = tempstr.c_str(); non_const(*eq) = 0; } else { // Copy just varname to temp, return val in place. - varname = tempstr.assign(varname, eq); + tempstr.assign(varname, eq); + varname = tempstr.c_str(); } } else if (*end) { // Must copy sub string to temp. - val = tempstr.assign(val, end); + tempstr.assign(val, end); + val = tempstr.c_str(); } // Else can return val without copying. @@ -963,7 +966,7 @@ void CStructInfo::SwapEndian(void* data, size_t nCount, bool bWriting) const { non_const(*this).MakeEndianDesc(); - if (EndianDesc.length() == 1 && !HasBitfields && EndianDescSize(EndianDesc) == Size) + if (EndianDesc.length() == 1 && !HasBitfields && EndianDescSize(EndianDesc.c_str()) == Size) { // Optimised array swap. size_t nElems = (EndianDesc[0u] & 0x3F) * nCount; @@ -989,7 +992,7 @@ void CStructInfo::SwapEndian(void* data, size_t nCount, bool bWriting) const // First swap bits. // Iterate the endian descriptor. void* step = data; - for (cstr desc = EndianDesc; *desc; desc++) + for (cstr desc = EndianDesc.c_str(); *desc; desc++) { size_t nElems = *desc & 0x3F; switch (*desc & 0xC0) @@ -1064,7 +1067,7 @@ void CStructInfo::MakeEndianDesc() // Struct-computed endian desc. CStructInfo const& infoSub = static_cast(var.Type); non_const(infoSub).MakeEndianDesc(); - subdesc = infoSub.EndianDesc; + subdesc = infoSub.EndianDesc.c_str(); if (!*subdesc) { // No swapping. diff --git a/Code/Legacy/CryCommon/CryTypeInfo.h b/Code/Legacy/CryCommon/CryTypeInfo.h index 43b9d3e5b9..0bd734492a 100644 --- a/Code/Legacy/CryCommon/CryTypeInfo.h +++ b/Code/Legacy/CryCommon/CryTypeInfo.h @@ -17,13 +17,12 @@ #include #include "CryArray.h" #include "Options.h" -#include "CryString.h" #include "TypeInfo_decl.h" class ICrySizer; class CCryName; -string ToString(CCryName const& val); +AZStd::string ToString(CCryName const& val); bool FromString(CCryName& val, const char* s); //--------------------------------------------------------------------------- @@ -85,7 +84,7 @@ struct CTypeInfo // // Convert value to string. - virtual string ToString([[maybe_unused]] const void* data, [[maybe_unused]] FToString flags = 0, [[maybe_unused]] const void* def_data = 0) const + virtual AZStd::string ToString([[maybe_unused]] const void* data, [[maybe_unused]] FToString flags = 0, [[maybe_unused]] const void* def_data = 0) const { return ""; } // Write value from string, return success. @@ -180,7 +179,7 @@ struct CTypeInfo assert(!bBitfield); return Type.FromString((char*)base + Offset, str, flags); } - string ToString(const void* base, FToString flags = 0, const void* def_base = 0) const + AZStd::string ToString(const void* base, FToString flags = 0, const void* def_base = 0) const { assert(!bBitfield); return Type.ToString((const char*)base + Offset, flags, def_base ? (const char*)def_base + Offset : 0); @@ -189,7 +188,7 @@ struct CTypeInfo // Attribute access. Not fast. bool GetAttr(cstr name) const; bool GetAttr(cstr name, float& val) const; - bool GetAttr(cstr name, string& val) const; + bool GetAttr(cstr name, AZStd::string& val) const; // Comment, excluding attributes. cstr GetComment() const; diff --git a/Code/Legacy/CryCommon/IEntityRenderState.h b/Code/Legacy/CryCommon/IEntityRenderState.h index 9ee974b7fc..e9f041ba17 100644 --- a/Code/Legacy/CryCommon/IEntityRenderState.h +++ b/Code/Legacy/CryCommon/IEntityRenderState.h @@ -205,7 +205,7 @@ struct IRenderNode // Debug info about object. virtual const char* GetName() const = 0; virtual const char* GetEntityClassName() const = 0; - virtual string GetDebugString([[maybe_unused]] char type = 0) const { return ""; } + virtual AZStd::string GetDebugString([[maybe_unused]] char type = 0) const { return ""; } virtual float GetImportance() const { return 1.f; } // Description: diff --git a/Code/Legacy/CryCommon/IFont.h b/Code/Legacy/CryCommon/IFont.h index c95182abd7..41e9f5653a 100644 --- a/Code/Legacy/CryCommon/IFont.h +++ b/Code/Legacy/CryCommon/IFont.h @@ -16,7 +16,6 @@ #include #include -#include #include #include @@ -101,7 +100,7 @@ struct ICryFont // All font names separated by , // Example: // "console,default,hud" - virtual string GetLoadedFontNames() const = 0; + virtual AZStd::string GetLoadedFontNames() const = 0; //! \brief Called when the g_language (current language) setting changes. //! @@ -264,7 +263,7 @@ struct IFFont // Description: // Wraps text based on specified maximum line width (UTF-8) - virtual void WrapText(string& result, float maxWidth, const char* pStr, const STextDrawContext& ctx) = 0; + virtual void WrapText(AZStd::string& result, float maxWidth, const char* pStr, const STextDrawContext& ctx) = 0; // Description: // Puts the memory used by this font into the given sizer. @@ -338,7 +337,7 @@ struct FontFamily FontFamily& operator=(const FontFamily&) = delete; FontFamily& operator=(const FontFamily&&) = delete; - string familyName; + AZStd::string familyName; IFFont* normal; IFFont* bold; IFFont* italic; diff --git a/Code/Legacy/CryCommon/IRenderer.h b/Code/Legacy/CryCommon/IRenderer.h index d3557129bf..254f1933de 100644 --- a/Code/Legacy/CryCommon/IRenderer.h +++ b/Code/Legacy/CryCommon/IRenderer.h @@ -17,7 +17,6 @@ #include "Cry_Matrix33.h" #include "Cry_Color.h" #include "smartptr.h" -#include "StringUtils.h" #include // <> required for Interfuscator #include "smartptr.h" #include @@ -1449,7 +1448,7 @@ struct IRenderer virtual const char* EF_GetShaderMissLogPath() = 0; ///////////////////////////////////////////////////////////////////////////////// - virtual string* EF_GetShaderNames(int& nNumShaders) = 0; + virtual AZStd::string* EF_GetShaderNames(int& nNumShaders) = 0; // Summary: // Reloads file virtual bool EF_ReloadFile (const char* szFileName) = 0; diff --git a/Code/Legacy/CryCommon/ISerialize.h b/Code/Legacy/CryCommon/ISerialize.h index 0476237903..84e665850f 100644 --- a/Code/Legacy/CryCommon/ISerialize.h +++ b/Code/Legacy/CryCommon/ISerialize.h @@ -179,28 +179,16 @@ struct SSerializeString void resize(int sz) { m_str.resize(sz); } void reserve(int sz) { m_str.reserve(sz); } - void set_string(const string& s) + void set_string(const AZStd::string& s) { m_str.assign(s.begin(), s.size()); } -#if !defined(RESOURCE_COMPILER) - void set_string(const CryStringLocal& s) - { - m_str.assign(s.begin(), s.size()); - } -#endif - template - void set_string(const CryFixedStringT& s) - { - m_str.assign(s.begin(), s.size()); - } - - operator const string () const { + operator const AZStd::string() const { return m_str; } private: - string m_str; + AZStd::string m_str; }; // the ISerialize is intended to be implemented by objects that need @@ -308,7 +296,7 @@ public: m_pSerialize->Value(szName, value); } - void Value(const char* szName, string& value, int policy) + void Value(const char* szName, AZStd::string& value, int policy) { if (IsWriting()) { @@ -327,11 +315,11 @@ public: value = serializeString.c_str(); } } - ILINE void Value(const char* szName, string& value) + ILINE void Value(const char* szName, AZStd::string& value) { Value(szName, value, 0); } - void Value(const char* szName, const string& value, int policy) + void Value(const char* szName, const AZStd::string& value, int policy) { if (IsWriting()) { @@ -343,76 +331,7 @@ public: assert(0 && "This function can only be used for Writing"); } } - ILINE void Value(const char* szName, const string& value) - { - Value(szName, value, 0); - } - template - void Value(const char* szName, CryStringLocalT& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - if (GetSerializationTarget() != eST_Script) - { - value = ""; - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ReadStringValue(szName, serializeString, policy); - value = serializeString.c_str(); - } - } - template - ILINE void Value(const char* szName, CryStringLocalT& value) - { - Value(szName, value, 0); - } - template - void Value(const char* szName, const CryStringLocalT& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - assert(0 && "This function can only be used for Writing"); - } - } - template - ILINE void Value(const char* szName, const CryStringLocalT& value) - { - Value(szName, value, 0); - } - template - void Value(const char* szName, CryFixedStringT& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - if (GetSerializationTarget() != eST_Script) - { - value = ""; - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ReadStringValue(szName, serializeString, policy); - assert(serializeString.length() <= S); - value = serializeString.c_str(); - } - } - template - ILINE void Value(const char* szName, CryFixedStringT& value) + ILINE void Value(const char* szName, const AZStd::string& value) { Value(szName, value, 0); } @@ -493,7 +412,7 @@ public: m_pSerialize->ValueWithDefault(name, x, defaultValue); } - void ValueWithDefault(const char* szName, string& value, const string& defaultValue) + void ValueWithDefault(const char* szName, AZStd::string& value, const AZStd::string& defaultValue) { static SSerializeString defaultSerializeString; @@ -919,29 +838,8 @@ public: return CSerializeWrapper(m_pSerialize); } - SSerializeString& SetSharedSerializeString(const string& str) - { - static SSerializeString serializeString; - serializeString.set_string(str); - return serializeString; - } - -#if !defined(RESOURCE_COMPILER) - SSerializeString& SetSharedSerializeString(const CryStringLocal& str) - { - - - static SSerializeString serializeString; - serializeString.set_string(str); - return serializeString; - } -#endif - - template - SSerializeString& SetSharedSerializeString(const CryFixedStringT& str) + SSerializeString& SetSharedSerializeString(const AZStd::string& str) { - - static SSerializeString serializeString; serializeString.set_string(str); return serializeString; diff --git a/Code/Legacy/CryCommon/IShader.h b/Code/Legacy/CryCommon/IShader.h index 3a49e4d1ac..978da1a77f 100644 --- a/Code/Legacy/CryCommon/IShader.h +++ b/Code/Legacy/CryCommon/IShader.h @@ -25,7 +25,6 @@ #include "Cry_Matrix33.h" #include "Cry_Color.h" #include "smartptr.h" -#include "StringUtils.h" #include // <> required for Interfuscator #include "smartptr.h" #include "VertexFormats.h" @@ -1394,12 +1393,12 @@ struct IRenderTarget struct STexSamplerFX { #if SHADER_REFLECT_TEXTURE_SLOTS - string m_szUIName; - string m_szUIDescription; + AZStd::string m_szUIName; + AZStd::string m_szUIDescription; #endif - string m_szName; - string m_szTexture; + AZStd::string m_szName; + AZStd::string m_szTexture; union { @@ -1708,7 +1707,7 @@ struct SEfResTextureExt //------------------------------------------------------------------------------ struct SEfResTexture { - string m_Name; + AZStd::string m_Name; bool m_bUTile; bool m_bVTile; signed char m_Filter; @@ -1890,7 +1889,7 @@ struct SEfResTexture struct SBaseShaderResources { AZStd::vector m_ShaderParams; - string m_TexturePath; + AZStd::string m_TexturePath; const char* m_szMaterialName; float m_AlphaRef; @@ -2146,8 +2145,8 @@ struct SShaderTextureSlot m_TexType = eTT_MaxTexType; } - string m_Name; - string m_Description; + AZStd::string m_Name; + AZStd::string m_Description; byte m_TexType; // 2D, 3D, Cube etc.. void GetMemoryUsage(ICrySizer* pSizer) const @@ -2726,7 +2725,7 @@ protected: virtual ~ILightAnimWrapper() {} protected: - string m_name; + AZStd::string m_name; IAnimNode* m_pNode; }; @@ -3256,12 +3255,12 @@ enum EGrNodeIOSemantic struct SShaderGraphFunction { - string m_Data; - string m_Name; - std::vector inParams; - std::vector outParams; - std::vector szInTypes; - std::vector szOutTypes; + AZStd::string m_Data; + AZStd::string m_Name; + std::vector inParams; + std::vector outParams; + std::vector szInTypes; + std::vector szOutTypes; }; struct SShaderGraphNode @@ -3269,8 +3268,8 @@ struct SShaderGraphNode EGrNodeType m_eType; EGrNodeFormat m_eFormat; EGrNodeIOSemantic m_eSemantic; - string m_CustomSemantics; - string m_Name; + AZStd::string m_CustomSemantics; + AZStd::string m_Name; bool m_bEditable; bool m_bWasAdded; SShaderGraphFunction* m_pFunction; @@ -3296,7 +3295,7 @@ struct SShaderGraphBlock { EGrBlockType m_eType; EGrBlockSamplerType m_eSamplerType; - string m_ClassName; + AZStd::string m_ClassName; FXShaderGraphNodes m_Nodes; ~SShaderGraphBlock(); diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index d934995b4d..973196ac4c 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -946,7 +946,7 @@ struct ISystem // If m_GraphicsSettingsMap is defined (in Graphics Settings Dialog box), fills in mapping based on sys_spec_Full // Arguments: // sPath - e.g. "Game/Config/CVarGroups" - virtual void AddCVarGroupDirectory(const string& sPath) = 0; + virtual void AddCVarGroupDirectory(const AZStd::string& sPath) = 0; // Summary: // Saves system configuration. diff --git a/Code/Legacy/CryCommon/IXml.h b/Code/Legacy/CryCommon/IXml.h index b722da78e3..e4cb752234 100644 --- a/Code/Legacy/CryCommon/IXml.h +++ b/Code/Legacy/CryCommon/IXml.h @@ -94,12 +94,12 @@ void testXml(bool bReuseStrings) // Summary: // Special string wrapper for xml nodes. class XmlString - : public string + : public AZStd::string { public: XmlString() {}; XmlString(const char* str) - : string(str) {}; + : AZStd::string(str) {}; operator const char*() const { return c_str(); diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 2dea83925d..e47d16d1bc 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -329,9 +329,6 @@ inline uint32 GetTickCount() #define _wtof(str) wcstod(str, 0) -// Need to include this before using it's used in finddata, but after the strnicmp definition -#include "CryString.h" - typedef struct __finddata64_t { //!< atributes set by find request diff --git a/Code/Legacy/CryCommon/LyShine/UiBase.h b/Code/Legacy/CryCommon/LyShine/UiBase.h index 274618821e..af6314be2c 100644 --- a/Code/Legacy/CryCommon/LyShine/UiBase.h +++ b/Code/Legacy/CryCommon/LyShine/UiBase.h @@ -65,6 +65,5 @@ namespace AZ AZ_TYPE_INFO_SPECIALIZE(ColorF, "{63782551-A309-463B-A301-3A360800DF1E}"); AZ_TYPE_INFO_SPECIALIZE(ColorB, "{6F0CC2C0-0CC6-4DBF-9297-B043F270E6A4}"); AZ_TYPE_INFO_SPECIALIZE(Vec4, "{CAC9510C-8C00-41D4-BC4D-2C6A8136EB30}"); - AZ_TYPE_INFO_SPECIALIZE(CryStringT, "{835199FB-292B-4DB3-BC7C-366E356300FA}"); } // namespace AZ diff --git a/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h b/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h index 05289c6c50..3ad3de2d3d 100644 --- a/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h +++ b/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h @@ -22,154 +22,6 @@ namespace LyShine { - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to an AZStd::String - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromCryStringToAzString( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a string or not valid - AZ_Error("Serialization", false, "Cannot get string data for element %s.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int newElementIndex = classElement.AddElement(context, subElementName); - if (newElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", subElementName); - return false; - } - - AZStd::string newData(oldData.c_str()); - classElement.GetSubElement(newElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to a char - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromCryStringToChar( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName, - char defaultValue) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a CryString - AZ_Error("Serialization", false, "Element %s is not a CryString.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int newElementIndex = classElement.AddElement(context, subElementName); - if (newElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", subElementName); - return false; - } - - char newData = (oldData.empty()) ? defaultValue : oldData[0]; - classElement.GetSubElement(newElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to a simple asset reference - // Inline to avoid DLL linkage issues - template - inline bool ConvertSubElementFromCryStringToAssetRef( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a CryString - AZ_Error("Serialization", false, "Element %s is not a CryString.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int simpleAssetRefIndex = classElement.AddElement >(context, subElementName); - if (simpleAssetRefIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for simpleAssetRefIndex %s", subElementName); - return false; - } - - // add a sub element for the SimpleAssetReferenceBase within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefNode = classElement.GetSubElement(simpleAssetRefIndex); - int simpleAssetRefBaseIndex = simpleAssetRefNode.AddElement(context, "BaseClass1"); - if (simpleAssetRefBaseIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element BaseClass1"); - return false; - } - - // add a sub element for the AssetPath within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefBaseNode = simpleAssetRefNode.GetSubElement(simpleAssetRefBaseIndex); - int assetPathElementIndex = simpleAssetRefBaseNode.AddElement(context, "AssetPath"); - if (assetPathElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element AssetPath"); - return false; - } - - AZStd::string newData(oldData.c_str()); - simpleAssetRefBaseNode.GetSubElement(assetPathElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - //////////////////////////////////////////////////////////////////////////////////////////////// // Helper function to VersionConverter to convert an AZStd::string field to a simple asset reference // Inline to avoid DLL linkage issues diff --git a/Code/Legacy/CryCommon/StlUtils.h b/Code/Legacy/CryCommon/StlUtils.h index 2438ee9f7b..d7e5697593 100644 --- a/Code/Legacy/CryCommon/StlUtils.h +++ b/Code/Legacy/CryCommon/StlUtils.h @@ -494,7 +494,7 @@ namespace stl //! Specialization of string to const char cast. template <> - inline const char* constchar_cast(const string& type) + inline const char* constchar_cast(const AZStd::string& type) { return type.c_str(); } diff --git a/Code/Legacy/CryCommon/StringUtils.h b/Code/Legacy/CryCommon/StringUtils.h deleted file mode 100644 index ffd1001f95..0000000000 --- a/Code/Legacy/CryCommon/StringUtils.h +++ /dev/null @@ -1,1358 +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 _CRY_ENGINE_STRING_UTILS_HDR_ -#define _CRY_ENGINE_STRING_UTILS_HDR_ - -#pragma once - -#include "CryString.h" -#include -#include // std::replace, std::min -#include "UnicodeFunctions.h" -#include "UnicodeIterator.h" -#include - -#if !defined(RESOURCE_COMPILER) -# include "CryCrc32.h" -#endif - -#if defined(LINUX) || defined(APPLE) -# include -#endif - -namespace CryStringUtils -{ - // Convert a single ASCII character to lower case, this is compatible with the standard "C" locale (ie, only A-Z). - inline char toLowerAscii(char c) - { - return (c >= 'A' && c <= 'Z') ? (c - 'A' + 'a') : c; - } - - // Convert a single ASCII character to upper case, this is compatible with the standard "C" locale (ie, only A-Z). - inline char toUpperAscii(char c) - { - return (c >= 'a' && c <= 'z') ? (c - 'a' + 'A') : c; - } -} - -// cry_strXXX() and CryStringUtils_Internal::strXXX(): -// -// The functions copy characters from src to dst one by one until any of -// the following conditions is met: -// 1) the end of the destination buffer (minus one character) is reached. -// 2) the end of the source buffer is reached. -// 3) zero character is found in the source buffer. -// -// When any of 1), 2), 3) happens, the functions write the terminating zero -// character to the destination buffer and return. -// -// The functions guarantee writing the terminating zero character to the -// destination buffer (if the buffer can fit at least one character). -// -// The functions return false when a null pointer is passed or when -// clamping happened (i.e. when the end of the destination buffer is -// reached but the source has some characters left). - -namespace CryStringUtils_Internal -{ - template - inline bool strcpy_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) - { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); - - if (!dst || dst_size_in_bytes < sizeof(TChar)) - { - return false; - } - - if (!src || src_size_in_bytes < sizeof(TChar)) - { - dst[0] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes / sizeof(TChar); - const size_t n = (std::min)(dst_size_in_bytes / sizeof(TChar) - 1, src_n); - - for (size_t i = 0; i < n; ++i) - { - dst[i] = src[i]; - if (!src[i]) - { - return true; - } - } - - dst[n] = 0; - return n >= src_n || src[n] == 0; - } - - template - inline bool strcat_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) - { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); - - if (!dst || dst_size_in_bytes < sizeof(TChar)) - { - return false; - } - - const size_t dst_n = dst_size_in_bytes / sizeof(TChar) - 1; - - size_t dst_len = 0; - while (dst_len < dst_n && dst[dst_len]) - { - ++dst_len; - } - - if (!src || src_size_in_bytes < sizeof(TChar)) - { - dst[dst_len] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes / sizeof(TChar); - const size_t n = (std::min)(dst_n - dst_len, src_n); - TChar* dst_ptr = &dst[dst_len]; - - for (size_t i = 0; i < n; ++i) - { - *dst_ptr++ = src[i]; - if (!src[i]) - { - return true; - } - } - - *dst_ptr = 0; - return n >= src_n || src[n] == 0; - } - - // Compares characters as case-sensitive, locale agnostic. - template - struct SCharComparatorCaseSensitive - { - static bool IsEqual(CharType a, CharType b) - { - return a == b; - } - }; - - // Compares characters as case-insensitive, uses the standard "C" locale. - template - struct SCharComparatorCaseInsensitive - { - static bool IsEqual(CharType a, CharType b) - { - if (a < 0x80 && b < 0x80) - { - a = (CharType)CryStringUtils::toLowerAscii(char(a)); - b = (CharType)CryStringUtils::toLowerAscii(char(b)); - } - return a == b; - } - }; - - // Template for wildcard matching, UCS code-point aware. - // Can be used for ASCII and Unicode (UTF-8/UTF-16/UTF-32), but not for ANSI. - // ? will match exactly one code-point. - // * will match zero or more code-points. - template class CharComparator, class CharType> - inline bool MatchesWildcards_Tpl(const CharType* pStr, const CharType* pWild) - { - const CharType* savedStr = 0; - const CharType* savedWild = 0; - - while ((*pStr) && (*pWild != '*')) - { - if (!CharComparator::IsEqual(*pWild, *pStr) && (*pWild != '?')) - { - return false; - } - - // We need special handling of '?' for Unicode - if (*pWild == '?' && *pStr > 127) - { - Unicode::CIterator utf(pStr, pStr + 4); - if (utf.IsAtValidCodepoint()) - { - pStr = (++utf).GetPosition(); - --pStr; - } - } - - ++pWild; - ++pStr; - } - - while (*pStr) - { - if (*pWild == '*') - { - if (!*++pWild) - { - return true; - } - savedWild = pWild; - savedStr = pStr + 1; - } - else if (CharComparator::IsEqual(*pWild, *pStr) || (*pWild == '?')) - { - // We need special handling of '?' for Unicode - if (*pWild == '?' && *pStr > 127) - { - Unicode::CIterator utf(pStr, pStr + 4); - if (utf.IsAtValidCodepoint()) - { - pStr = (++utf).GetPosition(); - --pStr; - } - } - - ++pWild; - ++pStr; - } - else - { - pWild = savedWild; - pStr = savedStr++; - } - } - - while (*pWild == '*') - { - ++pWild; - } - - return *pWild == 0; - } -} // namespace CryStringUtils_Internal - - -inline bool cry_strcpy(char* const dst, size_t const dst_size_in_bytes, const char* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_strcpy(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_strcpy(char(&dst)[SIZE_IN_CHARS], const char* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_CHARS, src, (size_t)-1); -} - -template -inline bool cry_strcpy(char(&dst)[SIZE_IN_CHARS], const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_CHARS, src, src_size_in_bytes); -} - - -inline bool cry_wstrcpy(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_wstrcpy(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_wstrcpy(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, (size_t)-1); -} - -template -inline bool cry_wstrcpy(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, src_size_in_bytes); -} - - -inline bool cry_strcat(char* const dst, size_t const dst_size_in_bytes, const char* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_strcat(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_strcat(char(&dst)[SIZE_IN_CHARS], const char* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_CHARS, src, (size_t)-1); -} - -template -inline bool cry_strcat(char(&dst)[SIZE_IN_CHARS], const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_CHARS, src, src_size_in_bytes); -} - - -inline bool cry_wstrcat(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_wstrcat(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_wstrcat(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, (size_t)-1); -} - -template -inline bool cry_wstrcat(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, src_size_in_bytes); -} - - -namespace CryStringUtils -{ - enum - { - CRY_DEFAULT_HASH_SEED = 40503, // This is a large 16 bit prime number (perfect for seeding) - CRY_EMPTY_STR_HASH = 3350499166U, // HashString("") - }; - - // removes the extension from the file path - // \param szFilePath the source path - inline char* StripFileExtension(char* szFilePath) - { - for (char* p = szFilePath + (int)strlen(szFilePath) - 1; p >= szFilePath; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return nullptr; - case '.': - // there's an extension in this file name - *p = '\0'; - return p + 1; - } - } - // it seems the file name is a pure name, without path or extension - return nullptr; - } - - - // returns the parent directory of the given file or directory. - // the returned path is WITHOUT the trailing slash - // if the input path has a trailing slash, it's ignored - // nGeneration - is the number of parents to scan up - // Note: A drive specifier (if any) will always be kept (Windows-specific). - template - StringCls GetParentDirectory(const StringCls& strFilePath, int nGeneration = 1) - { - for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent - p >= strFilePath.c_str(); - --p) - { - switch (*p) - { - case ':': - return StringCls(strFilePath.c_str(), p); - break; - case '/': - case '\\': - // we've reached a path separator - return everything before it. - if (!--nGeneration) - { - return StringCls(strFilePath.c_str(), p); - } - break; - } - } - ; - // the file name is a pure name, without path or extension - return StringCls(); - } - - /*! - // converts all chars to lower case - */ - inline string ToLower(const string& str) - { - string temp = str; - -#ifndef NOT_USE_CRY_STRING - temp.MakeLower(); -#else - std::transform(temp.begin(), temp.end(), temp.begin(), toLowerAscii); // STL MakeLower -#endif - - return temp; - } - - /// Converts the single character to lower case. - /*! - \param c source character to convert to lower case if possible - \return the lower case character equivalent if possible - */ - inline char ToLower(char c) - { - return ((c <= 'Z') && (c >= 'A')) ? c + ('a' - 'A') : c; - } - - /// Converts the specified character into lowercase. - /*! - \param c the character to convert to lowercase - \return the lowercase character - */ - // Converts all ASCII characters to upper case. - // Note: Any non-ASCII characters are left unchanged. - // This function is ASCII-only and locale agnostic. - inline string toUpper (const string& str) - { - string temp = str; - -#ifndef NOT_USE_CRY_STRING - temp.MakeUpper(); -#else - std::transform(temp.begin(), temp.end(), temp.begin(), toUpperAscii); // STL MakeLower -#endif - - return temp; - } - - // searches and returns the pointer to the extension of the given file - /*! - \param szFileName source filename to search - // This function is Unicode agnostic and locale agnostic. - */ - inline const char* FindExtension(const char* szFileName) - { - const char* szEnd = szFileName + (int)strlen(szFileName); - for (const char* p = szEnd - 1; p >= szFileName; --p) - { - if (*p == '.') - { - return p + 1; - } - } - - return szEnd; - } - - // searches and returns the pointer to the file name in the given file path - /*! - \param szFilePath source path to search - */ - inline const char* FindFileNameInPath(const char* szFilePath) - { - for (const char* p = szFilePath + (int)strlen(szFilePath) - 1; p >= szFilePath; --p) - { - if (*p == '\\' || *p == '/') - { - return p + 1; - } - } - return szFilePath; - } - - // works like strstr, but is case-insensitive - /*! - \param szString the source string - \param szSubstring the sub-string to look for - */ - inline const char* stristr(const char* szString, const char* szSubstring) - { - int nSuperstringLength = (int)strlen(szString); - int nSubstringLength = (int)strlen(szSubstring); - - for (int nSubstringPos = 0; nSubstringPos <= nSuperstringLength - nSubstringLength; ++nSubstringPos) - { - if (_strnicmp(szString + nSubstringPos, szSubstring, nSubstringLength) == 0) - { - return szString + nSubstringPos; - } - } - return nullptr; - } - - -#ifndef NOT_USE_CRY_STRING - - /* - \param strPath the path to "unify" - */ - inline void UnifyFilePath(stack_string& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - - template - inline void UnifyFilePath(CryStackStringT& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - - /// Replaces backslashes with forward slashes and transforms string to lowercase. - /*! - \param strPath the path to "unify" - */ - inline void UnifyFilePath(string& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - -#endif - - // converts the number to a string - /* - \param nNumber an unsigned number - \return the unsigned number as a string - */ - inline string ToString(unsigned nNumber) - { - char szNumber[16]; - sprintf_s(szNumber, "%u", nNumber); - return szNumber; - } - - /// Converts the number to a string. - /*! - \param nNumber an signed integer - \return the signed integer as a string - */ - inline string ToString(signed int nNumber) - { - char szNumber[16]; - sprintf_s(szNumber, "%d", nNumber); - return szNumber; - } - - /// Converts the floating point number to a string. - /*! - \param nNumber a floating point number - \return the floating point number as a string - */ - inline string ToString(float nNumber) - { - char szNumber[128]; - sprintf_s(szNumber, "%f", nNumber); - return szNumber; - } - - /// Converts the boolean value to a string ("0" or "1"). - /*! - \param nNumber an unsigned number - \return the bool as a string (either "1" or "0") - */ - inline string ToString(bool nNumber) - { - char szNumber[4]; - sprintf_s(szNumber, "%i", (int)nNumber); - return szNumber; - } - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_MATRIX44_H - /// Converts a Matrix44 to a string. - /*! - \param m A matrix of type Matrix44 - \return the matrix in the format {0,0,0,0}{0,0,0,0}{0,0,0,0}{0,0,0,0} - */ - inline string ToString(const Matrix44& m) - { - char szBuf[0x200]; - sprintf_s(szBuf, "{%g,%g,%g,%g}{%g,%g,%g,%g}{%g,%g,%g,%g}{%g,%g,%g,%g}", - m(0, 0), m(0, 1), m(0, 2), m(0, 3), - m(1, 0), m(1, 1), m(1, 2), m(1, 3), - m(2, 0), m(2, 1), m(2, 2), m(2, 3), - m(3, 0), m(3, 1), m(3, 2), m(3, 3)); - return szBuf; - } -#endif - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_QUAT_H - /// Converts a CryQuat to a string. - /*! - \param m A quaternion of type CryQuat - \return the quaternion in the format {0,{0,0,0,0}} - */ - inline string ToString (const CryQuat& q) - { - char szBuf[0x100]; - sprintf_s(szBuf, "{%g,{%g,%g,%g}}", q.w, q.v.x, q.v.y, q.v.z); - return szBuf; - } -#endif - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_VECTOR3_H - /// Converts a Vec3 to a string. - /*! - \param m A vector of type Vec3 - \return the vector in the format {0,0,0} - */ - inline string ToString (const Vec3& v) - { - char szBuf[0x80]; - sprintf_s(szBuf, "{%g,%g,%g}", v.x, v.y, v.z); - return szBuf; - } -#endif - - /// This function only exists to allow ToString to compile if it is ever used with an unsupported type. - /*! - \param unknownType - \return a string that reads "unknown" - */ - template - inline string ToString(T& unknownType) - { - char szValue[8]; - sprintf_s(szValue, "%s", "unknown"); - return szValue; - } - - // does the same as strstr, but the szString is allowed to be no more than the specified size - /*! - \param szString the source string - \param szSubstring the sub-string to look for - \param nSuperstringLength the maximum size of szString - */ - inline const char* strnstr(const char* szString, const char* szSubstring, int nSuperstringLength) - { - int nSubstringLength = (int)strlen(szSubstring); - if (!nSubstringLength) - { - return szString; - } - - for (int nSubstringPos = 0; szString[nSubstringPos] && nSubstringPos < nSuperstringLength - nSubstringLength; ++nSubstringPos) - { - if (strncmp(szString + nSubstringPos, szSubstring, nSubstringLength) == 0) - { - return szString + nSubstringPos; - } - } - return nullptr; - } - - - // Finds the string in the array of strings. - // Returns its 0-based index or -1 if not found. - // Comparison is case-sensitive. - // The string array end is demarked by the NULL value. - // This function is Unicode agnostic (but no Unicode collation is performed for equality test) and locale agnostic. - inline int findString(const char* szString, const char* arrStringList[]) - { - for (const char** p = arrStringList; *p; ++p) - { - if (0 == strcmp(*p, szString)) - { - return (int)(p - arrStringList); - } - } - return -1; // string was not found - } - - /// Finds the string in the array of strings. - /*! - \param szString the string to look for - \param arrStringList array of strings - \remark comparison is case-sensitive - \remark The string array end is delimited by the nullptr value - \return its 0-based index or -1 if not found - */ - inline int FindString(const char* szString, const char* arrStringList[]) - { - for (const char** p = arrStringList; *p; ++p) - { - if (0 == strcmp(*p, szString)) - { - return (int)(p - arrStringList); - } - } - return -1; // string was not found - } - - /// Used for printing out sets of objects of string type. - /*! - \remark just forms the comma-delimited string where each string in the set is presented as a formatted substring - \param setStrings set of strings to print - \return a formatted string - */ - inline string ToString(const std::set& setStrings) - { - string strResult; - if (!setStrings.empty()) - { - strResult += "{"; - for (std::set::const_iterator it = setStrings.begin(); it != setStrings.end(); ++it) - { - if (it != setStrings.begin()) - { - strResult += ", "; - } - strResult += "\""; - strResult += *it; - strResult += "\""; - } - strResult += "}"; - } - return strResult; - } - - // Cuts the string and adds leading ... if it's longer than specified maximum length. - // This function is ASCII-only and locale agnostic. - inline string cutString(const string& strPath, unsigned nMaxLength) - { - if (strPath.length() > nMaxLength && nMaxLength > 3) - { - return string("...") + string(strPath.c_str() + strPath.length() - (nMaxLength - 3)); - } - else - { - return strPath; - } - } - - /// Cuts the string and adds leading ... if it's longer than specified maximum length. - /*! - \param str the string to cut - \param nMaxLength the allowed length of the string before its cut. - \return a shortened string starting in ellipses or the source string if it's smaller than nMaxLength - */ - inline string CutString(const string& str, unsigned nMaxLength) - { - if (str.length() > nMaxLength && nMaxLength > 3) - { - return string("...") + string(str.c_str() + str.length() - (nMaxLength - 3)); - } - else - { - return str; - } - } - - /// Converts the given set of NUMBERS into the string. - /*! - \param setMtlms A numeric set to convert into a string - \param szFormat - \param szPostfix - */ - template - string ToString(const std::set& setMtls, const char* szFormat, const char* szPostfix = "") - { - string strResult; - char szBuffer[64]; - if (!setMtls.empty()) - { - strResult += strResult.empty() ? "(" : " ("; - for (typename std::set::const_iterator it = setMtls.begin(); it != setMtls.end(); ) - { - if (it != setMtls.begin()) - { - strResult += ", "; - } - sprintf_s(szBuffer, szFormat, *it); - strResult += szBuffer; - T nStart = *it; - - ++it; - - if (it != setMtls.end() && *it == nStart + 1) - { - T nPrev = *it; - // we've got a region - while (++it != setMtls.end() && *it == nPrev + 1) - { - nPrev = *it; - } - if (nPrev == nStart + 1) - { - // special case - range of length 1 - strResult += ","; - } - else - { - strResult += ".."; - } - sprintf_s(szBuffer, szFormat, nPrev); - strResult += szBuffer; - } - } - strResult += ")"; - } - return szPostfix[0] ? strResult + szPostfix : strResult; - } - - - // Attempts to find a matching wildcard in a string. - /*! - \param szString source string - \param szWildcard the wildcard, supports * and ? - // returns true if the string matches the wildcard - // Note: ANSI input is not supported, ASCII is fine since it's a subset of UTF-8. - */ - inline bool MatchWildcard(const char* szString, const char* szWildcard) - { - return CryStringUtils_Internal::MatchesWildcards_Tpl(szString, szWildcard); - } - - // Returns true if the string matches the wildcard. - // Supports wildcard ? (matches one code-point) and * (matches zero or more code-points). - // This function is Unicode aware and uses the "C" locale for case comparison. - // Note: ANSI input is not supported, ASCII is fine since it's a subset of UTF-8. - inline bool MatchWildcardIgnoreCase(const char* szString, const char* szWildcard) - { - return CryStringUtils_Internal::MatchesWildcards_Tpl(szString, szWildcard); - } - -#if !defined(RESOURCE_COMPILER) - - // calculates a hash value for a given string - inline uint32 CalculateHash(const char* str) - { - return CCrc32::Compute(str); - } - - // calculates a hash value for the lower case version of a given string - inline uint32 CalculateHashLowerCase(const char* str) - { - return CCrc32::ComputeLowercase(str); - } - - // This function is Unicode agnostic and locale agnostic. - inline uint32 HashStringSeed(const char* string, const uint32 seed) - { - // A string hash taken from the FRD/Crysis2 (game) code with low probability of clashes - // Recommend you use the CRY_DEFAULT_HASH_SEED (see HashString) - const char* p; - uint32 hash = seed; - for (p = string; *p != '\0'; p++) - { - hash += *p; - hash += (hash << 10); - hash ^= (hash >> 6); - } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - return hash; - } - - // This function is ASCII-only and uses the standard "C" locale for case conversion. - inline uint32 HashStringLowerSeed(const char* string, const uint32 seed) - { - // computes the hash of 'string' converted to lower case - // also see the comment in HashStringSeed - const char* p; - uint32 hash = seed; - for (p = string; *p != '\0'; p++) - { - hash += toLowerAscii(*p); - hash += (hash << 10); - hash ^= (hash >> 6); - } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - return hash; - } - - // This function is Unicode agnostic and locale agnostic. - inline uint32 HashString(const char* string) - { - return HashStringSeed(string, CRY_DEFAULT_HASH_SEED); - } - - // This function is ASCII-only and uses the standard "C" locale for case conversion. - inline uint32 HashStringLower(const char* string) - { - return HashStringLowerSeed(string, CRY_DEFAULT_HASH_SEED); - } -#endif - - // converts all chars to lower case - avoids memory allocation - /*! - \param str Reference to string to convert into lowercase. - */ - inline void ToLowerInplace(string& str) - { -#ifndef NOT_USE_CRY_STRING - str.MakeLower(); -#else - std::transform(str.begin(), str.end(), str.begin(), toLowerAscii); // STL MakeLower -#endif - } - - /// Converts all chars to lower case - avoids memory allocation - /*! - \param str Reference to string to convert into lowercase. - */ - inline void ToLowerInplace(char* str) - { - if (str == nullptr) - { - return; - } - - for (char* s = str; *s != '\0'; s++) - { - *s = toLowerAscii(*s); - } - } - - -#ifndef NOT_USE_CRY_STRING - - // Converts a wide string (can be UTF-16 or UTF-32 depending on platform) to UTF-8. - // This function is Unicode aware and locale agnostic. - /// Converts a wide string to a UTF8 string. - /*! - \param str The wide string to convert. - \return dstr The wide string converted into the specified UTF8 type. - */ - template - inline void WStrToUTF8(const wchar_t* str, T& dstr) - { - string utf8; - Unicode::Convert(utf8, str); - - // Note: This function expects T to have assign(ptr, len) function - dstr.assign(utf8.c_str(), utf8.length()); - } - - // Converts a wide string (can be UTF-16 or UTF-32 depending on platform) to UTF-8. - // This function is Unicode aware and locale agnostic. - /// Converts a wide string to UTF8. - /*! - \param str The wchar_t string to convert. - \return The UTF8 string. - */ - inline string WStrToUTF8(const wchar_t* str) - { - return Unicode::Convert(str); - } - - /// Converts a UTF8 string to a wide string. - /*! - \param str The UTF8 string to convert. - \return dstr The UTF8 string converted into the specified type. - */ - template - inline void UTF8ToWStr(const char* str, T& dstr) - { - wstring wide; - Unicode::Convert(wide, str); - - // Note: This function expects T to have assign(ptr, len) function - dstr.assign(wide.c_str(), wide.length()); - } - - // Converts an UTF-8 string to wide string (can be UTF-16 or UTF-32 depending on platform). - // This function is Unicode aware and locale agnostic. - /*! - \param str The UTF8 string to convert. - \return str as converted to wstring. - */ - inline wstring UTF8ToWStr(const char* str) - { - return Unicode::Convert(str); - } - - /// Converts a string to a wide character string - /*! - \param str Source string. - \param dstr Destination wstring. - */ - inline void StrToWstr(const char* str, wstring& dstr) - { - CryStackStringT tmp; - tmp.resize(strlen(str)); - tmp.clear(); - - while (const wchar_t c = (wchar_t)(*str++)) - { - tmp.append(1, c); - } - - dstr.assign(tmp.data(), tmp.length()); - } - -#endif // NOT_USE_CRY_STRING - - /// The type used to parse a yes/no string -#if defined(_DISALLOW_ENUM_CLASS) - enum YesNoType -#else - enum class YesNoType -#endif - { - Yes, - No, - Invalid - }; - - // parse the yes/no string - /*! - \param szString any of the following strings: yes, enable, true, 1, no, disable, false, 0 - \return YesNoType::Yes if szString is yes/enable/true/1, YesNoType::No if szString is no, disable, false, 0 and YesNoType::Invalid if the string is not one of the expected values. - */ - inline YesNoType ToYesNoType(const char* szString) - { - if (!_stricmp(szString, "yes") - || !_stricmp(szString, "enable") - || !_stricmp(szString, "true") - || !_stricmp(szString, "1")) -#if defined(_DISALLOW_ENUM_CLASS) - { - return Yes; - } -#else - { - return YesNoType::Yes; - } -#endif - if (!_stricmp(szString, "no") - || !_stricmp(szString, "disable") - || !_stricmp(szString, "false") - || !_stricmp(szString, "0")) -#if defined(_DISALLOW_ENUM_CLASS) - { - return No; - } -#else - { - return YesNoType::No; - } -#endif - -#if defined(_DISALLOW_ENUM_CLASS) - return Invalid; -#else - return YesNoType::Invalid; -#endif - } - - /// Verifies if the filename provided only contains the accepted characters. - /*! - \param fileName the filename to verify - \return true if the filename only contains alphanumeric values and/or dot, dash and underscores. - */ - inline bool IsValidFileName(const char* fileName) - { - size_t i = 0; - for (;; ) - { - const char c = fileName[i++]; - if (c == 0) - { - return true; - } - if (!((c >= '0' && c <= '9') - || (c >= 'A' && c <= 'Z') - || (c >= 'a' && c <= 'z') - || c == '.' || c == '-' || c == '_')) - { - return false; - } - } - } - - - /************************************************************************** - *void _makepath() - build path name from components - * - *Purpose: - * create a path name from its individual components - * - *Entry: - * char *path - pointer to buffer for constructed path - * char *drive - pointer to drive component, may or may not contain trailing ':' - * char *dir - pointer to subdirectory component, may or may not include leading and/or trailing '/' or '\' characters - * char *fname - pointer to file base name component - * char *ext - pointer to extension component, may or may not contain a leading '.'. - * - *Exit: - * path - pointer to constructed path name - * - *******************************************************************************/ - ILINE void portable_makepath(char path[_MAX_PATH], const char* drive, const char* dir, const char* fname, const char* ext) - { - const char* p; - - /* we assume that the arguments are in the following form (although we - * do not diagnose invalid arguments or illegal filenames (such as - * names longer than 8.3 or with illegal characters in them) - * - * drive: - * A ; or - * A: - * dir: - * \top\next\last\ ; or - * /top/next/last/ ; or - * either of the above forms with either/both the leading - * and trailing / or \ removed. Mixed use of '/' and '\' is - * also tolerated - * fname: - * any valid file name - * ext: - * any valid extension (none if empty or null ) - */ - - /* copy drive */ - - if (drive && *drive) - { - *path++ = *drive; - *path++ = (':'); - } - - /* copy dir */ - - if ((p = dir) && *p) - { - do - { - *path++ = *p++; - } while (*p); - if (*(p - 1) != '/' && *(p - 1) != ('\\')) - { - *path++ = ('\\'); - } - } - - /* copy fname */ - - if (p = fname) - { - while (*p) - { - *path++ = *p++; - } - } - - /* copy ext, including 0-terminator - check to see if a '.' needs - * to be inserted. - */ - - if (p = ext) - { - if (*p && *p != ('.')) - { - *path++ = ('.'); - } - while (*path++ = *p++) - { - ; - } - } - else - { - /* better add the 0-terminator */ - *path = ('\0'); - } - } - - /// Create a path name from its individual components. - /*! - \param char *path pointer to buffer for constructed path - \param char *drive pointer to drive component, may or may not contain trailing ':' - \param char *dir pointer to subdirectory component, may or may not include leading and/or trailing '/' or '\' characters - \param char *fname pointer to file base name component - \param char *ext pointer to extension component, may or may not contain a leading '.'. - \return path pointer to constructed path name - */ - inline void MakePath(char path[_MAX_PATH], const char* drive, const char* dir, const char* fname, const char* ext) - { - const char* p; - - // we assume that the arguments are in the following form (although we - // do not diagnose invalid arguments or illegal filenames (such as - // names longer than 8.3 or with illegal characters in them) - // - // drive: - // A ; or - // A: - // dir: - // \top\next\last\ ; or - // /top/next/last/ ; or - // either of the above forms with either/both the leading - // and trailing / or \ removed. Mixed use of '/' and '\' is - // also tolerated - // fname: - // any valid file name - // ext: - // any valid extension (none if empty or null ) - // - - // copy drive - if (drive && *drive) - { - *path++ = *drive; - *path++ = (':'); - } - - // copy dir - if ((p = dir) && *p) - { - do - { - *path++ = *p++; - } while (*p); - if (*(p - 1) != '/' && *(p - 1) != ('\\')) - { - *path++ = ('\\'); - } - } - - // copy fname - if (p = fname) - { - while (*p) - { - *path++ = *p++; - } - } - - // copy ext, including 0-terminator - check to see if a '.' needs - // to be inserted. - if (p = ext) - { - if (*p && *p != ('.')) - { - *path++ = ('.'); - } - while (*path++ = *p++) - { - ; - } - } - else - { - // better add the 0-terminator - *path = ('\0'); - } - } - - // Copies characters from a string. - /*! - \param destination Pointer to the destination array where the content is to be copied. - \param source C string to be copied. - \param num Maximum number of characters to be copied from source. - \remark Parameter order is the same as strncpy; Copies only up to num characters from source to destination. - \return true if entirety of source was copied into destination. - */ - inline bool strncpy(char* destination, const char* source, size_t num) - { - bool reply = false; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (num) - { - size_t i; - for (i = 0; source[i] && (i + 1) < num; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == '\0'); - } - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT_MESSAGE(reply, string().Format("String '%s' is too big to fit into a buffer of length %u", source, (unsigned int)num)); -#endif - return reply; - } - - // Copies wide characters from a wide string. - /*! - \param destination Pointer to the destination wchar_t array where the content is to be copied. - \param source C wide string to be copied. - \param num Maximum number of characters to be copied from source. - \remark Parameter order is the same as strncpy; Copies only up to num characters from source to destination. - \return true if entirety of source was copied into destination. - */ - inline bool wstrncpy(wchar_t* destination, const wchar_t* source, size_t bufferLength) - { - bool reply = false; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (bufferLength) - { - size_t i; - for (i = 0; source[i] && (i + 1) < bufferLength; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == '\0'); - } - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT_MESSAGE(reply, string().Format("String '%ls' is too big to fit into a buffer of length %u", source, (unsigned int)bufferLength)); -#endif - return reply; - } - - // Copies a C string into a destination buffer up to a specified delimiter or null terminator. - /*! - \param destination Pointer to a buffer where the resulting C-string is stored. - \param source C string to be copied. - \param num Maximum number of characters to be copied from source. - \param delimiter Delimiter character up to which the string will be copied. - \return Number of bytes written into destination (including null terminator) or 0 if delimiter is not found within the first num bytes of source. - */ - inline size_t CopyStringUntilFindChar(char* destination, const char* source, size_t num, char delimiter) - { - size_t reply = 0; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (num) - { - size_t i; - for (i = 0; source[i] && source[i] != delimiter && (i + 1) < num; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == delimiter) ? (i + 1) : 0; - } - - return reply; - } -} // namespace CryStringUtils - -#endif // CRYINCLUDE_CRYCOMMON_STRINGUTILS_H diff --git a/Code/Legacy/CryCommon/TypeInfo_decl.h b/Code/Legacy/CryCommon/TypeInfo_decl.h index f763ec6ebb..28a0b370a9 100644 --- a/Code/Legacy/CryCommon/TypeInfo_decl.h +++ b/Code/Legacy/CryCommon/TypeInfo_decl.h @@ -15,6 +15,7 @@ #pragma once #include +#include ////////////////////////////////////////////////////////////////////////// // Meta-type support. @@ -55,7 +56,7 @@ inline const CTypeInfo& TypeInfo(const T* t) // Type info declaration, with additional prototypes for string conversions. #define BASIC_TYPE_INFO(Type) \ - string ToString(Type const & val); \ + AZStd::string ToString(Type const & val); \ bool FromString(Type & val, const char* s); \ DECLARE_TYPE_INFO(Type) @@ -105,7 +106,7 @@ BASIC_TYPE_INFO(double) BASIC_TYPE_INFO(AZ::Uuid) -DECLARE_TYPE_INFO(string) +DECLARE_TYPE_INFO(AZStd::string) // All pointers share same TypeInfo. const CTypeInfo&PtrTypeInfo(); diff --git a/Code/Legacy/CryCommon/UnicodeBinding.h b/Code/Legacy/CryCommon/UnicodeBinding.h index 6bfa846035..aaefcf0f55 100644 --- a/Code/Legacy/CryCommon/UnicodeBinding.h +++ b/Code/Legacy/CryCommon/UnicodeBinding.h @@ -12,7 +12,6 @@ // // (At least) the following string types can be bound with these helper functions: // Types Input Output Null-Terminator -// CryStringT, (::string, ::wstring): yes yes implied by type (also Stack and Fixed variants) // std::basic_string, std::string, std::wstring: yes yes implied by type // QString: yes yes implied by type // std::vector, std::list, std::deque: yes yes not present @@ -56,18 +55,14 @@ // Forward declare the supported types. // Before actually instantiating a binding however, you need to have the full definition included. // Also, this allows us to work with QChar/QString as declared names without a dependency on Qt. -template -class CryStackStringT; -template -class CryFixedStringT; -template -class CryFixedWStringT; -template -class CryStringLocalT; -template -class CryStringT; +namespace AZStd +{ + template + class basic_fixed_string; +} class QChar; class QString; + namespace Unicode { namespace Detail @@ -253,36 +248,15 @@ namespace Unicode static const bool isValid = SValidChar::value; static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; template - struct SBindObject, InferEncoding> + struct SBindObject, InferEncoding> { typedef typename add_const::type CharType; static const bool isValid = SValidChar::value; static const EBind value = isValid ? eBind_Data : eBind_Impossible; }; template - struct SBindObject, InferEncoding> - { - typedef char CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> + struct SBindObject, InferEncoding> { typedef wchar_t CharType; static const bool isValid = SValidChar::value; @@ -348,22 +322,8 @@ namespace Unicode static const bool isValid = SValidChar::value; static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; template - struct SBindOutput, InferEncoding> + struct SBindOutput, InferEncoding> { typedef T CharType; static const bool isValid = SValidChar::value; diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 3208da9d68..a60dbdf00b 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -486,7 +486,7 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext drv[0] = 0; } - typedef CryStackStringT path_stack_string; + typedef AZStd::fixed_string path_stack_string; const path_stack_string inPath(inpath); string::size_type s = inPath.rfind('/', inPath.size());//position of last / diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index 0392f11c89..63c5b49513 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -78,7 +78,6 @@ set(FILES CryCrc32.h CryCustomTypes.h CryFile.h - CryFixedString.h CryHeaders.h CryHeaders_info.cpp CryListenerSet.h @@ -87,7 +86,6 @@ set(FILES CryPath.h CryPodArray.h CrySizer.h - CryString.h CrySystemBus.h CryThread.h CryThreadImpl.h @@ -111,7 +109,6 @@ set(FILES SimpleSerialize.h smartptr.h StlUtils.h - StringUtils.h Synchronization.h Tarray.h Timer.h diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index b3846b88dd..60edf10de9 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -689,9 +689,6 @@ void SetFlags(T& dest, U flags, bool b) #include AZ_RESTRICTED_FILE(platform_h) #endif -// Platform wrappers must be included before CryString.h -# include "CryString.h" - // Include support for meta-type data. #include "TypeInfo_decl.h" @@ -701,12 +698,6 @@ void SetFlags(T& dest, U flags, bool b) bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes); threadID CryGetCurrentThreadId(); -#if !defined(NOT_USE_CRY_STRING) -// Fixed-Sized (stack based string) -// put after the platform wrappers because of missing wcsicmp/wcsnicmp functions - #include "CryFixedString.h" -#endif - // need this in a common header file and any other file would be too misleading enum ETriState { diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index a677ba30b6..6ec8df0365 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -8,7 +8,6 @@ #include -#include #include #include #include @@ -248,10 +247,7 @@ int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const ch return 0; } #endif - wstring wideText, wideCaption; - Unicode::Convert(wideText, lpText); - Unicode::Convert(wideCaption, lpCaption); - return MessageBoxW(NULL, wideText.c_str(), wideCaption.c_str(), uType); + return MessageBox(NULL, lpText, lpCaption, uType); #else return 0; #endif diff --git a/Code/Legacy/CrySystem/CmdLine.cpp b/Code/Legacy/CrySystem/CmdLine.cpp index cb805b6990..50b8b2c092 100644 --- a/Code/Legacy/CrySystem/CmdLine.cpp +++ b/Code/Legacy/CrySystem/CmdLine.cpp @@ -11,7 +11,7 @@ #include "CmdLine.h" -void CCmdLine::PushCommand(const string& sCommand, const string& sParameter) +void CCmdLine::PushCommand(const AZStd::string& sCommand, const AZStd::string& sParameter) { if (sCommand.empty()) { @@ -47,7 +47,7 @@ CCmdLine::CCmdLine(const char* commandLine) char* src = (char*)commandLine; - string command, parameter; + AZStd::string command, parameter; for (;; ) { @@ -56,12 +56,12 @@ CCmdLine::CCmdLine(const char* commandLine) break; } - string arg = Next(src); + AZStd::string arg = Next(src); if (m_args.empty()) { // this is the filename, convert backslash to forward slash - arg.replace('\\', '/'); + AZ::StringFunc::Replace(arg, '\\', '/'); m_args.push_back(CCmdLineArg("filename", arg.c_str(), eCLAT_Executable)); } else @@ -90,7 +90,7 @@ CCmdLine::CCmdLine(const char* commandLine) } else { - parameter += string(" ") + arg; + parameter += AZStd::string(" ") + arg; } } } @@ -151,7 +151,7 @@ const ICmdLineArg* CCmdLine::FindArg(const ECmdLineArgType ArgType, const char* } -string CCmdLine::Next(char*& src) +AZStd::string CCmdLine::Next(char*& src) { char ch = 0; char* org = src; @@ -170,7 +170,7 @@ string CCmdLine::Next(char*& src) ; } - return string(org, src - 1); + return AZStd::string(org, src - 1); case '[': org = src; @@ -178,7 +178,7 @@ string CCmdLine::Next(char*& src) { ; } - return string(org, src - 1); + return AZStd::string(org, src - 1); case ' ': ch = *src++; @@ -190,12 +190,12 @@ string CCmdLine::Next(char*& src) ; } - return string(org, src); + return AZStd::string(org, src); } ch = *src++; } - return string(); + return AZStd::string(); } diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp index 576c3ee9fb..1914e82515 100644 --- a/Code/Legacy/CrySystem/DebugCallStack.cpp +++ b/Code/Legacy/CrySystem/DebugCallStack.cpp @@ -430,18 +430,18 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) { const char* const szMessage = m_bIsFatalError ? s_szFatalErrorCode : m_szBugMessage; excName = szMessage; - cry_strcpy(excCode, szMessage); - cry_strcpy(excAddr, ""); - cry_strcpy(desc, ""); - cry_strcpy(m_excModule, ""); - cry_strcpy(excDesc, szMessage); + azstrcpy(excCode, szMessage); + azstrcpy(excAddr, ""); + azstrcpy(desc, ""); + azstrcpy(m_excModule, ""); + azstrcpy(excDesc, szMessage); } else { sprintf_s(excAddr, "0x%04X:0x%p", pex->ContextRecord->SegCs, pex->ExceptionRecord->ExceptionAddress); sprintf_s(excCode, "0x%08X", pex->ExceptionRecord->ExceptionCode); excName = TranslateExceptionCode(pex->ExceptionRecord->ExceptionCode); - cry_strcpy(desc, ""); + azstrcpy(desc, ""); sprintf_s(excDesc, "%s\r\n%s", excName, desc); @@ -471,9 +471,9 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) WriteLineToLog("Exception Description: %s", desc); - cry_strcpy(m_excDesc, excDesc); - cry_strcpy(m_excAddr, excAddr); - cry_strcpy(m_excCode, excCode); + azstrcpy(m_excDesc, excDesc); + azstrcpy(m_excAddr, excAddr); + azstrcpy(m_excCode, excCode); char errs[32768]; @@ -499,7 +499,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) dumpCallStack(funcs); // Fill call stack. char str[s_iCallStackSize]; - cry_strcpy(str, ""); + azstrcpy(str, ""); for (unsigned int i = 0; i < funcs.size(); i++) { char temp[s_iCallStackSize]; @@ -509,7 +509,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) cry_strcat(errs, temp); cry_strcat(errs, "\n"); } - cry_strcpy(m_excCallstack, str); + azstrcpy(m_excCallstack, str); } cry_strcat(errorString, errs); diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index e8cc4d484c..83db5e4a29 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -567,7 +567,7 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) INDENT_LOG_DURING_SCOPE(); char levelName[256]; - cry_strcpy(levelName, _levelName); + azstrcpy(levelName, _levelName); // Not remove a scope!!! { diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp index ce39f08480..fe0fd9cb22 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp +++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp @@ -528,7 +528,7 @@ static void CopyLowercase(char* dst, size_t dstSize, const char* src, size_t src } ////////////////////////////////////////////////////////////////////////// -static void ReplaceEndOfLine(CryFixedStringT& s) +static void ReplaceEndOfLine(AZStd::fixed_string& s) { const string oldSubstr("\\n"); const string newSubstr(" \n"); @@ -536,7 +536,7 @@ static void ReplaceEndOfLine(CryFixedStringT::npos) + if (pos == AZStd::fixed_string::npos) { return; } @@ -955,7 +955,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName, bool bFirstRow = true; - CryFixedStringT sTmp; + AZStd::fixed_string sTmp; // lower case event name char szLowerCaseEvent[128]; @@ -1609,7 +1609,7 @@ bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8 { continue; } - AzFramework::StringFunc::Replace(textValue, "\\n", " \n"); // carried over from helper func ReplaceEndOfLine(CryFixedStringT<>& s) + AzFramework::StringFunc::Replace(textValue, "\\n", " \n"); if (keyString[0] == '@') { AzFramework::StringFunc::LChop(keyString, 1); @@ -2536,7 +2536,7 @@ void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberStrin int n = abs(number); string separator; - CryFixedStringT<64> tmp; + AZStd::fixed_string<64> tmp; LocalizeString_ch("@ui_thousand_separator", separator); while (n > 0) { @@ -2565,7 +2565,7 @@ void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals { if (number == 0.0f) { - CryFixedStringT<64> tmp; + AZStd::fixed_string<64> tmp; tmp.Format("%.*f", decimals, number); outNumberString.assign(tmp.c_str()); return; @@ -2585,7 +2585,7 @@ void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals int decimalsAsInt = aznumeric_cast(int_round(decimalsOnly * pow(10.0f, decimals))); - CryFixedStringT<64> tmp; + AZStd::fixed_string<64> tmp; tmp.Format("%s%s%0*d", intPart.c_str(), commaSeparator.c_str(), decimals, decimalsAsInt); outNumberString.assign(tmp.c_str()); @@ -2657,7 +2657,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool if (len > 0) { // len includes terminating null! - CryFixedWStringT<256> tmpString; + AZStd::fixed_wstring<256> tmpString; tmpString.resize(len); ::GetTimeFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len); Unicode::Convert(outTimeString, tmpString); @@ -2678,7 +2678,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool UnixTimeToSystemTime(t, &systemTime); // len includes terminating null! - CryFixedWStringT<256> tmpString; + AZStd::fixed_wstring<256> tmpString; if (bIncludeWeekday) { diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index d2d8495063..2c7c307d50 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -509,7 +509,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo stack_string s = szBuffer; s += "\t "; s += sAssetScope; - cry_strcpy(szBuffer, s.c_str()); + azstrcpy(szBuffer, s.c_str()); } } @@ -863,7 +863,7 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL { // When logging from other thread then main, push all log strings to queue. SLogMsg msg; - cry_strcpy(msg.msg, szString); + azstrcpy(msg.msg, szString); msg.bAdd = bAdd; msg.destination = destination; msg.logType = logType; @@ -1286,7 +1286,7 @@ void CLog::CreateBackupFile() const string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt); fileSystem->CreatePath(LOG_BACKUP_PATH); - cry_strcpy(m_sBackupFilename, bakdest.c_str()); + azstrcpy(m_sBackupFilename, bakdest.c_str()); // Remove any existing backup file with the same name first since the copy will fail otherwise. fileSystem->Remove(m_sBackupFilename); fileSystem->Copy(m_szFilename, bakdest); diff --git a/Code/Legacy/CrySystem/Log.h b/Code/Legacy/CrySystem/Log.h index 5b1956b12f..3c0fa98037 100644 --- a/Code/Legacy/CrySystem/Log.h +++ b/Code/Legacy/CrySystem/Log.h @@ -37,7 +37,7 @@ class CLog { public: typedef std::list Callbacks; - typedef CryStackStringT LogStringType; + typedef AZStd::fixed_string LogStringType; // constructor CLog(ISystem* pSystem); diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp index 7fa7f7d2b0..bf4de8489d 100644 --- a/Code/Legacy/CrySystem/System.cpp +++ b/Code/Legacy/CrySystem/System.cpp @@ -1190,7 +1190,7 @@ void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int if (file && *file) { - CryFixedStringT fmt = szBuffer; + AZStd::fixed_string fmt = szBuffer; fmt += " [File="; fmt += file; fmt += "]"; diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index 2cc41adc08..943a540ae6 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -127,7 +127,7 @@ const char* CSystem::GetUserName() DWORD dwSize = iNameBufferSize; wchar_t nameW[iNameBufferSize]; ::GetUserNameW(nameW, &dwSize); - cry_strcpy(szNameBuffer, CryStringUtils::WStrToUTF8(nameW)); + azstrcpy(szNameBuffer, CryStringUtils::WStrToUTF8(nameW)); return szNameBuffer; #else #if defined(LINUX) @@ -283,7 +283,7 @@ static const char* GetLastSystemErrorMessage() 0, NULL)) { - cry_strcpy(szBuffer, (char*)lpMsgBuf); + azstrcpy(szBuffer, (char*)lpMsgBuf); LocalFree(lpMsgBuf); } else @@ -505,7 +505,9 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize) if (bSucceeded) { // Convert from UNICODE to UTF-8 - cry_strcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath)); + AZStd::string str; + AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath)); + azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str()); CoTaskMemFree(wMyDocumentsPath); } } @@ -519,7 +521,9 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize) bSucceeded = SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, wMyDocumentsPath)); if (bSucceeded) { - cry_strcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath)); + AZStd::string str; + AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath)); + azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str()); } } diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index 09b3182c04..a69d86e8b7 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -1554,7 +1554,7 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags) // hiding this makes it a bit more difficult for cheaters // if(dwFlags&VF_CHEAT) cry_strcat( sFlags,"CHEAT, "); - cry_strcpy(sFlags, ""); + azstrcpy(sFlags, ""); if (dwFlags & VF_READONLY) { diff --git a/Code/Legacy/CrySystem/XConsole.h b/Code/Legacy/CrySystem/XConsole.h index eca52771dd..f09c8e5ad7 100644 --- a/Code/Legacy/CrySystem/XConsole.h +++ b/Code/Legacy/CrySystem/XConsole.h @@ -42,11 +42,11 @@ enum ScrollDir ////////////////////////////////////////////////////////////////////////// struct CConsoleCommand { - string m_sName; // Console command name - string m_sCommand; // lua code that is executed when this command is invoked - string m_sHelp; // optional help string - can be shown in the console with " ?" - int m_nFlags; // bitmask consist of flag starting with VF_ e.g. VF_CHEAT - ConsoleCommandFunc m_func; // Pointer to console command. + AZStd::string m_sName; // Console command name + AZStd::string m_sCommand; // lua code that is executed when this command is invoked + AZStd::string m_sHelp; // optional help string - can be shown in the console with " ?" + int m_nFlags; // bitmask consist of flag starting with VF_ e.g. VF_CHEAT + ConsoleCommandFunc m_func; // Pointer to console command. ////////////////////////////////////////////////////////////////////////// CConsoleCommand() @@ -67,7 +67,7 @@ struct CConsoleCommand struct CConsoleCommandArgs : public IConsoleCmdArgs { - CConsoleCommandArgs(string& line, std::vector& args) + CConsoleCommandArgs(AZStd::string& line, std::vector& args) : m_line(line) , m_args(args) {}; virtual int GetArgCount() const { return m_args.size(); }; @@ -87,8 +87,8 @@ struct CConsoleCommandArgs } private: - std::vector& m_args; - string& m_line; + std::vector& m_args; + AZStd::string& m_line; }; @@ -132,7 +132,7 @@ class CXConsole , public AzFramework::CommandRegistrationBus::Handler { public: - typedef std::deque ConsoleBuffer; + typedef std::deque ConsoleBuffer; typedef ConsoleBuffer::iterator ConsoleBufferItor; typedef ConsoleBuffer::reverse_iterator ConsoleBufferRItor; @@ -262,7 +262,7 @@ protected: // ------------------------------------------------------------------ void AddInputUTF8(const AZStd::string& textUTF8); void RemoveInputChar(bool bBackSpace); void ExecuteInputBuffer(); - void ExecuteCommand(CConsoleCommand& cmd, string& params, bool bIgnoreDevMode = false); + void ExecuteCommand(CConsoleCommand& cmd, AZStd::string& params, bool bIgnoreDevMode = false); void ScrollConsole(); @@ -294,7 +294,7 @@ protected: // ------------------------------------------------------------------ // Arguments: // bFromConsole - true=from console, false=from outside - void SplitCommands(const char* line, std::list& split); + void SplitCommands(const char* line, std::list& split); void ExecuteStringInternal(const char* command, const bool bFromConsole, const bool bSilentMode = false); void ExecuteDeferredCommands(); @@ -320,27 +320,27 @@ private: // ---------------------------------------------------------- void PostLine(const char* lineOfText, size_t len); - typedef std::map ConsoleCommandsMap; + typedef std::map ConsoleCommandsMap; typedef ConsoleCommandsMap::iterator ConsoleCommandsMapItor; - typedef std::map ConsoleBindsMap; + typedef std::map ConsoleBindsMap; typedef ConsoleBindsMap::iterator ConsoleBindsMapItor; - typedef std::map > ArgumentAutoCompleteMap; + typedef std::map > ArgumentAutoCompleteMap; struct SConfigVar { - string m_value; + AZStd::string m_value; bool m_partOfGroup; }; - typedef std::map ConfigVars; + typedef std::map ConfigVars; struct SDeferredCommand { - string command; + AZStd::string command; bool silentMode; - SDeferredCommand(const string& _command, bool _silentMode) + SDeferredCommand(const AZStd::string& _command, bool _silentMode) : command(_command) , silentMode(_silentMode) {} @@ -359,10 +359,10 @@ private: // ---------------------------------------------------------- int m_nProgress; int m_nProgressRange; - string m_sInputBuffer; - string m_sReturnString; + AZStd::string m_sInputBuffer; + AZStd::string m_sReturnString; - string m_sPrevTab; + AZStd::string m_sPrevTab; int m_nTabCount; ConsoleCommandsMap m_mapCommands; // diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp index da4bf66eee..55fab84286 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp @@ -49,7 +49,7 @@ bool CSerializeXMLReaderImpl::Value(const char* name, int8& value) return bResult; } -bool CSerializeXMLReaderImpl::Value(const char* name, string& value) +bool CSerializeXMLReaderImpl::Value(const char* name, AZStd::string& value) { DefaultValue(value); // Set input value to default. if (m_nErrors) @@ -177,7 +177,7 @@ void CSerializeXMLReaderImpl::EndGroup() ////////////////////////////////////////////////////////////////////////// const char* CSerializeXMLReaderImpl::GetStackInfo() const { - static string str; + static AZStd::string str; str.assign(""); for (int i = 0; i < (int)m_nodeStack.size(); i++) { diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h index c0e2059886..177db0ffaa 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h @@ -47,7 +47,7 @@ public: g_pXmlStrCmp = pPrevCmpFunc; return bReturn; } - ILINE bool GetAttr([[maybe_unused]] XmlNodeRef& node, [[maybe_unused]] const char* name, [[maybe_unused]] const string& value) + ILINE bool GetAttr([[maybe_unused]] XmlNodeRef& node, [[maybe_unused]] const char* name, [[maybe_unused]] const AZStd::string& value) { return false; } @@ -75,7 +75,7 @@ public: } bool Value(const char* name, int8& value); - bool Value(const char* name, string& value); + bool Value(const char* name, AZStd::string& value); bool Value(const char* name, CTimeValue& value); bool Value(const char* name, XmlNodeRef& value); @@ -172,8 +172,8 @@ private: void DefaultValue(Quat& v) const { v.w = 1.0f; v.v.x = 0; v.v.y = 0; v.v.z = 0; } void DefaultValue(CTimeValue& v) const { v.SetValue(0); } //void DefaultValue( char *str ) const { if (str) str[0] = 0; } - void DefaultValue(string& str) const { str = ""; } - void DefaultValue([[maybe_unused]] const string& str) const {} + void DefaultValue(AZStd::string& str) const { str = ""; } + void DefaultValue([[maybe_unused]] const AZStd::string& str) const {} void DefaultValue([[maybe_unused]] SNetObjectID& id) const {} void DefaultValue([[maybe_unused]] SSerializeString& str) const {} void DefaultValue(XmlNodeRef& ref) const { ref = NULL; } diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp index bd31fb3ba4..e59f6b8969 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp @@ -32,7 +32,7 @@ const char* XMLBinary::XMLBinaryReader::GetErrorDescription() const void XMLBinary::XMLBinaryReader::SetErrorDescription(const char* text) { - cry_strcpy(m_errorDescription, text); + azstrcpy(m_errorDescription, text); } diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp index 60e0d2e4f1..81994b26e0 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp @@ -84,7 +84,7 @@ static void write(XMLBinary::IDataWriter* const pFile, size_t& nPosition, const } ////////////////////////////////////////////////////////////////////////// -bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, AZStd::string& error) { error = ""; @@ -99,7 +99,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, static const uint nMaxNodeCount = (NodeIndex) ~0; if (m_nodes.size() > nMaxNodeCount) { - error.Format("XMLBinary: Too many nodes: %d (max is %i)", m_nodes.size(), nMaxNodeCount); + error = AZStd::string::format("XMLBinary: Too many nodes: %d (max is %i)", m_nodes.size(), nMaxNodeCount); return false; } @@ -192,7 +192,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, return true; } -bool XMLBinary::CXMLBinaryWriter::CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error) { bool ok = CompileTablesForNode(node, -1, pFilter, error); ok = ok && CompileChildTable(node, pFilter, error); @@ -200,7 +200,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTables(XmlNodeRef node, XMLBinary::IFil } ////////////////////////////////////////////////////////////////////////// -bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, AZStd::string& error) { // Add the tag to the string table. int nTagStringOffset = AddString(node->getTag()); @@ -231,7 +231,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar static const int nMaxAttributeCount = (uint16) ~0; if (nAttributeCount > nMaxAttributeCount) { - error.Format("XMLBinary: Too many attributes in a node: %d (max is %i)", nAttributeCount, nMaxAttributeCount); + error = AZStd::string::format("XMLBinary: Too many attributes in a node: %d (max is %i)", nAttributeCount, nMaxAttributeCount); return false; } @@ -261,7 +261,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar { if (++nChildCount > nMaxChildCount) { - error.Format("XMLBinary: Too many children in node '%s': %d (max is %i)", childNode->getTag(), nChildCount, nMaxChildCount); + error = AZStd::string::format("XMLBinary: Too many children in node '%s': %d (max is %i)", childNode->getTag(), nChildCount, nMaxChildCount); return false; } if (!CompileTablesForNode(childNode, nIndex, pFilter, error)) @@ -277,7 +277,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar } ////////////////////////////////////////////////////////////////////////// -bool XMLBinary::CXMLBinaryWriter::CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error) { const int nIndex = m_nodesMap.find(node)->second; // Assume node always exist in map. const int nFirstChildIndex = (int)m_childs.size(); @@ -298,7 +298,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileChildTable(XmlNodeRef node, XMLBinary:: } if (nChildCount != nd.nChildCount) { - error.Format("XMLBinary: Internal error in CompileChildTable()"); + error = AZStd::string::format("XMLBinary: Internal error in CompileChildTable()"); return false; } diff --git a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp index f78fa93a60..ff4cfc91d2 100644 --- a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp +++ b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp @@ -345,7 +345,7 @@ void CXMLPatcher::DumpXMLNodes( AZ::IO::HandleType inFileHandle, int inIndent, const XmlNodeRef& inNode, - CryFixedStringT<512>* ioTempString) + AZStd::fixed_string<512>* ioTempString) { auto pPak = gEnv->pCryPak; @@ -393,7 +393,7 @@ void CXMLPatcher::DumpFiles( DumpXMLFile(string().Format("PATCH_%s", pOrigFileName), inBefore); - CryFixedStringT<128> newFileName(pOrigFileName); + AZStd::fixed_string<128> newFileName(pOrigFileName); newFileName.replace(".xml", "_patched.xml"); DumpXMLFile(string().Format("PATCH_%s", newFileName.c_str()), inAfter); @@ -414,7 +414,7 @@ void CXMLPatcher::DumpXMLFile( if (fileHandle != AZ::IO::InvalidHandle) { - CryFixedStringT<512> tempStr; + AZStd::fixed_string<512> tempStr; DumpXMLNodes(fileHandle, 0, inNode, &tempStr); diff --git a/Code/Legacy/CrySystem/XML/XMLPatcher.h b/Code/Legacy/CrySystem/XML/XMLPatcher.h index 039b369723..ccc5f481eb 100644 --- a/Code/Legacy/CrySystem/XML/XMLPatcher.h +++ b/Code/Legacy/CrySystem/XML/XMLPatcher.h @@ -59,7 +59,7 @@ protected: AZ::IO::HandleType inFileHandle, int inIndent, const XmlNodeRef& inNode, - CryFixedStringT<512>* ioTempString); + AZStd::fixed_string<512>* ioTempString); void DumpFiles( const char* pInXMLFileName, const XmlNodeRef& inBefore, diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp index 5761d8a963..c6e660155f 100644 --- a/Code/Legacy/CrySystem/XML/xml.cpp +++ b/Code/Legacy/CrySystem/XML/xml.cpp @@ -1691,8 +1691,8 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, char str[1024]; - CryStackStringT adjustedFilename; - CryStackStringT pakPath; + AZStd::fixed_string<256> adjustedFilename; + AZStd::fixed_string<256> pakPath; if (fileSize <= 0) { CCryFile xmlFile; @@ -1761,7 +1761,7 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, // not binary XML - refuse to load if in scripts dir and not in bin xml to help reduce hacking // wish we could compile the text xml parser out, but too much work to get everything moved over static const char SCRIPTS_DIR[] = "Scripts/"; - CryFixedStringT<32> strScripts("S"); + AZStd::fixed_string<32> strScripts("S"); strScripts += "c"; strScripts += "r"; strScripts += "i"; @@ -1770,7 +1770,7 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, strScripts += "s"; strScripts += "/"; // exclude files and PAKs from Mods folder - CryFixedStringT<8> modsStr("M"); + AZStd::fixed_string<8> modsStr("M"); modsStr += "o"; modsStr += "d"; modsStr += "s"; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 795c823fd6..7974d0f2c1 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include "AtomFont.h" diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp index 9aaaf2ffeb..f72ba6e1ff 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp @@ -18,7 +18,7 @@ namespace AtomFontInternal if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPath))) { const char* fontPath = m_strFontPath.c_str(); - const char* fontName = CryStringUtils::FindFileNameInPath(fontPath); + const char* fontName = AZ::IO::PathView(fontPath).Filename(); string newFontPath(sysFontPath); newFontPath += "/"; diff --git a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp index b7a7443daa..933633b5e3 100644 --- a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp +++ b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp @@ -437,8 +437,6 @@ namespace Blast static void CmdToggleBlastDebugVisualization(IConsoleCmdArgs* args) { - using namespace CryStringUtils; - const int argumentCount = args->GetArgCount(); if (argumentCount == 2) diff --git a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp index 640fc2100e..78742028f9 100644 --- a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp +++ b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp @@ -85,7 +85,7 @@ namespace LmbrCentral { static const char* s_assetCatalogFilename = "assetcatalog.xml"; - using LmbrCentralAllocatorScope = AZ::AllocatorScope; + using LmbrCentralAllocatorScope = AZ::AllocatorScope; // This component boots the required allocators for LmbrCentral everywhere but AssetBuilders class LmbrCentralAllocatorComponent @@ -347,12 +347,6 @@ namespace LmbrCentral m_allocatorShutdowns.push_back([]() { AZ::AllocatorInstance::Destroy(); }); } - if (!AZ::AllocatorInstance::IsReady()) - { - AZ::AllocatorInstance::Create(); - m_allocatorShutdowns.push_back([]() { AZ::AllocatorInstance::Destroy(); }); - } - // Register asset handlers. Requires "AssetDatabaseService" AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!"); diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp index d930b4b581..9cca6cdf8d 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp @@ -1512,7 +1512,7 @@ int CUiAnimViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, con if (const char* pCh = strstr(nodeName, ".[")) { char matPath[MAX_PATH]; - cry_strcpy(matPath, nodeName, (size_t)(pCh - nodeName)); + azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName)); matName = matPath; pCh += 2; if ((*pCh) != 0) diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp index ac55cd38e9..98cbd22f71 100644 --- a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp +++ b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp @@ -47,7 +47,8 @@ bool PropertyHandlerChar::ReadValuesIntoGUI(size_t index, AzToolsFramework::Prop // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to // work for cases tested but may not in general. wchar_t wcharString[2] = { static_cast(instance), 0 }; - AZStd::string val(CryStringUtils::WStrToUTF8(wcharString)); + AZStd::string val; + AZStd::to_string(val, AZStd::wstring(wcharString)); GUI->setValue(val); } GUI->blockSignals(false); diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.h b/Gems/LyShine/Code/Source/LyShineSystemComponent.h index 9b5f32aa57..f922c59afe 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.h +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.h @@ -22,9 +22,9 @@ namespace LyShine { - // LyShine depends on the LegacyAllocator and CryStringAllocator. This will be managed + // LyShine depends on the LegacyAllocator. This will be managed // by the LyShineSystemComponent - using LyShineAllocatorScope = AZ::AllocatorScope; + using LyShineAllocatorScope = AZ::AllocatorScope; class LyShineSystemComponent : public AZ::Component diff --git a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp index 318a165914..cbd0b2d6cb 100644 --- a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp +++ b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp @@ -20,7 +20,8 @@ bool UiClipboard::SetText(const AZStd::string& text) { if (text.length() > 0) { - auto wstr = CryStringUtils::UTF8ToWStr(text.c_str()); + AZStd::wstring wstr; + AZStd::to_wstring(wstr, text); const SIZE_T buffSize = (wstr.size() + 1) * sizeof(WCHAR); if (HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, buffSize)) { @@ -46,7 +47,7 @@ AZStd::string UiClipboard::GetText() if (HANDLE hText = GetClipboardData(CF_UNICODETEXT)) { const WCHAR* text = static_cast(GlobalLock(hText)); - outText = CryStringUtils::WStrToUTF8(text); + AZStd::to_string(outText, AZStd::wstring(text)); GlobalUnlock(hText); } CloseClipboard(); diff --git a/Gems/LyShine/Code/Source/StringUtfUtils.h b/Gems/LyShine/Code/Source/StringUtfUtils.h index 74a27afe9f..e10e691a6f 100644 --- a/Gems/LyShine/Code/Source/StringUtfUtils.h +++ b/Gems/LyShine/Code/Source/StringUtfUtils.h @@ -36,7 +36,8 @@ namespace LyShine // In the long run it would be better to eliminate // this function and use Unicode::CIterator<>::Position instead. wchar_t wcharString[2] = { static_cast(multiByteChar), 0 }; - AZStd::string utf8String(CryStringUtils::WStrToUTF8(wcharString)); + AZStd::string utf8String; + AZStd::to_string(utf8String, AZStd::wstring(wcharString)); int utf8Length = utf8String.length(); return utf8Length; } diff --git a/Gems/LyShine/Code/Source/UiButtonComponent.cpp b/Gems/LyShine/Code/Source/UiButtonComponent.cpp index bf0a67d08a..c6ba64848e 100644 --- a/Gems/LyShine/Code/Source/UiButtonComponent.cpp +++ b/Gems/LyShine/Code/Source/UiButtonComponent.cpp @@ -220,48 +220,9 @@ bool UiButtonComponent::VersionConverter(AZ::SerializeContext& context, // conversion from version 1 to 2: // - Need to convert CryString elements to AZStd::string // - Need to convert Color to Color and Alpha - if (classElement.GetVersion() < 2) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "SelectedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "PressedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "DisabledSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "SelectedColor", "SelectedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "PressedColor", "PressedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "DisabledColor", "DisabledAlpha")) - { - return false; - } - } - // conversion from version 2 to 3: // - Need to convert CryString ActionName elements to AZStd::string - if (classElement.GetVersion() < 3) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "ActionName")) - { - return false; - } - } + AZ_Assert(classElement.GetVersion() < 3, "Unsupported UiButtonComponent version: %d", classElement.GetVersion()); // conversion from version 3 to 4: // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp index 901c13d594..8f4145c07b 100644 --- a/Gems/LyShine/Code/Source/UiImageComponent.cpp +++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp @@ -2663,18 +2663,7 @@ bool UiImageComponent::VersionConverter(AZ::SerializeContext& context, // conversion from version 1: // - Need to convert CryString elements to AZStd::string // - Need to convert Color to Color and Alpha - if (classElement.GetVersion() <= 1) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "SpritePath")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "Color", "Alpha")) - { - return false; - } - } + AZ_Assert(classElement.GetVersion() <= 1, "Unsupported UiImageComponent version: %d", classElement.GetVersion()); // conversion from version 1 or 2 to current: // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference diff --git a/Gems/LyShine/Code/Source/UiSerialize.cpp b/Gems/LyShine/Code/Source/UiSerialize.cpp index f44d011863..e0892596ff 100644 --- a/Gems/LyShine/Code/Source/UiSerialize.cpp +++ b/Gems/LyShine/Code/Source/UiSerialize.cpp @@ -31,67 +31,6 @@ namespace UiSerialize { - //////////////////////////////////////////////////////////////////////////////////////////////////// - class CryStringTCharSerializer - : public AZ::SerializeContext::IDataSerializer - { - /// Return the size of binary buffer necessary to store the value in binary format - size_t GetRequiredBinaryBufferSize(const void* classPtr) const - { - const CryStringT* string = reinterpret_cast*>(classPtr); - return string->length() + 1; - } - - /// Store the class data into a stream. - size_t Save(const void* classPtr, AZ::IO::GenericStream& stream, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - const CryStringT* string = reinterpret_cast*>(classPtr); - const char* data = string->c_str(); - - return static_cast(stream.Write(string->length() + 1, reinterpret_cast(data))); - } - - size_t DataToText(AZ::IO::GenericStream& in, AZ::IO::GenericStream& out, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - size_t len = in.GetLength(); - char* buffer = static_cast(azmalloc(len)); - in.Read(in.GetLength(), reinterpret_cast(buffer)); - - AZStd::string outText = buffer; - azfree(buffer); - - return static_cast(out.Write(outText.size(), outText.data())); - } - - size_t TextToData(const char* text, unsigned int textVersion, AZ::IO::GenericStream& stream, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - (void)textVersion; - - size_t len = strlen(text) + 1; - stream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN); - return static_cast(stream.Write(len, reinterpret_cast(text))); - } - - bool Load(void* classPtr, AZ::IO::GenericStream& stream, unsigned int /*version*/, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - CryStringT* string = reinterpret_cast*>(classPtr); - - size_t len = stream.GetLength(); - char* buffer = static_cast(azmalloc(len)); - - stream.Read(len, reinterpret_cast(buffer)); - - *string = buffer; - azfree(buffer); - return true; - } - - bool CompareValueData(const void* lhs, const void* rhs) override - { - return AZ::SerializeContext::EqualityCompareHelper >::CompareValues(lhs, rhs); - } - }; - ////////////////////////////////////////////////////////////////////////// void UiOffsetsScriptConstructor(UiTransform2dInterface::Offsets* thisPtr, AZ::ScriptDataContext& dc) { @@ -553,9 +492,6 @@ namespace UiSerialize if (serializeContext) { - serializeContext->Class >()-> - Serializer(&AZ::Serialize::StaticInstance::s_instance); - serializeContext->Class() ->Version(1) ->Field("SerializeString", &AnimationData::m_serializeData); diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp index 025c22a895..76a789c5cf 100644 --- a/Gems/LyShine/Code/Source/UiTextComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp @@ -4995,28 +4995,8 @@ bool UiTextComponent::VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { // conversion from version 1: Need to convert Color to Color and Alpha - if (classElement.GetVersion() == 1) - { - if (!LyShine::ConvertSubElementFromCryStringToAssetRef(context, classElement, "FontFileName")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "Color", "Alpha")) - { - return false; - } - } - // conversion from version 1 or 2: Need to convert Text from CryString to AzString - if (classElement.GetVersion() <= 2) - { - // Call internal function to work-around serialization of empty AZ std string - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "Text")) - { - return false; - } - } + AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextComponent version: %d", classElement.GetVersion()); // Versions prior to v4: Change default font if (classElement.GetVersion() <= 3) diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp index e37d8787e1..c746d14095 100644 --- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp @@ -1185,7 +1185,8 @@ void UiTextInputComponent::UpdateDisplayedTextFunction() // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to // work for cases tested but may not in general. wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 }; - AZStd::string replacementCharString(CryStringUtils::WStrToUTF8(wcharString)); + AZStd::string replacementCharString; + AZStd::to_string(replacementCharString, AZStd::wstring(wcharString)); int numReplacementChars = LyShine::GetUtf8StringLength(originalText); @@ -1475,54 +1476,10 @@ bool UiTextInputComponent::VersionConverter(AZ::SerializeContext& context, // conversion from version 1: // - Need to convert CryString elements to AZStd::string // - Need to convert Color to Color and Alpha - if (classElement.GetVersion() <= 1) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "SelectedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "PressedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "SelectedColor", "SelectedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "PressedColor", "PressedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToChar(context, classElement, "ReplacementCharacter", defaultReplacementChar)) - { - return false; - } - } - // conversion from version 1 or 2 to current: // - Need to convert CryString ActionName elements to AZStd::string - if (classElement.GetVersion() <= 2) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "ChangeAction")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "EndEditAction")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "EnterAction")) - { - return false; - } - } - + AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextInputComponent version: %d", classElement.GetVersion()); + // conversion from version 1, 2 or 3 to current: // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference if (classElement.GetVersion() <= 3) diff --git a/Gems/LyShine/Code/Tests/SerializationTest.cpp b/Gems/LyShine/Code/Tests/SerializationTest.cpp index e5ed3638d4..70ae590358 100644 --- a/Gems/LyShine/Code/Tests/SerializationTest.cpp +++ b/Gems/LyShine/Code/Tests/SerializationTest.cpp @@ -24,7 +24,6 @@ namespace UnitTest appDesc.m_stackRecordLevels = 20; AZ::ComponentApplication::StartupParameters appStartup; - // Module needs to be created this way to create CryString allocator for test appStartup.m_createStaticModulesCallback = [](AZStd::vector& modules) { diff --git a/Gems/LyShine/Code/Tests/SpriteTest.cpp b/Gems/LyShine/Code/Tests/SpriteTest.cpp index 0ac3465cd7..84b47955b4 100644 --- a/Gems/LyShine/Code/Tests/SpriteTest.cpp +++ b/Gems/LyShine/Code/Tests/SpriteTest.cpp @@ -27,7 +27,6 @@ namespace UnitTest appDesc.m_stackRecordLevels = 20; AZ::ComponentApplication::StartupParameters appStartup; - // Module needs to be created this way to create CryString allocator for test appStartup.m_createStaticModulesCallback = [](AZStd::vector& modules) { diff --git a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp index 114e768975..60d578d1f8 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp @@ -52,7 +52,7 @@ void CCaptureTrack::GetKeyInfo(int key, const char*& description, float& duratio char prefix[64] = "Frame"; if (!m_keys[key].prefix.empty()) { - cry_strcpy(prefix, m_keys[key].prefix.c_str()); + azstrcpy(prefix, m_keys[key].prefix.c_str()); } description = buffer; if (!m_keys[key].folder.empty()) diff --git a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp index c9a50a0979..1dd72de567 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp @@ -25,7 +25,7 @@ void CCommentTrack::GetKeyInfo(int key, const char*& description, float& duratio description = 0; duration = m_keys[key].m_duration; - cry_strcpy(desc, m_keys[key].m_strComment.c_str()); + azstrcpy(desc, m_keys[key].m_strComment.c_str()); description = desc; } diff --git a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp index 5e1a63b4bc..278833cfe2 100644 --- a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp @@ -69,7 +69,7 @@ void CEventTrack::GetKeyInfo(int key, const char*& description, float& duration) CheckValid(); description = 0; duration = 0; - cry_strcpy(desc, m_keys[key].event.c_str()); + azstrcpy(desc, m_keys[key].event.c_str()); if (!m_keys[key].eventValue.empty()) { cry_strcat(desc, ", "); diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp index 4ffb7f0413..9e3fe212df 100644 --- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp @@ -916,7 +916,7 @@ void CAnimSceneNode::ApplyCameraKey(ISelectKey& key, SAnimContext& ec) void CAnimSceneNode::ApplyEventKey(IEventKey& key, [[maybe_unused]] SAnimContext& ec) { char funcName[1024]; - cry_strcpy(funcName, "Event_"); + azstrcpy(funcName, "Event_"); cry_strcat(funcName, key.event.c_str()); gEnv->pMovieSystem->SendGlobalEvent(funcName); } diff --git a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp index f6a0920901..3eca733a1d 100644 --- a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp @@ -143,7 +143,7 @@ void CTrackEventTrack::GetKeyInfo(int key, const char*& description, float& dura CheckValid(); description = 0; duration = 0; - cry_strcpy(desc, m_keys[key].event.c_str()); + azstrcpy(desc, m_keys[key].event.c_str()); if (!m_keys[key].eventValue.empty()) { cry_strcat(desc, ", "); diff --git a/Gems/Maestro/Code/Source/MaestroSystemComponent.h b/Gems/Maestro/Code/Source/MaestroSystemComponent.h index e5776c6628..b27075dbc0 100644 --- a/Gems/Maestro/Code/Source/MaestroSystemComponent.h +++ b/Gems/Maestro/Code/Source/MaestroSystemComponent.h @@ -17,10 +17,10 @@ namespace Maestro { - // Ensure that Maestro always has the LegacyAllocator and CryStringAllocators available + // Ensure that Maestro always has the LegacyAllocator available // NOTE: This component is only activated in the AssetBuilder, as the required allocators are // booted by the launcher or editor. - using MaestroAllocatorScope = AZ::AllocatorScope; + using MaestroAllocatorScope = AZ::AllocatorScope; class MaestroAllocatorComponent : public AZ::Component diff --git a/Gems/Metastream/Code/Tests/MetastreamTest.cpp b/Gems/Metastream/Code/Tests/MetastreamTest.cpp index c304a1c55f..4f1d37391a 100644 --- a/Gems/Metastream/Code/Tests/MetastreamTest.cpp +++ b/Gems/Metastream/Code/Tests/MetastreamTest.cpp @@ -38,12 +38,10 @@ protected: AZ::AllocatorInstance::Create(); AZ::AllocatorInstance::Create(); AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); } void TeardownEnvironment() override { - AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 96da22480d..0ccc77bba4 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -577,8 +577,6 @@ namespace PhysXDebug static void physx_Debug([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { - using namespace CryStringUtils; - const int argumentCount = arguments.size(); if (argumentCount == 1) From 63d2f34ad6641546c81674a79ee39eb20370b90d Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 28 Jul 2021 11:06:14 -0700 Subject: [PATCH 034/251] more fixes, AtomFont still requires more work Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/ILocalizationManager.h | 32 +++++++++---------- .../Legacy/CryCommon/LocalizationManagerBus.h | 26 +++++++-------- .../AtomLyIntegration/AtomFont/AtomFont.h | 4 +-- .../AtomLyIntegration/AtomFont/AtomNullFont.h | 4 +-- .../AtomLyIntegration/AtomFont/FFont.h | 12 +++---- .../AtomLyIntegration/AtomFont/FontRenderer.h | 2 +- .../AtomLyIntegration/AtomFont/FontTexture.h | 4 +-- .../AtomLyIntegration/AtomFont/GlyphCache.h | 2 +- .../AtomFont/Code/Source/FFontXML_Internal.h | 14 ++++---- 9 files changed, 49 insertions(+), 51 deletions(-) diff --git a/Code/Legacy/CryCommon/ILocalizationManager.h b/Code/Legacy/CryCommon/ILocalizationManager.h index de100152b3..2cba093f21 100644 --- a/Code/Legacy/CryCommon/ILocalizationManager.h +++ b/Code/Legacy/CryCommon/ILocalizationManager.h @@ -34,14 +34,14 @@ struct SLocalizedInfoGame } const char* szCharacterName; - string sUtf8TranslatedText; + AZStd::string sUtf8TranslatedText; bool bUseSubtitle; }; struct SLocalizedAdvancesSoundEntry { - string sName; + AZStd::string sName; float fValue; void GetMemoryUsage(ICrySizer* pSizer) const { @@ -178,12 +178,12 @@ struct ILocalizationManager // bEnglish - if true, translates the string into the always present English language. // Returns: // true if localization was successful, false otherwise - virtual bool LocalizeString_ch([[maybe_unused]] const char* sString, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } + virtual bool LocalizeString_ch([[maybe_unused]] const char* sString, [[maybe_unused]] AZStd::string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } // Summary: - // Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false ) + // Same as LocalizeString( const char* sString, AZStd::string& outLocalizedString, bool bEnglish=false ) // but at the moment this is faster. - virtual bool LocalizeString_s([[maybe_unused]] const string& sString, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } + virtual bool LocalizeString_s([[maybe_unused]] const AZStd::string& sString, [[maybe_unused]] AZStd::string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } // Summary: virtual void LocalizeAndSubstituteInternal([[maybe_unused]] AZStd::string& locString, [[maybe_unused]] const AZStd::vector& keys, [[maybe_unused]] const AZStd::vector& values) override {} @@ -196,7 +196,7 @@ struct ILocalizationManager // bEnglish - if true, returns the always present English version of the label. // Returns: // True if localization was successful, false otherwise. - virtual bool LocalizeLabel([[maybe_unused]] const char* sLabel, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } + virtual bool LocalizeLabel([[maybe_unused]] const char* sLabel, [[maybe_unused]] AZStd::string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } virtual bool IsLocalizedInfoFound([[maybe_unused]] const char* sKey) { return false; } // Summary: @@ -251,7 +251,7 @@ struct ILocalizationManager // sLocalizedString - Corresponding english language string. // Returns: // True if successful, false otherwise (key not found). - virtual bool GetEnglishString([[maybe_unused]] const char* sKey, [[maybe_unused]] string& sLocalizedString) override { return false; } + virtual bool GetEnglishString([[maybe_unused]] const char* sKey, [[maybe_unused]] AZStd::string& sLocalizedString) override { return false; } // Summary: // Get Subtitle for Key or Label . @@ -261,21 +261,21 @@ struct ILocalizationManager // bForceSubtitle - If true, get subtitle (sLocalized or sEnglish) even if not specified in Data file. // Returns: // True if subtitle found (and outSubtitle filled in), false otherwise. - virtual bool GetSubtitle([[maybe_unused]] const char* sKeyOrLabel, [[maybe_unused]] string& outSubtitle, [[maybe_unused]] bool bForceSubtitle = false) override { return false; } + virtual bool GetSubtitle([[maybe_unused]] const char* sKeyOrLabel, [[maybe_unused]] AZStd::string& outSubtitle, [[maybe_unused]] bool bForceSubtitle = false) override { return false; } // Description: // These methods format outString depending on sString with ordered arguments // FormatStringMessage(outString, "This is %2 and this is %1", "second", "first"); // Arguments: // outString - This is first and this is second. - virtual void FormatStringMessage_List([[maybe_unused]] string& outString, [[maybe_unused]] const string& sString, [[maybe_unused]] const char** sParams, [[maybe_unused]] int nParams) override {} - virtual void FormatStringMessage([[maybe_unused]] string& outString, [[maybe_unused]] const string& sString, [[maybe_unused]] const char* param1, [[maybe_unused]] const char* param2 = 0, [[maybe_unused]] const char* param3 = 0, [[maybe_unused]] const char* param4 = 0) override {} - - virtual void LocalizeTime([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShowSeconds, [[maybe_unused]] string& outTimeString) override {} - virtual void LocalizeDate([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShort, [[maybe_unused]] bool bIncludeWeekday, [[maybe_unused]] string& outDateString) override {} - virtual void LocalizeDuration([[maybe_unused]] int seconds, [[maybe_unused]] string& outDurationString) override {} - virtual void LocalizeNumber([[maybe_unused]] int number, [[maybe_unused]] string& outNumberString) override {} - virtual void LocalizeNumber_Decimal([[maybe_unused]] float number, [[maybe_unused]] int decimals, [[maybe_unused]] string& outNumberString) override {} + virtual void FormatStringMessage_List([[maybe_unused]] AZStd::string& outString, [[maybe_unused]] const AZStd::string& sString, [[maybe_unused]] const char** sParams, [[maybe_unused]] int nParams) override {} + virtual void FormatStringMessage([[maybe_unused]] AZStd::string& outString, [[maybe_unused]] const AZStd::string& sString, [[maybe_unused]] const char* param1, [[maybe_unused]] const char* param2 = 0, [[maybe_unused]] const char* param3 = 0, [[maybe_unused]] const char* param4 = 0) override {} + + virtual void LocalizeTime([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShowSeconds, [[maybe_unused]] AZStd::string& outTimeString) override {} + virtual void LocalizeDate([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShort, [[maybe_unused]] bool bIncludeWeekday, [[maybe_unused]] AZStd::string& outDateString) override {} + virtual void LocalizeDuration([[maybe_unused]] int seconds, [[maybe_unused]] AZStd::string& outDurationString) override {} + virtual void LocalizeNumber([[maybe_unused]] int number, [[maybe_unused]] AZStd::string& outNumberString) override {} + virtual void LocalizeNumber_Decimal([[maybe_unused]] float number, [[maybe_unused]] int decimals, [[maybe_unused]] AZStd::string& outNumberString) override {} // Summary: // Returns true if the project has localization configured for use, false otherwise. diff --git a/Code/Legacy/CryCommon/LocalizationManagerBus.h b/Code/Legacy/CryCommon/LocalizationManagerBus.h index 8daca5562a..69ab32cebf 100644 --- a/Code/Legacy/CryCommon/LocalizationManagerBus.h +++ b/Code/Legacy/CryCommon/LocalizationManagerBus.h @@ -99,12 +99,12 @@ public: // bEnglish - if true, translates the string into the always present English language. // Returns: // true if localization was successful, false otherwise - virtual bool LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish = false) = 0; + virtual bool LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0; // Summary: // Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false ) // but at the moment this is faster. - virtual bool LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish = false) = 0; + virtual bool LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0; // Set up system for passing in placeholder data for localized strings // Summary: @@ -138,7 +138,7 @@ public: // bEnglish - if true, returns the always present English version of the label. // Returns: // True if localization was successful, false otherwise. - virtual bool LocalizeLabel(const char* sLabel, string& outLocalizedString, bool bEnglish = false) = 0; + virtual bool LocalizeLabel(const char* sLabel, AZStd::string& outLocalizedString, bool bEnglish = false) = 0; // Summary: // Return number of localization entries. @@ -151,7 +151,7 @@ public: // sLocalizedString - Corresponding english language string. // Returns: // True if successful, false otherwise (key not found). - virtual bool GetEnglishString(const char* sKey, string& sLocalizedString) = 0; + virtual bool GetEnglishString(const char* sKey, AZStd::string& sLocalizedString) = 0; // Summary: // Get Subtitle for Key or Label . @@ -161,21 +161,21 @@ public: // bForceSubtitle - If true, get subtitle (sLocalized or sEnglish) even if not specified in Data file. // Returns: // True if subtitle found (and outSubtitle filled in), false otherwise. - virtual bool GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle = false) = 0; + virtual bool GetSubtitle(const char* sKeyOrLabel, AZStd::string& outSubtitle, bool bForceSubtitle = false) = 0; // Description: // These methods format outString depending on sString with ordered arguments // FormatStringMessage(outString, "This is %2 and this is %1", "second", "first"); // Arguments: // outString - This is first and this is second. - virtual void FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams) = 0; - virtual void FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) = 0; - - virtual void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) = 0; - virtual void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) = 0; - virtual void LocalizeDuration(int seconds, string& outDurationString) = 0; - virtual void LocalizeNumber(int number, string& outNumberString) = 0; - virtual void LocalizeNumber_Decimal(float number, int decimals, string& outNumberString) = 0; + virtual void FormatStringMessage_List(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams) = 0; + virtual void FormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) = 0; + + virtual void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString) = 0; + virtual void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString) = 0; + virtual void LocalizeDuration(int seconds, AZStd::string& outDurationString) = 0; + virtual void LocalizeNumber(int number, AZStd::string& outNumberString) = 0; + virtual void LocalizeNumber_Decimal(float number, int decimals, AZStd::string& outNumberString) = 0; // Summary: // Returns true if the project has localization configured for use, false otherwise. diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index 7dd2629bd0..7636b45060 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -82,7 +82,7 @@ namespace AZ FontFamilyPtr GetFontFamily(const char* fontFamilyName) override; void AddCharsToFontTextures(FontFamilyPtr fontFamily, const char* chars, int glyphSizeX = ICryFont::defaultGlyphSizeX, int glyphSizeY = ICryFont::defaultGlyphSizeY) override; void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} - string GetLoadedFontNames() const; + AZStd::string GetLoadedFontNames() const; void OnLanguageChanged() override; void ReloadAllFonts() override; ////////////////////////////////////////////////////////////////////////////////// @@ -124,7 +124,7 @@ namespace AZ //! \param fontFamilyName The name of the font family, or path to a font family file. //! \param outputDirectory Path to loaded font family (no filename), may need resolving with PathUtil::MakeGamePath. //! \param outputFullPath Full path to loaded font family, may need resolving with PathUtil::MakeGamePath. - XmlNodeRef LoadFontFamilyXml(const char* fontFamilyName, string& outputDirectory, string& outputFullPath); + XmlNodeRef LoadFontFamilyXml(const char* fontFamilyName, AZStd::string& outputDirectory, AZStd::string& outputFullPath); // Data::AssetBus::Handler overrides... void OnAssetReady(Data::Asset asset) override; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h index ebbdaf09d0..4820d1c176 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h @@ -42,7 +42,7 @@ namespace AZ size_t GetTextLength([[maybe_unused]] const char* str, [[maybe_unused]] const bool asciiMultiLine) const override { return 0; } - void WrapText(string& result, [[maybe_unused]] float maxWidth, const char* str, [[maybe_unused]] const TextDrawContext& ctx) override { result = str; } + void WrapText(AZStd::string& result, [[maybe_unused]] float maxWidth, const char* str, [[maybe_unused]] const TextDrawContext& ctx) override { result = str; } void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} @@ -76,7 +76,7 @@ namespace AZ virtual FontFamilyPtr GetFontFamily([[maybe_unused]] const char* fontFamilyName) override { CRY_ASSERT(false); return nullptr; } virtual void AddCharsToFontTextures([[maybe_unused]] FontFamilyPtr fontFamily, [[maybe_unused]] const char* chars, [[maybe_unused]] int glyphSizeX, [[maybe_unused]] int glyphSizeY) override {}; virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} - virtual string GetLoadedFontNames() const override { return ""; } + virtual AZStd::string GetLoadedFontNames() const override { return ""; } virtual void OnLanguageChanged() override { } virtual void ReloadAllFonts() override { } diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 7974d0f2c1..6f56d912a0 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -122,7 +122,7 @@ namespace AZ struct FontEffect { - string m_name; + AZStd::string m_name; std::vector m_passes; FontEffect(const char* name) @@ -178,7 +178,7 @@ namespace AZ void DrawString(float x, float y, float z, const char* str, const bool asciiMultiLine, const TextDrawContext& ctx) override; Vec2 GetTextSize(const char* str, const bool asciiMultiLine, const TextDrawContext& ctx) override; size_t GetTextLength(const char* str, const bool asciiMultiLine) const override; - void WrapText(string& result, float maxWidth, const char* str, const TextDrawContext& ctx) override; + void WrapText(AZStd::string& result, float maxWidth, const char* str, const TextDrawContext& ctx) override; void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {}; void GetGradientTextureCoord(float& minU, float& minV, float& maxU, float& maxV) const override; unsigned int GetEffectId(const char* effectName) const override; @@ -215,7 +215,7 @@ namespace AZ FFont(AtomFont* atomFont, const char* fontName); FontTexture* GetFontTexture() const { return m_fontTexture; } - const string& GetName() const { return m_name; } + const AZStd::string& GetName() const { return m_name; } FontEffect* AddEffect(const char* effectName); FontEffect* GetDefaultEffect(); @@ -291,8 +291,8 @@ namespace AZ static constexpr uint32_t NumBuffers = 2; static constexpr float WindowScaleWidth = 800.0f; static constexpr float WindowScaleHeight = 600.0f; - string m_name; - string m_curPath; + AZStd::string m_name; + AZStd::string m_curPath; AZ::Name m_dynamicDrawContextName = AZ::Name(AZ::AtomFontDynamicDrawContextName); @@ -341,7 +341,7 @@ namespace AZ FFont* font = const_cast(static_cast(ptr)); if (font && font->m_atomFont) { - font->m_atomFont->UnregisterFont(font->m_name); + font->m_atomFont->UnregisterFont(font->m_name.c_str()); font->m_atomFont = nullptr; } diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h index 9f95c12180..3cfb900055 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h @@ -60,7 +60,7 @@ namespace AZ FontRenderer(); ~FontRenderer(); - int LoadFromFile(const string& fileName); + int LoadFromFile(const AZStd::string& fileName); int LoadFromMemory(unsigned char* buffer, int bufferSize); int Release(); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h index 91fecfa3ef..b9bdce6810 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h @@ -74,7 +74,7 @@ namespace AZ FontTexture(); ~FontTexture(); - int CreateFromFile(const string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCharCount = 16, int heightCharCount = 16); + int CreateFromFile(const AZStd::string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCharCount = 16, int heightCharCount = 16); //! Default texture slot width/height is 16x8 slots, allowing for 128 glyphs to be stored in the font texture. This was //! previously 16x16, allowing 256 glyphs to be stored. For reference, there are 95 printable ASCII characters, so by @@ -129,7 +129,7 @@ namespace AZ // useful for special feature rendering interleaved with fonts (e.g. box behind the text) void CreateGradientSlot(); - int WriteToFile(const string& fileName); + int WriteToFile(const AZStd::string& fileName); void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const {} diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h index cd37cb6b79..8c6cf721b3 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h @@ -79,7 +79,7 @@ namespace AZ int Create(int iCacheSize, int glyphBitmapWidth, int glyphBitmapHeight, FontSmoothMethod smoothMethod, FontSmoothAmount smoothAmount, float sizeRatio); int Release(); - int LoadFontFromFile(const string& fileName); + int LoadFontFromFile(const AZStd::string& fileName); int LoadFontFromMemory(unsigned char* fileBuffer, int dataSize); int ReleaseFont(); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h index 2cae7b45ee..ac6d140dfc 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h @@ -36,7 +36,7 @@ namespace AtomFontInternal ELEMENT_PASS_BLEND = 14 }; - inline int GetBlendModeFromString(const string& str, bool dst) + inline int GetBlendModeFromString(const AZStd::string& str, bool dst) { int blend = GS_BLSRC_ONE; @@ -100,7 +100,7 @@ namespace AtomFontInternal ); } - inline AZ::FontSmoothMethod TranslateSmoothMethod(const string& value) + inline AZ::FontSmoothMethod TranslateSmoothMethod(const AZStd::string& value) { AZ::FontSmoothMethod smoothMethod = AZ::FontSmoothMethod::None; if (value == "blur") @@ -179,9 +179,8 @@ namespace AtomFontInternal void FoundElementImpl(); // notify methods - void FoundElement(const string& name) + void FoundElement(const AZStd::string& name) { - //MessageBox(NULL, string("[" + name + "]").c_str(), "FoundElement", MB_OK); // process the previous element switch (m_nElement) { @@ -246,9 +245,8 @@ namespace AtomFontInternal } } - void FoundAttribute(const string& name, const string& value) + void FoundAttribute(const AZStd::string& name, const AZStd::string& value) { - //MessageBox(NULL, string(name + "\n" + value).c_str(), "FoundAttribute", MB_OK); switch (m_nElement) { case ELEMENT_FONT: @@ -388,8 +386,8 @@ namespace AtomFontInternal AZ::FFont::FontEffect* m_effect; AZ::FFont::FontRenderingPass* m_pass; - string m_strFontPath; - string m_strFontEffectPath; + AZStd::string m_strFontPath; + AZStd::string m_strFontEffectPath; vector2l m_FontTexSize; AZ::AtomFont::GlyphSize m_slotSizes; float m_SizeRatio = IFFontConstants::defaultSizeRatio; From 72f808876c9bdaa4127edb2aae4b73e746858baa Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Wed, 28 Jul 2021 16:35:51 -0700 Subject: [PATCH 035/251] Improvements to pass statistics and SRG debugability Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../Atom/RHI.Reflect/ConstantsLayout.h | 5 +- .../Atom/RHI.Reflect/NameIdReflectionMap.h | 9 +++ .../RHI/Code/Include/Atom/RHI/ConstantsData.h | 8 +++ .../Atom/RHI/ShaderResourceGroupData.h | 3 + .../Atom/RHI/ShaderResourceGroupDebug.h | 21 ++++++ .../Source/RHI.Reflect/ConstantsLayout.cpp | 35 ++++++---- .../RHI/Code/Source/RHI/ConstantsData.cpp | 66 +++++++++++++++++++ .../Source/RHI/ShaderResourceGroupData.cpp | 5 ++ .../Source/RHI/ShaderResourceGroupDebug.cpp | 59 +++++++++++++++++ .../Atom/RHI/Code/atom_rhi_public_files.cmake | 2 + .../Include/Atom/RPI.Public/Pass/PassSystem.h | 15 ++++- .../RPI.Public/Pass/PassSystemInterface.h | 41 ++++++++---- .../Include/Atom/RPI.Public/Pass/RasterPass.h | 3 + .../Source/RPI.Public/Pass/PassSystem.cpp | 24 +++++++ .../Source/RPI.Public/Pass/RasterPass.cpp | 7 ++ .../Source/RPI.Public/Pass/RenderPass.cpp | 2 + ...AtomViewportDisplayInfoSystemComponent.cpp | 25 +++---- 17 files changed, 289 insertions(+), 41 deletions(-) create mode 100644 Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h create mode 100644 Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h index 09415f1bc2..003a7dcd23 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h @@ -81,6 +81,10 @@ namespace AZ //! If validation is disabled, true is always returned. bool ValidateAccess(ShaderInputConstantIndex inputIndex) const; + //! Prints to the console the shader input names specified by input list of indices + //! Will ignore any indices outside of the inputs array bounds + void DebugPrintNames(AZStd::array_view constantList) const; + protected: ConstantsLayout() = default; @@ -94,7 +98,6 @@ namespace AZ AZStd::vector m_inputs; IdReflectionMapForConstants m_idReflection; - AZStd::vector m_intervals; uint32_t m_sizeInBytes = 0; HashValue64 m_hash = InvalidHash; }; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h index 7756e7d290..b6042ab34c 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h @@ -68,6 +68,9 @@ namespace AZ /// Return the number of entries size_t Size() const; + // Returns true if size is zero + bool IsEmpty() const; + class NameIdReflectionMapSerializationEvents : public SerializeContext::IEventHandler { @@ -168,6 +171,12 @@ namespace AZ return m_reflectionMap.size(); } + template + bool NameIdReflectionMap::IsEmpty() const + { + return Size() == 0; + } + template void NameIdReflectionMap::Sort() { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h index 5fd10212d4..27bd418b8a 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h @@ -84,6 +84,14 @@ namespace AZ //! Returns the constants layout. const ConstantsLayout* GetLayout() const; + //! Returns whether other constant data and this have the same value at the specified shader input index + bool ConstantIsEqual(const ConstantsData& other, ShaderInputConstantIndex inputIndex) const; + + //! Performs a diff between this and input constant data and returns a list of all the shader input indices + //! for which the constants are not the same between the two. If one of the two has more constants than the + //! other, these additional constants will be added to the end of the returned list. + AZStd::vector GetIndicesOfDifferingConstants(const ConstantsData& other) const; + private: enum class ValidateConstantAccessExpect : uint32_t { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h index a145ba7ece..17ed3a64f1 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h @@ -172,6 +172,9 @@ namespace AZ //! Different platforms might follow different packing rules for the internally-managed SRG constant buffer. AZStd::array_view GetConstantData() const; + //! Returns the underlying ConstantsData struct + const ConstantsData& GetConstantsData() const; + //! Returns the shader resource layout for this group. const ShaderResourceGroupLayout* GetLayout() const; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h new file mode 100644 index 0000000000..b81f9e0c0b --- /dev/null +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h @@ -0,0 +1,21 @@ +/* + * 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 + +namespace AZ +{ + namespace RHI + { + class ConstantsData; + struct DrawItem; + class ShaderResourceGroup; + + void PrintConstantDataDiff(const ShaderResourceGroup& shaderResourceGroup, ConstantsData& referenceData, bool updateReferenceData = false); + void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData = false); + + } +} diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp index 3f9d9d9d63..fa85fbd884 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp @@ -17,10 +17,9 @@ namespace AZ if (SerializeContext* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) + ->Version(1) // Version 1: Adding debug helper functions to Shader Resource Groups ->Field("m_inputs", &ConstantsLayout::m_inputs) ->Field("m_idReflection", &ConstantsLayout::m_idReflection) - ->Field("m_intervals", &ConstantsLayout::m_intervals) ->Field("m_sizeInBytes", &ConstantsLayout::m_sizeInBytes) ->Field("m_hash", &ConstantsLayout::m_hash); } @@ -42,7 +41,6 @@ namespace AZ { m_inputs.clear(); m_idReflection.Clear(); - m_intervals.clear(); m_sizeInBytes = 0; m_hash = InvalidHash; } @@ -66,11 +64,8 @@ namespace AZ return false; } - // The constant data size is the maximum offset + size from the start of the struct. - constantDataSize = AZStd::max(constantDataSize, constantDescriptor.m_constantByteOffset + constantDescriptor.m_constantByteCount); - - // Add the [min, max) interval for the inline constant. - m_intervals.emplace_back(constantDescriptor.m_constantByteOffset, constantDescriptor.m_constantByteOffset + constantDescriptor.m_constantByteCount); + uint32_t end = constantDescriptor.m_constantByteOffset + constantDescriptor.m_constantByteCount; + constantDataSize = AZStd::max(constantDataSize, end); ++constantInputIndex; m_hash = TypeHash64(constantDescriptor.GetHash(), m_hash); @@ -99,7 +94,10 @@ namespace AZ Interval ConstantsLayout::GetInterval(ShaderInputConstantIndex inputIndex) const { - return m_intervals[inputIndex.GetIndex()]; + const ShaderInputConstantDescriptor& desc = GetShaderInput(inputIndex); + uint32_t start = desc.m_constantByteOffset; + uint32_t end = start + desc.m_constantByteCount; + return Interval(start, end); } const ShaderInputConstantDescriptor& ConstantsLayout::GetShaderInput(ShaderInputConstantIndex inputIndex) const @@ -138,8 +136,8 @@ namespace AZ { if (!m_sizeInBytes) { - AZ_Assert(m_intervals.empty(), "Constants size is not valid."); - return m_intervals.empty(); + AZ_Assert(m_idReflection.IsEmpty(), "Constants size is not valid."); + return m_idReflection.IsEmpty(); } } @@ -148,5 +146,20 @@ namespace AZ return true; } + + void ConstantsLayout::DebugPrintNames(AZStd::array_view constantList) const + { + AZStd::string output; + for (const ShaderInputConstantIndex& constandIdx : constantList) + { + if (constandIdx.GetIndex() < m_inputs.size()) + { + output += m_inputs[constandIdx.GetIndex()].m_name.GetCStr(); + output += " - "; + } + } + AZ_Printf("RHI", output.c_str()); + } + } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp index e00896d44e..29d451b4d5 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp @@ -404,5 +404,71 @@ namespace AZ AZ_Assert(m_layout, "Constants layout is null"); return m_layout.get(); } + + bool ConstantsData::ConstantIsEqual(const ConstantsData& other, ShaderInputConstantIndex inputIndex) const + { + AZStd::array_view myConstans = GetConstantRaw(inputIndex); + AZStd::array_view otherConstans = other.GetConstantRaw(inputIndex); + + // If they point to the same data, they are equal + if (myConstans == otherConstans) + { + return true; + } + + // If they point to data of different size, they are not equal + if (myConstans.size() != otherConstans.size()) + { + return false; + } + + // If they point to differing data of same size, compare the data + // Note: due to small size of data this loop will be faster than a mem compare + for(uint32_t i = 0; i < myConstans.size(); ++i) + { + if (myConstans[i] != otherConstans[i]) + { + return false; + } + } + + // Arrays point to different locations in memory but all bytes match, return true + return true; + } + + AZStd::vector ConstantsData::GetIndicesOfDifferingConstants(const ConstantsData& other) const + { + AZStd::vector differingIndices; + + if (m_layout == nullptr || other.m_layout == nullptr) + { + return differingIndices; + } + + AZStd::array_view myShaderInputs = m_layout->GetShaderInputList(); + AZStd::array_view otherShaderInputs = other.m_layout->GetShaderInputList(); + + size_t minSize = AZStd::min(myShaderInputs.size(), otherShaderInputs.size()); + size_t maxSize = AZStd::max(myShaderInputs.size(), otherShaderInputs.size()); + + for (size_t idx = 0; idx < minSize; ++idx) + { + const ShaderInputConstantIndex inputIndex(idx); + if (!ConstantIsEqual(other, inputIndex)) + { + differingIndices.push_back(inputIndex); + } + } + + // If sizes are different, add difference at the end + for (size_t idx = minSize; idx < maxSize; ++idx) + { + const ShaderInputConstantIndex inputIndex(idx); + differingIndices.push_back(inputIndex); + } + + return differingIndices; + } + } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp index f2b57bf1e5..65499fb57d 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp @@ -334,5 +334,10 @@ namespace AZ return m_constantsData.GetConstantData(); } + const ConstantsData& ShaderResourceGroupData::GetConstantsData() const + { + return m_constantsData; + } + } // namespace RHI } // namespace AZ diff --git a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp new file mode 100644 index 0000000000..4bd8d0aab8 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include + +namespace AZ +{ + namespace RHI + { + + void PrintConstantDataDiff(const ShaderResourceGroup& shaderResourceGroup, ConstantsData& referenceData, bool updateReferenceData) + { + const RHI::ConstantsData& currentData = shaderResourceGroup.GetData().GetConstantsData(); + + AZStd::vector differingIndices = currentData.GetIndicesOfDifferingConstants(referenceData); + + if (differingIndices.size() > 0) + { + AZ_Printf("RHI", "Detected different SRG values for the following fields:\n"); + if (currentData.GetLayout()) + { + currentData.GetLayout()->DebugPrintNames(differingIndices); + } + } + + if (updateReferenceData) + { + referenceData = currentData; + } + } + + void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData) + { + s32 srgIndex = -1; + for (u32 i = 0; i < drawItem.m_shaderResourceGroupCount; ++i) + { + if (drawItem.m_shaderResourceGroups[i]->GetBindingSlot() == srgBindingSlot) + { + srgIndex = i; + break; + } + } + + if (srgIndex != -1) + { + const ShaderResourceGroup& srg = *drawItem.m_shaderResourceGroups[srgIndex]; + PrintConstantDataDiff(srg, referenceData, updateReferenceData); + } + } + + } +} diff --git a/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake b/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake index b489cbbbb4..2bf2acd892 100644 --- a/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake +++ b/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake @@ -156,10 +156,12 @@ set(FILES Source/RHI/ScopeAttachment.cpp Include/Atom/RHI/ShaderResourceGroup.h Include/Atom/RHI/ShaderResourceGroupData.h + Include/Atom/RHI/ShaderResourceGroupDebug.h Include/Atom/RHI/ShaderResourceGroupInvalidateRegistry.h Include/Atom/RHI/ShaderResourceGroupPool.h Source/RHI/ShaderResourceGroup.cpp Source/RHI/ShaderResourceGroupData.cpp + Source/RHI/ShaderResourceGroupDebug.cpp Source/RHI/ShaderResourceGroupInvalidateRegistry.cpp Source/RHI/ShaderResourceGroupPool.cpp Include/Atom/RHI/MemoryStatisticsBuilder.h diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h index de57e2e3f6..5998798ae8 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h @@ -74,6 +74,12 @@ namespace AZ const AZ::Name& GetTargetedPassDebuggingName() const override; void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) override; PassSystemState GetState() const override; + SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const override; + + // PassSystemInterface statistics related functions + void IncrementFrameDrawItemCount(u32 numDrawItems) override; + void IncrementFrameRenderPassCount() override; + PassSystemFrameStatistics GetFrameStatistics() override; // PassSystemInterface factory related functions... void AddPassCreator(Name className, PassCreator createFunction) override; @@ -92,7 +98,6 @@ namespace AZ void RegisterPass(Pass* pass) override; void UnregisterPass(Pass* pass) override; AZStd::vector FindPasses(const PassFilter& passFilter) const override; - SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const override; private: // Returns the root of the pass tree hierarchy @@ -115,6 +120,9 @@ namespace AZ void QueueForRemoval(Pass* pass) override; void QueueForInitialization(Pass* pass) override; + // Resets the frame statistic counters + void ResetFrameStatistics(); + // Lists for queuing passes for various function calls // Name of the list reflects the pass function it will call AZStd::vector< Ptr > m_buildPassList; @@ -140,13 +148,16 @@ namespace AZ AZ::Name m_targetedPassDebugName; // Counts the number of passes - int32_t m_passCounter = 0; + u32 m_passCounter = 0; // Events OnReadyLoadTemplatesEvent m_loadTemplatesEvent; // Used to track what phase of execution the pass system is in PassSystemState m_state = PassSystemState::Unitialized; + + // Counters used to gather statistics about the frame + PassSystemFrameStatistics m_frameStatistics; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h index cc66a7c228..246e43a2f7 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h @@ -66,6 +66,14 @@ namespace AZ FrameEnd, }; + //! Frame counters used for collecting statistics + struct PassSystemFrameStatistics + { + u32 m_numRenderPassesExecuted = 0; + u32 m_totalDrawItemsRendered = 0; + u32 m_maxDrawItemsRenderedInAPass = 0; + }; + class PassSystemInterface { friend class Pass; @@ -115,6 +123,27 @@ namespace AZ virtual void SetTargetedPassDebuggingName(const AZ::Name& targetPassName) = 0; virtual const AZ::Name& GetTargetedPassDebuggingName() const = 0; + //! Find the SwapChainPass associated with window Handle + virtual SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const = 0; + + using OnReadyLoadTemplatesEvent = AZ::Event<>; + //! Connect a handler to listen to the event that the pass system is ready to load pass templates + //! The event is triggered when pass system is initialized and asset system is ready. + //! The handler can add new pass templates or load pass template mappings from assets + virtual void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) = 0; + + virtual PassSystemState GetState() const = 0; + + // Passes call this function to notify the pass system that they are drawing X draw items this frame + // Used for Pass System statistics + virtual void IncrementFrameDrawItemCount(u32 numDrawItems) = 0; + + // Increments the counter for the number of render passes executed this frame (does not include passes that are disabled) + virtual void IncrementFrameRenderPassCount() = 0; + + // Get frame statistics from the Pass System + virtual PassSystemFrameStatistics GetFrameStatistics() = 0; + // --- Pass Factory related functionality --- //! Directly creates a pass given a PassDescriptor @@ -171,17 +200,6 @@ namespace AZ //! Find matching passes from registered passes with specified filter virtual AZStd::vector FindPasses(const PassFilter& passFilter) const = 0; - //! Find the SwapChainPass associated with window Handle - virtual SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const = 0; - - using OnReadyLoadTemplatesEvent = AZ::Event<>; - //! Connect a handler to listen to the event that the pass system is ready to load pass templates - //! The event is triggered when pass system is initialized and asset system is ready. - //! The handler can add new pass templates or load pass template mappings from assets - virtual void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) = 0; - - virtual PassSystemState GetState() const = 0; - private: // These functions are only meant to be used by the Pass class @@ -199,7 +217,6 @@ namespace AZ //! Unregisters the pass with the pass library. Called in the Pass destructor. virtual void UnregisterPass(Pass* pass) = 0; - }; namespace PassSystemEvents diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h index 735b3930c8..b0d941083b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h @@ -42,6 +42,8 @@ namespace AZ //! Expose shader resource group. ShaderResourceGroup* GetShaderResourceGroup(); + u32 GetDrawItemCount(); + protected: explicit RasterPass(const PassDescriptor& descriptor); @@ -68,6 +70,7 @@ namespace AZ RHI::Viewport m_viewportState; bool m_overrideScissorSate = false; bool m_overrideViewportState = false; + u32 m_drawItemCount = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index 91cc645947..3092b9ecd0 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -308,6 +308,7 @@ namespace AZ AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: FrameUpdate"); + ResetFrameStatistics(); ProcessQueuedChanges(); m_state = PassSystemState::Rendering; @@ -392,6 +393,29 @@ namespace AZ handler.Connect(m_loadTemplatesEvent); } + void PassSystem::ResetFrameStatistics() + { + m_frameStatistics.m_numRenderPassesExecuted = 0; + m_frameStatistics.m_totalDrawItemsRendered = 0; + m_frameStatistics.m_maxDrawItemsRenderedInAPass = 0; + } + + PassSystemFrameStatistics PassSystem::GetFrameStatistics() + { + return m_frameStatistics; + } + + void PassSystem::IncrementFrameDrawItemCount(u32 numDrawItems) + { + m_frameStatistics.m_totalDrawItemsRendered += numDrawItems; + m_frameStatistics.m_maxDrawItemsRenderedInAPass = AZStd::max(m_frameStatistics.m_maxDrawItemsRenderedInAPass, numDrawItems); + } + + void PassSystem::IncrementFrameRenderPassCount() + { + ++m_frameStatistics.m_numRenderPassesExecuted; + } + // --- Pass Factory Functions --- void PassSystem::AddPassCreator(Name className, PassCreator createFunction) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index ee38c1e5ef..ae74e355f2 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -112,6 +112,11 @@ namespace AZ return m_shaderResourceGroup.get(); } + u32 RasterPass::GetDrawItemCount() + { + return m_drawItemCount; + } + // --- Pass behaviour overrides --- void RasterPass::Validate(PassValidationResults& validationResults) @@ -145,6 +150,8 @@ namespace AZ // Draw List m_drawListView = view->GetDrawList(m_drawListTag); + m_drawItemCount = m_drawListView.size(); + PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); } RenderPass::FrameBeginInternal(params); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp index 96649573b2..92e6d8b2b6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp @@ -200,6 +200,8 @@ namespace AZ m_attachmentCopy.lock()->FrameBegin(params); } CollectSrgs(); + + PassSystemInterface::Get()->IncrementFrameRenderPassCount(); } diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index af9fd7fdd8..ef341f8dc8 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -229,25 +229,20 @@ namespace AZ::Render AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); auto rootPass = viewportContext->GetCurrentPipeline()->GetRootPass(); const RPI::PipelineStatisticsResult stats = rootPass->GetLatestPipelineStatisticsResult(); - AZStd::function)> containingPassCount = [&containingPassCount](const AZ::RPI::Ptr pass) - { - int count = 1; - if (auto passAsParent = pass->AsParent()) - { - for (const auto& child : passAsParent->GetChildren()) - { - count += containingPassCount(child); - } - } - return count; - }; - const int numPasses = containingPassCount(rootPass); + + RPI::PassSystemFrameStatistics passSystemFrameStatistics = AZ::RPI::PassSystemInterface::Get()->GetFrameStatistics(); + DrawLine(AZStd::string::format( - "Total Passes: %d Vertex Count: %lld Primitive Count: %lld", - numPasses, + "RenderPasses: %d Vertex Count: %lld Primitive Count: %lld", + passSystemFrameStatistics.m_numRenderPassesExecuted, aznumeric_cast(stats.m_vertexCount), aznumeric_cast(stats.m_primitiveCount) )); + DrawLine(AZStd::string::format( + "Total Draw Item Count: %d Max Draw Items in a Pass: %d", + passSystemFrameStatistics.m_totalDrawItemsRendered, + passSystemFrameStatistics.m_maxDrawItemsRenderedInAPass + )); } void AtomViewportDisplayInfoSystemComponent::UpdateFramerate() From 56eda61828f9fb9beaf328ad2107de00ffd482f6 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:49:44 -0700 Subject: [PATCH 036/251] remove of UNICODE/_UNICODE Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../WinAPI/AzCore/Debug/Trace_WinAPI.cpp | 4 - .../WinAPI/AzCore/IO/SystemFile_WinAPI.cpp | 115 +----------------- .../Module/DynamicModuleHandle_WinAPI.cpp | 5 - .../AzCore/std/parallel/config_WinAPI.h | 12 +- .../Windows/AzCore/PlatformIncl_Windows.h | 1 + Code/Legacy/CryCommon/AppleSpecific.h | 5 - Code/Legacy/CryCommon/LinuxSpecific.h | 5 - Code/Legacy/CryCommon/platform.h | 2 +- 8 files changed, 5 insertions(+), 144 deletions(-) diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp index d4a0f52941..143bd8f9d0 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp @@ -61,16 +61,12 @@ namespace AZ void OutputToDebugger(const char* window, const char* message) { AZ_UNUSED(window); -#ifdef _UNICODE wchar_t messageW[g_maxMessageLength]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, messageW, message, g_maxMessageLength - 1) == 0) { OutputDebugStringW(messageW); } -#else // !_UNICODE - OutputDebugString(message); -#endif // !_UNICODE } } } diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp index 090e29a535..15d779017d 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp @@ -28,7 +28,6 @@ namespace //========================================================================= DWORD GetAttributes(const char* fileName) { -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) @@ -39,9 +38,6 @@ namespace { return INVALID_FILE_ATTRIBUTES; } -#else //!_UNICODE - return GetFileAttributes(fileName); -#endif // !_UNICODE } //========================================================================= @@ -51,7 +47,6 @@ namespace //========================================================================= BOOL SetAttributes(const char* fileName, DWORD fileAttributes) { -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) @@ -62,9 +57,6 @@ namespace { return FALSE; } -#else //!_UNICODE - return SetFileAttributes(fileName, fileAttributes); -#endif // !_UNICODE } //========================================================================= @@ -76,7 +68,6 @@ namespace // * GetLastError() on Windows-like platforms // * errno on Unix platforms //========================================================================= -#if defined(_UNICODE) bool CreateDirRecursive(wchar_t* dirPath) { if (CreateDirectoryW(dirPath, nullptr)) @@ -112,53 +103,6 @@ namespace } return false; } -#else - bool CreateDirRecursive(char* dirPath) - { - if (CreateDirectory(dirPath, nullptr)) - { - return true; // Created without error - } - DWORD error = GetLastError(); - if (error == ERROR_PATH_NOT_FOUND) - { - // try to create our parent hierarchy - for (size_t i = strlen(dirPath); i > 0; --i) - { - if (dirPath[i] == '/' || dirPath[i] == '\\') - { - char delimiter = dirPath[i]; - dirPath[i] = 0; // null-terminate at the previous slash - bool ret = CreateDirRecursive(dirPath); - dirPath[i] = delimiter; // restore slash - if (ret) - { - // now that our parent is created, try to create again - if (CreateDirectory(dirPath, nullptr)) - { - return true; - } - DWORD creationError = GetLastError(); - if (creationError == ERROR_ALREADY_EXISTS) - { - DWORD attributes = GetFileAttributes(dirPath); - return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; - } - return false; - } - return false; - } - } - // if we reach here then there was no parent folder to create, so we failed for other reasons - } - else if (error == ERROR_ALREADY_EXISTS) - { - DWORD attributes = GetFileAttributes(dirPath); - return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; - } - return false; - } -#endif static const SystemFile::FileHandleType PlatformSpecificInvalidHandle = INVALID_HANDLE_VALUE; } @@ -208,7 +152,6 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) CreatePath(m_fileName.c_str()); } -# ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; m_handle = INVALID_HANDLE_VALUE; @@ -216,9 +159,6 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) { m_handle = CreateFileW(fileNameW, dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0); } -# else //!_UNICODE - m_handle = CreateFile(m_fileName.c_str(), dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0); -# endif // !_UNICODE if (m_handle == INVALID_HANDLE_VALUE) { @@ -417,7 +357,6 @@ namespace Platform HANDLE hFile; int lastError; -#ifdef _UNICODE wchar_t filterW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; hFile = INVALID_HANDLE_VALUE; @@ -425,39 +364,28 @@ namespace Platform { hFile = FindFirstFile(filterW, &fd); } -#else // !_UNICODE - hFile = FindFirstFile(filter, &fd); -#endif // !_UNICODE if (hFile != INVALID_HANDLE_VALUE) { const char* fileName; -#ifdef _UNICODE char fileNameA[AZ_MAX_PATH_LEN]; fileName = NULL; if (wcstombs_s(&numCharsConverted, fileNameA, fd.cFileName, AZ_ARRAY_SIZE(fileNameA) - 1) == 0) { fileName = fileNameA; } -#else // !_UNICODE - fileName = fd.cFileName; -#endif // !_UNICODE cb(fileName, (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0); // List all the other files in the directory. - while (FindNextFile(hFile, &fd) != 0) + while (FindNextFileW(hFile, &fd) != 0) { -#ifdef _UNICODE fileName = NULL; if (wcstombs_s(&numCharsConverted, fileNameA, fd.cFileName, AZ_ARRAY_SIZE(fileNameA) - 1) == 0) { fileName = fileNameA; } -#else // !_UNICODE - fileName = fd.cFileName; -#endif // !_UNICODE cb(fileName, (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0); } @@ -483,16 +411,12 @@ namespace Platform { HANDLE handle = nullptr; -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) { handle = CreateFileW(fileNameW, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); } -#else // !_UNICODE - handle = CreateFileA(fileName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); -#endif // !_UNICODE if (handle == INVALID_HANDLE_VALUE) { @@ -524,16 +448,12 @@ namespace Platform WIN32_FILE_ATTRIBUTE_DATA data = { 0 }; BOOL result = FALSE; -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) { result = GetFileAttributesExW(fileNameW, GetFileExInfoStandard, &data); } -#else // !_UNICODE - result = GetFileAttributesExA(fileName, GetFileExInfoStandard, &data); -#endif // !_UNICODE if (result) { @@ -553,7 +473,6 @@ namespace Platform bool Delete(const char* fileName) { -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) @@ -568,20 +487,12 @@ namespace Platform { return false; } -#else // !_UNICODE - if (DeleteFile(fileName) == 0) - { - EBUS_EVENT(FileIOEventBus, OnError, nullptr, fileName, (int)GetLastError()); - return false; - } -#endif // !_UNICODE return true; } bool Rename(const char* sourceFileName, const char* targetFileName, bool overwrite) { -#ifdef _UNICODE wchar_t sourceFileNameW[AZ_MAX_PATH_LEN]; wchar_t targetFileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; @@ -598,13 +509,6 @@ namespace Platform { return false; } -#else // !_UNICODE - if (MoveFileEx(sourceFileName, targetFileName, overwrite ? MOVEFILE_REPLACE_EXISTING : 0) == 0) - { - EBUS_EVENT(FileIOEventBus, OnError, nullptr, sourceFileName, (int)GetLastError()); - return false; - } -#endif // !_UNICODE return true; } @@ -639,7 +543,6 @@ namespace Platform { if (dirName) { -#if defined(_UNICODE) wchar_t dirPath[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, dirPath, dirName, AZ_ARRAY_SIZE(dirPath) - 1) == 0) @@ -651,18 +554,6 @@ namespace Platform } return success; } -#else - char dirPath[AZ_MAX_PATH_LEN]; - if (azstrcpy(dirPath, AZ_ARRAY_SIZE(dirPath), dirName) == 0) - { - bool success = CreateDirRecursive(dirPath); - if (!success) - { - EBUS_EVENT(FileIOEventBus, OnError, nullptr, dirName, (int)GetLastError()); - } - return success; - } -#endif } return false; } @@ -671,16 +562,12 @@ namespace Platform { if (dirName) { -#if defined(_UNICODE) wchar_t dirNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, dirNameW, dirName, AZ_ARRAY_SIZE(dirNameW) - 1) == 0) { return RemoveDirectory(dirNameW) != 0; } -#else - return RemoveDirectory(dirName) != 0; -#endif } return false; diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp index cc04fb6bd5..659650d2e2 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp @@ -98,7 +98,6 @@ namespace AZ bool alreadyLoaded = false; -# ifdef _UNICODE wchar_t fileNameW[MAX_PATH]; size_t numCharsConverted; errno_t wcharResult = mbstowcs_s(&numCharsConverted, fileNameW, m_fileName.c_str(), AZ_ARRAY_SIZE(fileNameW) - 1); @@ -114,10 +113,6 @@ namespace AZ m_handle = NULL; return LoadStatus::LoadFailure; } -# else //!_UNICODE - alreadyLoaded = NULL != GetModuleHandleA(m_fileName.c_str()); - m_handle = LoadLibraryA(m_fileName.c_str()); -# endif // !_UNICODE if (m_handle) { diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h index fe7620c173..fb91e4d503 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h @@ -75,22 +75,14 @@ extern "C" AZ_DLL_IMPORT HANDLE _stdcall CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCWSTR lpName); AZ_DLL_IMPORT BOOL _stdcall ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount); #ifndef CreateSemaphore - #ifdef UNICODE - #define CreateSemaphore CreateSemaphoreW - #else - #define CreateSemaphore CreateSemaphoreA - #endif + #define CreateSemaphore CreateSemaphoreW #endif // Event AZ_DLL_IMPORT HANDLE _stdcall CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName); AZ_DLL_IMPORT HANDLE _stdcall CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCWSTR lpName); #ifndef CreateEvent - #ifdef UNICODE - #define CreateEvent CreateEventW - #else - #define CreateEvent CreateEventA - #endif + #define CreateEvent CreateEventW #endif AZ_DLL_IMPORT BOOL _stdcall SetEvent(HANDLE); } diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h b/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h index 6adef282eb..f58e772155 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h @@ -9,6 +9,7 @@ #pragma once #define WIN32_LEAN_AND_MEAN +#define UNICODE //#define NOGDICAPMASKS //- CC_*, LC_*, PC_*, CP_*, TC_*, RC_ //#define NOVIRTUALKEYCODES //- VK_* //#define NOWINMESSAGES //- WM_*, EM_*, LB_*, CB_* diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index 4d17c18bac..caf85a8f44 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -192,13 +192,8 @@ typedef WCHAR* LPUWSTR, * PUWSTR; typedef const WCHAR* LPCWSTR, * PCWSTR; typedef const WCHAR* LPCUWSTR, * PCUWSTR; -#ifdef UNICODE typedef LPCWSTR LPCTSTR; typedef LPWSTR LPTSTR; -#else -typedef LPCSTR LPCTSTR; -typedef LPSTR LPTSTR; -#endif typedef DWORD COLORREF; #define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h index 5fc1f7b801..72673cafe3 100644 --- a/Code/Legacy/CryCommon/LinuxSpecific.h +++ b/Code/Legacy/CryCommon/LinuxSpecific.h @@ -156,13 +156,8 @@ typedef WCHAR* LPUWSTR, * PUWSTR; typedef const WCHAR* LPCWSTR, * PCWSTR; typedef const WCHAR* LPCUWSTR, * PCUWSTR; -#ifdef UNICODE typedef LPCWSTR LPCTSTR; typedef LPWSTR LPTSTR; -#else -typedef LPCSTR LPCTSTR; -typedef LPSTR LPTSTR; -#endif typedef char TCHAR; typedef DWORD COLORREF; diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 60edf10de9..c040139b5a 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -176,7 +176,7 @@ // In Win32 Release we use static linkage #ifdef WIN32 - #if !defined(_RELEASE) || defined(RESOURCE_COMPILER) || defined(EDITOR) || defined(_FORCEDLL) + #if !defined(_RELEASE) || defined(EDITOR) || defined(_FORCEDLL) // All windows targets not in Release built as DLLs. #ifndef _USRDLL #define _USRDLL From f21fc79dc45842c67ce7640b8bf061963ccf78de Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:50:24 -0700 Subject: [PATCH 037/251] remove of unicode files from Cry Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/UnicodeBinding.h | 946 -------------- Code/Legacy/CryCommon/UnicodeEncoding.h | 767 ----------- Code/Legacy/CryCommon/UnicodeFunctions.h | 1265 ------------------- Code/Legacy/CryCommon/UnicodeIterator.h | 615 --------- Code/Legacy/CryCommon/crycommon_files.cmake | 4 - 5 files changed, 3597 deletions(-) delete mode 100644 Code/Legacy/CryCommon/UnicodeBinding.h delete mode 100644 Code/Legacy/CryCommon/UnicodeEncoding.h delete mode 100644 Code/Legacy/CryCommon/UnicodeFunctions.h delete mode 100644 Code/Legacy/CryCommon/UnicodeIterator.h diff --git a/Code/Legacy/CryCommon/UnicodeBinding.h b/Code/Legacy/CryCommon/UnicodeBinding.h deleted file mode 100644 index aaefcf0f55..0000000000 --- a/Code/Legacy/CryCommon/UnicodeBinding.h +++ /dev/null @@ -1,946 +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 - * - */ - - -// Note: The utilities in this file should typically not be used directly, -// consider including UnicodeFunctions.h or UnicodeIterator.h instead. -// -// (At least) the following string types can be bound with these helper functions: -// Types Input Output Null-Terminator -// std::basic_string, std::string, std::wstring: yes yes implied by type -// QString: yes yes implied by type -// std::vector, std::list, std::deque: yes yes not present -// T[] (fixed-length buffer): yes yes guaranteed to be emitted on output, accepted on input -// T * and size_t (user-specified-size buffer): no yes guaranteed to be emitted on output -// const T * (null-terminated string): yes no expected -// const T[] (literal): yes no implied as the last item in the array -// pair of iterators over T: yes no should not be included in the range -// uint32 (single UCS code-point): yes no not present -// If some other string type is not listed, you can still use it for input easily by passing begin/end iterators. -// Note: For all types, T can be any 8-bit, 16-bit or 32-bit integral or character type. -// Further T types may be processed by explicitly passing InputEncoding and OutputEncoding. -// We never actively tested such scenario's, so no guarantees on floating and user-defined types as code-units. - - -#pragma once - -#ifndef assert -// Some tools use CRT's assert, most engine and game modules use CryAssert.h (via platform.h maybe). -// We don't want to force a choice upon all code that uses Unicode utilities, so we just assume assert is defined. -#error This header uses assert macro, please provide an applicable definition before including UnicodeXXX.h -#endif - -#include "UnicodeEncoding.h" -#include // For str(n)len and memcpy. -#include // For wcs(n)len. -#include // For size_t and ptrdiff_t. -#include // For std::iterator_traits. -#include // For std::basic_string. -#include // For std::vector. -#include // For std::list. -#include // For std::deque. -#include // ... standard type-traits (as of C++11). - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define UNICODEBINDING_H_SECTION_1 1 -#define UNICODEBINDING_H_SECTION_2 2 -#endif - -// Forward declare the supported types. -// Before actually instantiating a binding however, you need to have the full definition included. -// Also, this allows us to work with QChar/QString as declared names without a dependency on Qt. -namespace AZStd -{ - template - class basic_fixed_string; -} -class QChar; -class QString; - -namespace Unicode -{ - namespace Detail - { - // Import standard type traits. - // This requires C++11 compiler support. - using std::add_const; - using std::conditional; - using std::extent; - using std::integral_constant; - using std::is_arithmetic; - using std::is_array; - using std::is_base_of; - using std::is_const; - using std::is_convertible; - using std::is_integral; - using std::is_pointer; - using std::is_same; - using std::make_unsigned; - using std::remove_cv; - using std::remove_extent; - using std::remove_pointer; - - // SVoid: - // Result type will be void if T is well-formed. - // Note: This is mostly used to test the presence of member types at compile-time. - template - struct SVoid - { - typedef void type; - }; - - // SValidChar: - // Determine if T is a valid character type in the given compile-time context. - // The InferEncoding flag is set if the encoding has to be detected automatically. - // The Input flag is set if the type is used for input (and not set if the type is used for output). - template - struct SValidChar - { - typedef typename remove_cv::type BaseType; - static const bool isArithmeticType = is_arithmetic::value; - static const bool isQChar = is_same::value; - static const bool isUsable = isArithmeticType || isQChar; - static const bool isValidQualified = !is_const::value || Input; - static const bool isKnownSize = sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4; - static const bool isValidInferred = isKnownSize || !InferEncoding; - static const bool value = isUsable && isValidQualified && isValidInferred; - }; - - // SPackedIterators: - // A pair of iterators over some range. - // Note: Packing iterators into a single object allows us to pass them as a single argument like all other types. - template - struct SPackedIterators - { - const T begin, end; - SPackedIterators(const T& _begin, const T& _end) - : begin(_begin) - , end(_end) {} - }; - - // SPackedBuffer: - // A buffer-pointer/length tuple. - // Note: Packing them into a single object allows us to pass them as a single argument like all other types. - template - struct SPackedBuffer - { - T buffer; - size_t size; - SPackedBuffer(T _buffer, size_t _size) - : buffer(_buffer) - , size(_size) {} - }; - - // SDependentType: - // Makes the name of type T dependent on X (which is otherwise meaningless). - // Note: This is used to force two-phase lookup so we don't need the definition of T until instantiation. - // This way we can convince standards-compliant compilers Clang and GCC to not require definition of forward-declared types. - // Specifically, we forward-declare Qt's QString and QChar, for which the definition will never be available outside Editor. - template - struct SDependentType - { - typedef T type; - }; - - // EBind: - // Methods of binding a type for input and/or output. - // Note: These are used for tag-dispatch by binding functions, and are private to the implementation. - enum EBind - { // Input Output Description - eBind_Impossible, // No No Can't bind this type. - eBind_Iterators, // Yes Yes Bind by using begin() and end() member functions. - eBind_Data, // Yes Yes Bind by using data() and size() member functions. - eBind_Literal, // Yes No Bind a fixed size buffer (const element, aka string literal). - eBind_Buffer, // Yes No Bind a fixed size buffer (non-const element) that may be null-terminated. - eBind_PackedBuffer, // No Yes Bind a user-specified size buffer (non-const element). - eBind_NullTerminated, // Yes No Bind a null-terminated buffer of unknown length (C string). - eBind_CodePoint, // Yes No Bind a single code-point value. - }; - - // SBindIterator: - // Find the EBind for input from iterator pair of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible - template - struct SBindIterator - { - typedef const void CharType; - static const EBind value = eBind_Impossible; - }; - template - struct SBindIterator - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindIterator::type, - typename SVoid::type - > - { - typedef typename add_const::type CharType; - typedef typename T::iterator_category IteratorCategory; - static const bool isInputIterator = is_base_of::value; - static const bool isValid = SValidChar::value; - static const EBind value = isValid && isInputIterator ? eBind_Iterators : eBind_Impossible; - }; - - // SBindObject: - // Find the EBind for input from object of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible. - template - struct SBindObject - { - typedef typename add_const< - typename conditional< - is_array::value, - typename remove_extent::type, - typename remove_pointer::type - >::type - >::type CharType; - static const size_t FixedSize = extent::value; - COMPILE_TIME_ASSERT(!is_array::value || FixedSize > 0); - static const bool isConstArray = is_array::value && is_const::type>::value; - static const bool isBufferArray = is_array::value && !isConstArray; - static const bool isPointer = is_pointer::value; - static const bool isCodePoint = is_integral::value; - static const bool isValidChar = SValidChar::value; - static const EBind value = - !isValidChar ? eBind_Impossible : - isConstArray ? eBind_Literal : - isBufferArray ? eBind_Buffer : - isPointer ? eBind_NullTerminated : - isCodePoint ? eBind_CodePoint : - eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef wchar_t CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject - { - typedef const QChar CharType; - static const EBind value = eBind_Data; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename SBindIterator::CharType CharType; - static const EBind value = eBind_Iterators; - }; - - // SBindOutput: - // Find the EBind for output to object of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible. - template - struct SBindOutput - { - typedef typename remove_extent::type CharType; - static const size_t FixedSize = extent::value; - static const bool isArray = is_array::value; - static const bool isValid = SValidChar::type, InferEncoding, false>::value; - static const EBind value = isArray && isValid ? eBind_Buffer : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef OutputCharType CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_PackedBuffer : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef CharT CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput - { - typedef QChar CharType; - static const EBind value = eBind_Data; - }; - - // SInferEncoding: - // Infers the encoding of the given character type. - // Note: This will always pick an UTF encoding type based on the size of the element type. - template - struct SInferEncoding - { - typedef SBindObject ObjectType; - typedef SBindIterator IteratorType; - typedef typename conditional< - IteratorType::value != eBind_Impossible, - typename IteratorType::CharType, - typename ObjectType::CharType - >::type CharType; - static const EEncoding value = - sizeof(CharType) == 1 ? eEncoding_UTF8 : - sizeof(CharType) == 2 ? eEncoding_UTF16 : - eEncoding_UTF32; - COMPILE_TIME_ASSERT(value != eEncoding_UTF32 || sizeof(CharType) == 4); - }; - - // SBindCharacter: - // Pick the base character type to use during input or output with this element type. - template::value, bool IsQChar = is_same::type>::value> - struct SBindCharacter - { - typedef typename make_unsigned::type BaseType; // The standard doesn't define if a character type is signed or unsigned. - typedef typename remove_cv::type UnqualifiedType; - typedef typename conditional::type type; - }; - template - struct SBindCharacter - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - typedef typename remove_cv::type UnqualifiedType; - typedef typename conditional::type type; - }; - template - struct SBindCharacter - { - typedef typename conditional::type type; - typedef typename SDependentType::type ActuallyQChar; // Force two-phase name lookup on QChar. - COMPILE_TIME_ASSERT(sizeof(ActuallyQChar) == sizeof(type)); // In case Qt ever changes QChar. - }; - - // SBindPointer: - // Pick the pointer type to use during input or output with buffers (potentially inside string types). - template - struct SBindPointer - { - COMPILE_TIME_ASSERT(is_pointer::value || is_array::value); - typedef typename conditional< - is_pointer::value, - typename remove_pointer::type, - typename remove_extent::type - >::type UnboundCharType; - typedef typename SBindCharacter::type BoundCharType; - typedef BoundCharType* type; - }; - - // SAutomaticallyDeduced: - // Placeholder type that is never defined, used by SRequire for SFINAE overloading. - struct SAutomaticallyDeduced; - - // SRequire: - // Helper for SFINAE overloading. - // Similar to C++11's std::enable_if, which is not in boost (with that exact name anyway). - template - struct SRequire - { - typedef T type; - }; - template - struct SRequire {}; - - // SafeCast: - // Cast a pointer to type T, but only allowing safe casts. - // This guards against bad code in other functions since it prevents unintended casts. - template - inline T SafeCast(SourceChar* ptr, typename SRequire::value>::type* = 0) - { - // Allow casts from pointer-to-integral to unrelated pointer-to-integral, provided they are of the same size. - typedef typename remove_pointer::type TargetChar; - COMPILE_TIME_ASSERT(is_integral::value && is_integral::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); - return reinterpret_cast(ptr); - } - template - inline T SafeCast(SourceChar* ptr, typename SRequire::type, QChar>::value>::type* = 0) - { - // Allow casts from pointer-to-QChar to unrelated pointer-to-integral, provided they are of the same size. - typedef typename remove_pointer::type TargetChar; - COMPILE_TIME_ASSERT(is_integral::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); - return reinterpret_cast(ptr); - } - template - inline T SafeCast(SourceChar* ptr, typename SRequire::value&& !is_same::type, QChar>::value>::type* = 0) - { - // Any other casts that are allowed by C++. - return static_cast(ptr); - } - - // SCharacterTrait: - // Exposes some basic traits for a given character. - // Note: Map to (hopefully optimized) CRT functions where possible. - template::value> - struct SCharacterTrait - { - static size_t StrLen(const T* nts) // Fall-back strlen. - { - size_t result = 0; - while (*nts != 0) - { - ++nts; - ++result; - } - return result; - } - static size_t StrNLen(const T* ptr, size_t len) // Fall-back strnlen. - { - size_t result = 0; - while (*ptr != 0 && result != len) - { - ++ptr; - ++result; - } - return result; - } - }; - template - struct SCharacterTrait - { - static size_t StrLen(const T* nts) // Narrow CRT strlen. - { - return ::strlen(SafeCast(nts)); - } - static size_t StrNLen(const T* ptr, size_t len) // Narrow CRT strnlen. - { - return ::strnlen(SafeCast(ptr), len); - } - }; - template - struct SCharacterTrait - { - static size_t StrLen(const T* nts) // Wide CRT strlen. - { - return ::wcslen(SafeCast(nts)); - } - static size_t StrNLen(const T* ptr, size_t len) // Wide CRT strnlen. - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION UNICODEBINDING_H_SECTION_1 - #include AZ_RESTRICTED_FILE(UnicodeBinding_h) -#endif - return ::wcsnlen(SafeCast(ptr), len); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION UNICODEBINDING_H_SECTION_2 - #include AZ_RESTRICTED_FILE(UnicodeBinding_h) -#endif - } - }; - - // void Feed(const SPackedIterators &its, Sink &out, tag): - // Feeds the provided sink from provided packed iterator-range. - template - inline void Feed(const SPackedIterators& its, Sink& out, integral_constant) - { - typedef typename std::iterator_traits::value_type UnboundCharType; - typedef typename SBindCharacter::type BoundCharType; - for (InputIteratorType it = its.begin; it != its.end; ++it) - { - const UnboundCharType unbound = *it; - const BoundCharType bound = static_cast(unbound); - const uint32 item = static_cast(bound); - out(item); - } - } - - // void Feed(const SPackedIterators &its, Sink &out, tag): - // Feeds the provided sink from provided packed pointer-range. - // This is slightly better code-generation than using generic iterators. - template - inline void Feed(const SPackedIterators& its, Sink& out, integral_constant) - { - typedef typename SBindPointer::type PointerType; - assert(reinterpret_cast(its.begin) <= reinterpret_cast(its.end) && "Invalid range specified"); - const size_t length = its.end - its.begin; - PointerType ptr = SafeCast(its.begin); - assert((ptr || !length) && "Passed a non-empty range containing a null-pointer"); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast(*ptr); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a container, using it's iterators. - // Note: Dispatches to one of the packed-range overloads. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant tag) - { - typedef typename InputStringType::const_iterator IteratorType; - Detail::SPackedIterators its(in.begin(), in.end()); - Feed(its, out, tag); - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a string-object's buffer. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - typedef typename InputStringType::size_type SizeType; - typedef typename InputStringType::value_type ValueType; - typedef typename SBindPointer::type PointerType; - const SizeType length = in.size(); - if (length) - { - PointerType ptr = SafeCast(in.data()); - for (SizeType i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast(*ptr); - out(item); - } - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a string-literal. - // Note: The literal is assumed to be null-terminated. - // It's possible that a const-element fixed-size-buffer is mistaken as a literal. - // However, we expect no-one uses such buffers that are not null-terminated already. - // If somehow this use-case is desired, either terminate the buffer, or remove const from the buffer, or pass iterators. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - typedef typename SBindPointer::type PointerType; - const size_t length = extent::value - 1; - PointerType ptr = SafeCast(in); - assert(ptr[length] == 0 && "Literal is not null-terminated"); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast(*ptr); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a non-const-element fixed-size buffer. - // Note: The buffer is allowed to be null-terminated, but it's not required. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - typedef typename SBindPointer::type PointerType; - typedef typename SBindPointer::BoundCharType CharType; - const size_t length = extent::value; - PointerType ptr = SafeCast(in); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const CharType unbound = *ptr; - if (unbound == 0) - { - break; - } - const uint32 item = static_cast(unbound); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a null-terminated C-style string. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_pointer::value); - typedef typename SBindPointer::type PointerType; - typedef typename SBindPointer::BoundCharType CharType; - PointerType ptr = SafeCast(in); - if (ptr) - { - while (true) - { - const CharType unbound = *ptr; - ++ptr; - if (unbound == 0) - { - break; - } - const uint32 item = static_cast(unbound); - out(item); - } - } - } - - // void Feed(const InputCharType &in, Sink &out, tag): - // Feeds the provided sink from a single value (interpreted as an UCS code-point). - template - inline void Feed(const InputCharType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - const uint32 item = static_cast(in); - out(item); - } - - // size_t EncodedLength(const SPackedIterators &its, tag): - // Determines the length of the input sequence in a range of iterators. - template - inline size_t EncodedLength(const SPackedIterators& its, integral_constant) - { - return std::distance(its.begin, its.end); // std::distance will pick optimal implementation depending on iterator category. - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of an input container, which would otherwise be enumerated with iterators. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - return in.size(); // Can there be a container without size()? At the very least, not in the supported types. - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input container. The container uses contiguous element layout. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - return in.size(); - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input string-literal. This is a compile-time constant. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - return extent::value - 1; - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input fixed-size-buffer. We look for an (optional) null-terminator in the buffer. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - typedef typename remove_extent::type CharType; - return SCharacterTrait::StrNLen(in, extent::value); - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input used-specified buffer. We look for an (optional) null-terminator in the buffer. - template - inline size_t EncodedLength(const SPackedBuffer& in, integral_constant) - { - return in.buffer ? SCharacterTrait::StrNLen(in.buffer, in.size) : 0; - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input null-terminated c-style string. We just use strlen() if available. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_pointer::value); - typedef typename remove_pointer::type CharType; - return in ? SCharacterTrait::StrLen(in) : 0; - } - - // size_t EncodedLength(const InputCharType &in, tag): - // Determines the length of a single UCS code-point. This is always 1. - template - inline size_t EncodedLength([[maybe_unused]] const InputCharType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - return 1; - } - - // const void *EncodedPointer(const SPackedIterators &its, tag): - // Get a pointer to contiguous storage for an iterator range. - // Note: This can only work if the iterators are pointers, or the storage won't be guaranteed contiguous. - template - inline const void* EncodedPointer(const SPackedIterators& its, integral_constant) - { - return its.begin; - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for string/vector object. - // Note: This can only work for containers that actually use contiguous storage, which is determined by the SBindXXX helpers. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - return in.data(); - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a string-literal. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - return in; // We can just let the array type decay to a pointer. - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a fixed-size-buffer. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - return in; // We can just let the array type decay to a pointer. - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a null-terminated c-style-string. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_pointer::value); - return in; // Implied - } - - // const void *EncodedPointer(const InputCharType &in, tag): - // Get a pointer to contiguous storage for a single UCS code-point. - template - inline const void* EncodedPointer(const InputCharType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - return ∈ // Take the address of the parameter (which is kept on the stack of the caller). - } - - // SWriteSink: - // A helper that performs writing to the type T and can be passed as Sink type to a trans-coder helper. - template - struct SWriteSink; - template - struct SWriteSink - { - typedef typename T::value_type OutputCharType; - T& out; - SWriteSink(T& _out, size_t) - : out(_out) - { - if (!Append) - { - // If not appending, clear the object beforehand. - out.clear(); - } - } - void operator()(uint32 item) - { - const OutputCharType bound = static_cast(item); - out.push_back(bound); // We assume this can't fail and STL container takes care of memory. - } - void operator()(const void*, size_t); // Not implemented. - void HintSequence(uint32 length) {} // Don't care about sequences. - bool CanWrite() const { return true; } // Always writable - }; - template - struct SWriteSink - { - typedef SBindPointer BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - CharType* ptr; - SWriteSink(T& out, size_t length) - { - const size_t offset = Append ? out.size() : 0; - length += offset; - out.resize(length); // resize() can't fail without exceptions, so assert instead. - assert((out.size() == length) && "Buffer resize failed (out-of-memory?)"); - const CharType* base = length ? out.data() : 0; - ptr = const_cast(base + offset); - } - void operator()(uint32 item) - { - *SafeCast(ptr) = static_cast(item); - ++ptr; - } - void operator()(const void* src, size_t length) - { - ::memcpy(ptr, src, length * sizeof(CharType)); - ptr += length; - } - void HintSequence([[maybe_unused]] uint32 length) {} // Don't care about sequences. - bool CanWrite() const { return true; } // Always writable - }; - template - struct SWriteSink, Append, eBind_PackedBuffer> - { - typedef typename remove_pointer

::type ElementType; - typedef SBindPointer BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - CharType* ptr; - CharType* const terminator; - SWriteSink(CharType* _terminator) - : terminator(_terminator) {} - SWriteSink(SPackedBuffer

& out, size_t) - : terminator(out.size && out.buffer ? out.buffer + out.size - 1 : 0) - { - const size_t offset = Append - ? EncodedLength(out, integral_constant()) - : 0; - const size_t fixedOffset = Append && offset >= out.size - ? out.size - 1 // In case the buffer is already full and not terminated. - : offset; - CharType* base = static_cast(out.buffer); - ptr = terminator ? base + fixedOffset : 0; - } - ~SWriteSink() - { - if (ptr) - { - *ptr = 0; // Guarantees that the output is null-terminated. - } - } - void operator()(uint32 item) - { - if (ptr != terminator) // Guarantees we don't overflow the buffer. - { - *SafeCast(ptr) = static_cast(item); - ++ptr; - } - } - void operator()(const void* src, size_t length) - { - const size_t maxLength = terminator - ptr; - if (length > maxLength) - { - length = maxLength; - } - ::memcpy(ptr, src, length * sizeof(CharType)); - ptr += length; - } - void HintSequence(uint32 length) - { - if (terminator && (ptr + length >= terminator)) - { - // This sequence will overflow the buffer. - // In this case, we prefer to not generate any part of the sequence. - // Terminate at the current position and flag as full. - *ptr = 0; - ptr = terminator; - } - } - bool CanWrite() const - { - return terminator != ptr; - } - }; - template - struct SWriteSink // Uses above implementation with specialized constructor - : SWriteSink::type*>, Append, eBind_PackedBuffer> - { - typedef typename remove_extent::type ElementType; - typedef SWriteSink, Append, eBind_PackedBuffer> Super; - typedef SBindPointer BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - SWriteSink(T& out, size_t) - : Super(out + extent::value - 1) - { - const size_t offset = Append - ? EncodedLength(out, integral_constant()) - : 0; - const size_t fixedOffset = Append && offset >= extent::value - ? extent::value - 1 // In case the buffer is already full and not terminated. - : offset; - Super::ptr = out + fixedOffset; // Qualification for Super required for two-phase lookup. - } - }; - - // SIsBlockCopyable: - // Check if block-copy optimization is possible for these types. - // InputType should be an instantiation of SBindObject or SBindIterator. - // OutputType should be an instantiation of SBindOutput. - // Note: This doesn't take into account safe/unsafe conversions, just if the underlying storage types are compatible. - template - struct SIsBlockCopyable - { - template - struct SIsContiguous - { - static const bool value = - M == eBind_Data || - M == eBind_Literal || - M == eBind_Buffer || - M == eBind_PackedBuffer || - M == eBind_NullTerminated || - M == eBind_CodePoint; - }; - template - struct SIsPointers - { - static const bool value = false; - }; - template - struct SIsPointers > - { - static const bool value = true; - }; - typedef typename SBindCharacter::type InputCharType; - typedef typename SBindCharacter::type OutputCharType; - static const bool isIntegral = is_integral::value && is_integral::value; - static const bool isSameSize = sizeof(InputCharType) == sizeof(OutputCharType); - static const bool isInputContiguous = (SIsContiguous::value || SIsPointers::value); - static const bool isOutputContiguous = (SIsContiguous::value || SIsPointers::value); - static const bool value = isIntegral && isSameSize && isInputContiguous && isOutputContiguous; - }; - } -} diff --git a/Code/Legacy/CryCommon/UnicodeEncoding.h b/Code/Legacy/CryCommon/UnicodeEncoding.h deleted file mode 100644 index a3e20b639c..0000000000 --- a/Code/Legacy/CryCommon/UnicodeEncoding.h +++ /dev/null @@ -1,767 +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 : Generic Unicode encoding helpers. -// -// Defines encoding and decoding functions used by the higher-level functions. -// These are used by the various conversion functions in UnicodeFunctions.h and UnicodeIterator.h. -// Note: You can use these functions manually for low-level functionality, but we don't recommend that. -// In that case, you probably want to check inside the nested Detail namespace for the elementary bits. - - -#pragma once -#include "BaseTypes.h" // For uint8, uint16, uint32 -#include "CompileTimeAssert.h" // For COMPILE_TIME_ASSERT macro -namespace Unicode -{ - // Supported encoding/conversion types. - enum EEncoding - { - // UTF-8 encoding, see http://www.unicode.org/resources/utf8.html. - // Input and output are supported. - // Note: This format maps the entire UCS, where each code-point can take [1, 4] 8-bit code-units. - // Note: This is a strict super-set of Latin1/ISO-885901 as well as ASCII. - eEncoding_UTF8, - - // UTF-16 encoding, see http://tools.ietf.org/html/rfc2781. - // Input and output are supported. - // Note: This format maps the entire UCS, where each code-point can take [1, 2] 16-bit code-units. - eEncoding_UTF16, - - // UTF-32 encoding, see http://www.unicode.org/reports/tr17/. - // Input and output are supported. - // Note: This format maps the entire UCS, each code-point is stored in a single 32-bit code-unit. - eEncoding_UTF32, - - // ASCII encoding, see http://en.wikipedia.org/wiki/ASCII. - // Input and output are supported (any output UCS values out of supported range are mapped to question mark). - // Note: Only values [U+0000, U+007F] can be mapped. - eEncoding_ASCII, - - // Latin1, aka ISO-8859-1 encoding, see http://en.wikipedia.org/wiki/ISO/IEC_8859-1. - // Only input is supported. - // Note: This is a strict super-set of ASCII, it additionally maps [U+00A0, U+00FF]. - eEncoding_Latin1, - - // Windows ANSI codepage 1252, see http://en.wikipedia.org/wiki/Windows-1252. - // Only input is supported. - // Note: This is a strict super-set of ASCII and Latin1/ISO-8859-1, it maps some code-units from [0x80, 0x9F]. - eEncoding_Win1252, - }; - - // Methods of recovery from invalid encoded sequences. - enum EErrorRecovery - { - // No attempt to detect invalid encoding is performed, the input is assumed to be valid. - // If the input is not valid, the output is undefined (in debug, this condition will cause an assert to trigger). - eErrorRecovery_None, - - // When an invalidly encoded sequence is detected, the sequence is discarded (will not be part of the output). - // Typically used for logic/hashing purposes when the input is almost certainly valid. - eErrorRecovery_Discard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the replacement-character (U+FFFD). - // Typically used when the output sequence is used for UI display purposes. - eErrorRecovery_Replace, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Latin1 equivalent. - // If the sequence is also not valid Latin1 encoded, the sequence is discarded. - // Typically used when reading generic text files with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackLatin1ThenDiscard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Win1252 equivalent. - // If the sequence is also not valid codepage 1252 encoded, the sequence is discarded. - // Typically used when reading text files generated on Windows with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackWin1252ThenDiscard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Latin1 equivalent. - // If the sequence is also not valid Latin1 encoded, it is replaced with the replacement-character (U+FFFD). - // Typically used when reading generic text files with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackLatin1ThenReplace, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Win1252 equivalent. - // If the sequence is also not valid codepage 1252 encoded, it is replaced with the replacement-character (U+FFFD). - // Typically used when reading text files generated on Windows with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackWin1252ThenReplace, - }; - - namespace Detail - { - // Decode(state, unit): Decodes a single code-unit of an encoding into an UCS code-point. - // When Safe flag is set, encoding errors are detected so a fall-back encoding or other recovery method can be used. - // Interpret return value as follows: - // < 0x001FFFFF: Decoded codepoint (== return value), call again with next code-unit and clear state. - // < 0x80000000: Intermediate state returned, call again with next code-unit and the returned state. - // >= 0x80000000: Bad encoding detected, up to 16 bits (UTF-16) or 24 bits (UTF-8, last in lower bits) - // contain previous consumed values (does not happen if Safe == false). - template - inline uint32 Decode(uint32 state, uint32 unit); - - // Some constant values used when encoding/decoding. - enum - { - cDecodeShiftRemaining = 26, // Where to store the remaining count in the state. - cDecodeOneRemaining = 1 << cDecodeShiftRemaining, // Remaining value of one. - cDecodeMaskRemaining = 3 << cDecodeShiftRemaining, // All possible remaining bits that can be used. - cDecodeLeadBit = 1 << 22, // All bits up to and including this one are reserved. - cDecodeErrorBit = 1 << 31, // Set if an error occurs during decoding. - cDecodeOverlongBit = 1 << 30, // Set if overlong sequence was used. - cDecodeSurrogateBit = 1 << 29, // Set if surrogate code-point decoded in UTF-8. - cDecodeInvalidBit = 1 << 28, // Set if invalid code-point decoded (U+FFFE/FFFF). - cDecodeSuccess = 0, // Placeholder to indicate no error occurred. - cCodepointMax = 0x10FFFF, // The maximum value of an UCS code-point. - cLeadSurrogateFirst = 0xD800, // The first valid UTF-16 lead-surrogate value. - cLeadSurrogateLast = 0xDBFF, // The last valid UTF-16 lead-surrogate value. - cTrailSurrogateFirst = 0xDC00, // The first valid UTF-16 trail-surrogate value. - cTrailSurrogateLast = 0xDFFF, // The last valid UTF-16 trail-surrogate value. - cReplacementCharacter = 0xFFFD, // The default replacement character. - }; - - // Validate the UTF-8 state of a multi-byte sequence. - // The safe decoder of UTF-8 will call this function when a full potential code-point has been decoded. - // This function is (at most) called for 50% of the decoded UTF-8 code-units, but likely at much lower frequency. - inline uint32 DecodeValidate8(uint32 state) - { - uint32 errorbits = (state >> 8) | cDecodeErrorBit; - state ^= (state & 0x400000) >> 1; // For 3-byte sequences, bit 5 of the lead byte needs to be cleared. - const uint32 cp = - (state & 0x3F) | - ((state & 0x3F00) >> 2) | - ((state & 0x3F0000) >> 4) | - ((state & 0x07000000) >> 6); - if (cp <= cCodepointMax) - { - if (cp >= cLeadSurrogateFirst && cp <= cTrailSurrogateLast) - { - errorbits += cDecodeSurrogateBit; // CESU-8 encoding might have been used. - } - else - { - uint32 minval = 0x80; - minval += (0x00400000 & state) ? 0x800 - 0x80 : 0; - minval += (0x40000000 & state) ? 0x10000 - 0x80 : 0; - if (cp >= minval) - { - if ((cp & 0xFFFFFFFEU) != 0xFFFEU) - { - return cp; // Valid code-point. - } - errorbits += cDecodeInvalidBit; // Invalid character used. - } - errorbits += cDecodeOverlongBit; // Overlong encoding used. - } - } - return errorbits; - } - - // Decode UTF-8, unsafe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - if (state == 0) // First byte. - { - unit = unit & 0xFF; - if (unit < 0xC0) - { - return unit; // Single-unit (ASCII). - } - uint32 remaining = (unit >> 4) - 0xC; - remaining += (remaining == 0); - return (unit & 0x1F) + (remaining << cDecodeShiftRemaining); // Lead byte of multi-byte. - } - state = (state << 6) + (unit & 0x3F) + (state & cDecodeMaskRemaining) - cDecodeOneRemaining; // Apply c-byte. - return state & ~cDecodeLeadBit; // Mask off the lead bits of a 4-byte sequence. - } - - // Decode UTF-8, safe - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - if (unit <= 0xF4) // Discard out-of-range values immediately. - { - if (state == 0) // First byte. - { - if (unit < 0x80) - { - return unit; // Single-byte. - } - if (unit < 0xC2) - { - return cDecodeErrorBit; // Invalid continuation byte (or illegal 0xC0/0xC1). - } - uint32 remaining = (unit >> 4) - 0xC; - remaining += (remaining == 0); - return unit + (remaining << cDecodeShiftRemaining); // Multi-byte. - } - if ((unit & 0xC0) == 0x80) - { - const uint32 remaining = (state & cDecodeMaskRemaining) - cDecodeOneRemaining; - state = (state << 8) + unit; - if (remaining != 0) - { - return state | remaining; // Intermediate byte of a multi-byte sequence. - } - return DecodeValidate8(state); // Final byte of a multi-byte sequence. - } - } - return cDecodeErrorBit | state; - } - - // Decode UTF-16, unsafe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - const bool bLead = (unit >= cLeadSurrogateFirst) && (unit <= cLeadSurrogateLast); - const uint32 initial = unit + (bLead << cDecodeShiftRemaining); - const uint32 pair = 0x10000 + ((state & 0x3FF) << 10) + (unit & 0x3FF); - return state == 0 ? initial : pair; - } - - // Decode UTF-16, safe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - const bool bTrail = (unit >= cTrailSurrogateFirst) && (unit <= cTrailSurrogateLast); - if (state != 0 && !bTrail) - { - return cDecodeErrorBit + (state & 0xFFFF); // Lead surrogate without trail surrogate - } - uint32 result = Decode(state, unit); - bool bValid = (result & 0xFFFFFFFEU) != 0xFFFEU; - return bValid ? result : result + cDecodeErrorBit + cDecodeInvalidBit; - } - - // Decode UTF-32, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode UTF-32, safe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - if (unit > cCodepointMax) - { - return cDecodeErrorBit; - } - if (unit >= cLeadSurrogateFirst && unit <= cTrailSurrogateLast) - { - return cDecodeErrorBit | cDecodeSurrogateBit; - } - if ((unit & 0xFFFEU) == 0xFFFEU) - { - return cDecodeErrorBit | cDecodeInvalidBit; - } - return unit; - } - - // Decode ASCII, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode ASCII, safe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - if (unit > 0x7F) - { - return cDecodeErrorBit; - } - return unit; - } - - // Decode Latin1, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode Latin1, safe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - if ((unit >= 0x80 && unit <= 0x9F) || (unit > 0xFF)) - { - return cDecodeErrorBit; - } - return unit; - } - - // Decode Windows CP-1252, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - static const uint16 cp1252[] = - { - 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, - 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, - 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, - 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, - }; - return (unit < 0x80 || unit > 0x9F) ? unit : cp1252[unit - 0x80]; - } - - // Decode Windows CP-1252, safe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - if (unit > 0xFF) - { - return cDecodeErrorBit; - } - uint32 result = Decode(state, unit); - if (!(unit < 0x80 || unit > 0x9F) && (result == unit)) - { - return cDecodeErrorBit; // Not defined in codepage 1252. - } - return result; - } - - // SBase: - // Utility to apply empty-base-optimization on type T. - // Will fall back to a member if T is a reference type. - template - struct SBase - : T - { - SBase(T base) - : T(base) {} - T& GetBase() { return *this; } - const T& GetBase() const { return *this; } - }; - template - struct SBase - { - T& base; - SBase(T& b) - : base(b) {} - T& GetBase() { return base; } - const T& GetBase() const { return base; } - }; - - // SDecoder: - // Functor to decode UCS code-points from an input range. - // Recovery functor will be invoked as a fall-back if decoding fails. - // This allows ensuring all the output is valid (even if the input isn't). - // Note: The destructor will automatically flush any remaining (erroneous) state, you can also call Finalize(). - template - struct SDecoder - : SBase - , SBase - { - uint32 state; - SDecoder(Sink sink, Recovery recovery = Recovery()) - : SBase(sink) - , SBase(recovery) - , state(0) {} - SDecoder() { Finalize(); } - Recovery& recovery() { return SBase::GetBase(); } - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 unit) - { - state = Detail::Decode(state, unit); - if (state <= 0x1FFFFF) - { - sink()(state); - state = 0; - } - else if (state & Detail::cDecodeErrorBit) - { - recovery()(sink(), state, unit); - state = 0; - } - } - void Finalize() - { - if (state) - { - recovery()(sink(), state, 0); - state = 0; - } - } - }; - - // SDecoder: - // Functor to decode to UCS code-points from an input range. - // No attempt to discover or recover from encoding errors is made, can only safely be used with known-valid input. - template - struct SDecoder - : SBase - { - uint32 state; - SDecoder(Sink sink) - : SBase(sink) - , state(0) {} - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 unit) - { - state = Detail::Decode(state, unit); - if (state <= 0x1FFFFF) - { - sink()(state); - state = 0; - } - } - void Finalize() {} - }; - - // SEncoder: - // Generic Unicode encoder functor. - // Encoding must be one an encoding type for which output is supported. - // The Sink type must have HintSequence member for UTF-8 and UTF-16 (although it may be a no-op). - // In general, you feed operator() with UCS code-points and it will emit code-units. - template - struct SEncoder - { - static const bool value = false; - }; - - // SEncoder: - // Specialization of ASCII encoder functor. - // Note: Any out-of-range character is mapped to question mark. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint8 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - void operator()(uint32 cp) - { - cp = cp < 0x80 ? cp : (uint32)'?'; - SBase::GetBase()(value_type(cp)); - } - }; - - // SEncoder: - // Specialization of UTF-8 encoder functor. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint8 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 cp) - { - if (cp < 0x80) - { - // Single byte sequence. - sink()(value_type(cp)); - } - else - { - // Expand 21-bit value to 32-bit. - uint32 bits = - (cp & 0x00003F) + - ((cp & 0x000FC0) << 2) + - ((cp & 0x03F000) << 4) + - ((cp & 0x1C0000) << 6); - - // Type of sequence. - const bool bSeq4 = (cp >= 0x10000); - const bool bSeq3 = (cp >= 0x800); - - // Mask lead-bytes and continuation-bytes. - uint32 mask = 0xEFE0C080; - mask ^= (bSeq3 << 14); - mask += (bSeq4 ? 0xA00000 : 0); - bits |= mask; - - // Length of the sequence. - const uint32 length = (uint32)bSeq4 + (uint32)bSeq3 + 1; - sink().HintSequence(length); - - // Sink the multi-byte sequence. - if (bSeq4) - { - sink()(value_type(bits >> 24)); - } - if (bSeq3) - { - sink()(value_type(bits >> 16)); - } - sink()(value_type(bits >> 8)); - sink()(value_type(bits)); - } - } - }; - - // SEncoder: - // Specialization of UTF-16 encoder functor. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint16 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 cp) - { - if (cp < 0x10000) - { - // Single unit - sink()(value_type(cp)); - } - else - { - // We will generate two-element sequence - sink().HintSequence(2); - - // Surrogate pair - cp -= 0x10000; - uint32 lead = ((cp >> 10) & 0x3FF) + Detail::cLeadSurrogateFirst; - uint32 trail = (cp & 0x3FF) + Detail::cTrailSurrogateFirst; - sink()(value_type(lead)); - sink()(value_type(trail)); - } - } - }; - - // SEncoder: - // Specialization of UTF-32 encoder functor. - // Note: This is a no-op, but we want to be able to express UTF-32 just like the other encodings. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint32 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - void operator()(uint32 cp) - { - SBase::GetBase()(value_type(cp)); - } - }; - - // SDecoder, void>: - // Specialization for unsafe no-op trans-coding. - // Since the conversion is a no-op, no need to keep any state or do any computation. - // Note: For a decoding with a fallback, this is not possible since we can't guarantee the input is valid. - template - struct SDecoder, void> - { - Sink sink; - SDecoder(Sink s) - : sink(s) {} - void operator()(uint32 unit) - { - sink(unit); - } - void Finalize() {} - }; - - // SRecoveryDiscard: - // Recovery handler that, on encoding error, discards the offending sequence. - template - struct SRecoveryDiscard - { - SRecoveryDiscard() {} - void operator()([[maybe_unused]] Sink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) {} - }; - - // SRecoveryReplace: - // Recovery handler that, on encoding error, replaces the sequence with replacement-character (U+FFFD). - // Note: This implementation matches a whole invalid sequence, it could be changed to emit for every code-unit. - template - struct SRecoveryReplace - { - SRecoveryReplace() {} - void operator()(Sink& sink, uint32 error, uint32 unit) { sink(cReplacementCharacter); } - }; - - // SRecoveryFallback: - // Recovery handler that, on encoding error, falls back to another encoding. - // The fallback encoding must be stateless (ie: ASCII, Latin1 or Win1252). - // This type assumes an 8-bit primary encoding since the only viable fallback encodings are 8-bit. - template - struct SRecoveryFallback - : NextFallback - { - SRecoveryFallback() - : NextFallback() {} - void operator()(Sink& sink, uint32 error, uint32 unit) - { - SDecoder fallback(sink, *static_cast(this)); - uint8 byte1(error >> 16); - uint8 byte2(error >> 8); - uint8 byte3(error); - uint8 byte4(unit); - if (byte1) - { - fallback(byte1); - } - if (byte1 | byte2) - { - fallback(byte2); - } - if (byte1 | byte2 | byte3) - { - fallback(byte3); - } - fallback(byte4); - } - }; - - // SRecoveryFallbackHelper: - // Helper to pick a SRecoveryFallback instantiation based on RecoveryMethod. - template - struct SRecoveryFallbackHelper - { - // A compilation error here means RecoveryMethod value was unexpected here - COMPILE_TIME_ASSERT( - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace || - RecoveryMethod == eErrorRecovery_FallbackWin1252ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackWin1252ThenReplace); - typedef SEncoder SinkType; - static const EEncoding FallbackEncoding = - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace - ? eEncoding_Latin1 : eEncoding_Win1252; - template - struct Pick - { - typedef SRecoveryDiscard type; - }; - template - struct Pick - { - typedef SRecoveryReplace type; - }; - typedef typename Pick::type NextFallback; - typedef SRecoveryFallback RecoveryType; - typedef SDecoder FullType; - }; - - // STranscoderSelect: - // Derives a chained decoder/encoder pair that performs code-unit -> code-unit transform. - // The RecoveryMethod template parameter determines the behavior during encoding. - // This is the basic way to perform trans-coding, and is the type instantiated by the higher-level functions. - template - struct STranscoderSelect; - template - struct STranscoderSelect - : SDecoder, void> - { - typedef SDecoder, void> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SDecoder, SRecoveryDiscard > > - { - typedef SRecoveryDiscard > RecoveryType; - typedef SDecoder, RecoveryType> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SDecoder, SRecoveryReplace > > - { - typedef SRecoveryReplace > RecoveryType; - typedef SDecoder, RecoveryType> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackLatin1ThenDiscard; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackLatin1ThenReplace; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackWin1252ThenDiscard; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackWin1252ThenReplace; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - - // SIsSafeEncoding: - // Check if the given recovery mode is safe. - // This is used for SFINAE checks in higher-level functions. - template - struct SIsSafeEncoding - { - static const bool value = - R == eErrorRecovery_Discard || - R == eErrorRecovery_Replace || - R == eErrorRecovery_FallbackLatin1ThenDiscard || - R == eErrorRecovery_FallbackLatin1ThenReplace || - R == eErrorRecovery_FallbackWin1252ThenDiscard || - R == eErrorRecovery_FallbackWin1252ThenReplace; - }; - - // SIsCopyableEncoding: - // Check if data in one encoding can be copied directly to another encoding. - // This is the basis for block-copy and string-assign optimizations in un-safe conversion functions. - // Note: There are more valid combinations, they are left out since those can't occur with the output encodings supported. - // Note: Only used for un-safe functions since it doesn't account for potential invalid sequences (they would be copied over). - template - struct SIsCopyableEncoding - { - static const bool value = - InputEncoding == eEncoding_ASCII || // ASCII and Latin1 values don't change in any encoding. - (InputEncoding == eEncoding_Latin1 && OutputEncoding != eEncoding_ASCII); // Except Latin1 -> ASCII is lossy. - }; - template - struct SIsCopyableEncoding - { - static const bool value = true; // If the input and output encodings are the same, then it's copyable. - }; - } -} diff --git a/Code/Legacy/CryCommon/UnicodeFunctions.h b/Code/Legacy/CryCommon/UnicodeFunctions.h deleted file mode 100644 index 48debe9706..0000000000 --- a/Code/Legacy/CryCommon/UnicodeFunctions.h +++ /dev/null @@ -1,1265 +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 - * - */ - - -// Generic Unicode string functions. -// -// Implements the following functions: -// Analyze: Reports all information on the input string, (length for all encodings, validity- and non-ASCII flags). -// Validate: Checks if the input string is valid encoded. -// Length: Reports the encoded length of some known-valid input, as-if it was encoded in the given output encoding. -// LengthSafe: Reports the encoded length of some input, as-if it was encoded in the given output encoding/recovery. -// Convert: Converts input from a known-valid string type/encoding to another string type/encoding. -// ConvertSafe: Converts and recovers encoding errors from one string type/encoding to another string type/encoding. -// Append: Appends input from a known-valid string type/encoding to another string type/encoding. -// AppendSafe: Appends and recovers encoding errors from one string type/encoding to another string type/encoding. -// -// Note: Ideally the safe functions should be used only once when accepting input from the user or from a file. -// Afterwards, the content is known-safe and the unsafe functions can be used for optimal performance. -// Using ConvertSafe once with a reasonable fall-back (depending on the where the input is from) should be the goal. -// -// Each function has several overloads: -// - One variant to handle a string object / buffer / pointer (1 arg), and one to handle iterators (2 args). -// - One variant with automatic encoding (picks UTF encoding depending on character size), and one for specific encoding. -// - One variant that returns a new string, and one that takes an existing string to overwrite (Convert(Safe) only). -// Each function takes one default argument that employs SFINAE to pick the correct overload depending on the arguments. - - -#pragma once -#include "UnicodeBinding.h" -namespace Unicode -{ - // Results of analysis of an input range of code-units (in any encoding). - // This is returned by calling Analyze() function. - struct SAnalysisResult - { - // The type to use for counting units. - // Can be changed to uint64_t for dealing with 4GB+ of string data. - typedef uint32 size_type; - - size_type inputUnits; // The number of input units analyzed. - size_type outputUnits8; // The number of output units when encoded with UTF-8. - size_type outputUnits16; // The number of output units when encoded with UTF-16. - size_type outputUnits32; // The number of output units when encoded with UTF-32 (aka number of UCS code-points). - size_type cpNonAscii; // The number of non-ASCII UCS code-points encountered. - size_type cpInvalid; // The number of invalid UCS code-point encountered (or 0xFFFFFFFF if not available). - - // Default constructor, initialize everything to zero. - SAnalysisResult() - : inputUnits(0) - , outputUnits8(0) - , outputUnits16(0) - , outputUnits32(0) - , cpInvalid(0) - , cpNonAscii(0) {} - - // Check if the input range was empty. - bool IsEmpty() const { return inputUnits == 0; } - - // Check if the input range only contained ASCII characters. - bool IsAscii() const { return cpNonAscii == 0; } - - // Check if the input range was valid (has no encoding errors). - // Note: This returns false if an unsafe decoder was used for analysis. - bool IsValid() const { return cpInvalid == 0; } - - // Get the length of the input range, in source code-units. - size_type LengthInSourceUnits() const { return inputUnits; } - - // Get the length of the input range, in UCS code-points. - size_type LengthInUCS() const { return outputUnits32; } - - // Get the length of the input range when encoded with the given encoding, in code-units. - // Note: If the encoding is not supported for output, the function returns 0. - size_type LengthInEncodingUnits(EEncoding encoding) const - { - switch (encoding) - { - case eEncoding_ASCII: - case eEncoding_UTF32: - return outputUnits32; - case eEncoding_UTF16: - return outputUnits16; - case eEncoding_UTF8: - return outputUnits8; - default: - return 0; - } - } - - // Get the length of the input range when encoded with the given encoding, in bytes. - // Note: If the encoding is not supported for output, the function returns 0. - size_type LengthInEncodingBytes(EEncoding encoding) const - { - size_type units = LengthInEncodingUnits(encoding); - switch (encoding) - { - case eEncoding_UTF32: - return units << 2; - case eEncoding_UTF16: - return units << 1; - default: - return units; - } - } - }; - - namespace Detail - { - // SDummySink: - // A sink implementation that does nothing. - struct SDummySink - { - void operator()([[maybe_unused]] uint32 unit) {} - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SCountingSink: - // A sink that counts the number of units of output. - struct SCountingSink - { - size_t result; - - SCountingSink() - : result(0) {} - void operator()([[maybe_unused]] uint32 unit) { ++result; } - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SAnalysisSink: - // A sink that updates analysis statistics. - struct SAnalysisSink - { - SAnalysisResult& result; - - SAnalysisSink(SAnalysisResult& _result) - : result(_result) {} - void operator()(uint32 cp) - { - const bool isCat2 = cp >= 0x80; - const bool isCat3 = cp >= 0x800; - const bool isCat4 = cp >= 0x10000; - result.outputUnits32 += 1; - result.outputUnits16 += (1 + isCat4); - result.outputUnits8 += (1 + isCat4 + isCat3 + isCat2); - result.cpNonAscii += isCat2; - } - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SAnalysisRecovery: - // A recovery helper for analysis that counts invalid sequences. - struct SAnalysisRecovery - { - SAnalysisRecovery() {} - void operator()(SAnalysisSink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) - { - sink.result.cpInvalid += 1; - } - }; - - // SValidationRecovery: - // A recovery helper for validation, it tracks if there is any invalid sequence. - struct SValidationRecovery - { - bool isValid; - - SValidationRecovery() - : isValid(true) {} - void operator()([[maybe_unused]] SDummySink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) - { - isValid = false; - } - }; - - // SAnalyzer: - // Helper to perform analysis, counts the input for a given encoding. - template - struct SAnalyzer - { - SDecoder decoder; - - SAnalyzer(SAnalysisResult& result) - : decoder(result) {} - void operator()(uint32 item) - { - decoder.sink().result.inputUnits += 1; - decoder(item); - } - }; - - // Analyze(target, source): - // Analyze string and store analysis result. - // This is the generic function called by other Analyze overloads. - template - inline void Analyze(SAnalysisResult& target, const InputStringType& source) - { - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // Analyze using helper. - SAnalyzer analyzer(target); - Feed(source, analyzer, tag); - } - - // Validate(source): - // Tests that the string is valid encoding. - // This is the generic function called by other Validate overloads. - template - inline bool Validate(const InputStringType& source) - { - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // Validate using helper. - SDummySink sink; - SDecoder validator(sink); - Feed(source, validator, tag); - return validator.recovery().isValid; - } - - // Length(str): - // Find length of a string (in code-units) after trans-coding from InputEncoding to OutputEncoding. - // This is the generic function called by the other Length overloads. - template - inline size_t Length(const InputStringType& source) - { - // If this assert hits, consider using LengthSafe. - assert((Detail::Validate(source)) && "Length was used with non-safe input"); - - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // All copyable encodings have the property that the number of input encoding units equals the output units. - // In addition, this also holds for UTF-32 (always 1) -> ASCII (always 1), even though it's lossy. - const bool isCopyable = SIsCopyableEncoding::value; - const bool isCountable = isCopyable || (InputEncoding == eEncoding_UTF32 && OutputEncoding == eEncoding_ASCII); - - if (isCountable) - { - // Optimization: The number of input units is equal to the number of output units. - return EncodedLength(source, tag); - } - else - { - // We need to perform the conversion. - SCountingSink sink; - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - return sink.result; - } - } - - // LengthSafe(str): - // Find length of a string (in code-units) after trans-coding from InputEncoding to OutputEncoding. - // Note: The Recovery type used during conversion may influence the result, so this needs to match if you use the length information. - // This is the generic function called by the other LengthSafe overloads. - template - inline size_t LengthSafe(const InputStringType& source) - { - // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding::value); - - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // We can't optimize here, since we cannot assume the input is validly encoded - SCountingSink sink; - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - return sink.result; - } - - // SBlockCopy: - // Helper for block-copying entire string at once (as an optimization) - // This optimization will effectively try to memcpy or assign the whole string at once. - // Note: We need to do some partial specialization here to find out if the optimization is valid, so we can't use a function in C++98. - template - struct SBlockCopy - { - static const EBind bindMethod = SBindObject::value; - typedef integral_constant TagType; - size_t operator()(OutputStringType& target, const InputStringType& source) - { - // Optimization: Use block copying for these types. - TagType tag; - const size_t length = EncodedLength(source, tag); - SinkType sink(target, length); - if (sink.CanWrite()) - { - const void* const dataPtr = EncodedPointer(source, tag); - sink(dataPtr, length); - } - return length; - } - }; - - // SBlockCopy: - // Specialization that will use direct string assignment. - // Note: This optimization is not selected when appending, this could be a future optimization if this is common. - // Reason for this is that the += operator is not present on all supported types (ie, std::vector) - template - struct SBlockCopy - { - size_t operator()(SameStringType& target, const SameStringType& source) - { - // Optimization: Use copy assignment. - target = source; - return source.size(); - } - }; - - // SBlockCopy: - // Fall-back specialization for Enable == false. - // Note: This specialization has to exist for the linker, but should never be called (and optimized away). - template - struct SBlockCopy - { - size_t operator()([[maybe_unused]] OutputStringType& target, [[maybe_unused]] const InputStringType& source) - { - assert(false && "Should never be called"); - return 0; - } - }; - - // Convert(target, source): - // Trans-code a string from InputEncoding to OutputEncoding. - // This is the generic function that is called by Convert and Append overloads. - // Returns the number of code-units required for full output (excluding any terminators) - template - inline size_t Convert(OutputStringType& target, const InputStringType& source) - { - // If this assert hits, consider using ConvertSafe. - assert((Detail::Validate(source)) && "Convert was used with non-safe input"); - - // Bind methods. - const EBind inputBindMethod = SBindObject::value; - const EBind outputBindMethod = SBindOutput::value; - integral_constant tag; - typedef SWriteSink SinkType; - - // Check if we can optimize this. - const bool isCopyable = SIsCopyableEncoding::value; - const bool isBlocks = SIsBlockCopyable, SBindOutput >::value; - const bool useBlockCopy = isCopyable && isBlocks; - size_t length; - if (useBlockCopy) - { - // Use optimized path. - SBlockCopy blockCopy; - length = blockCopy(target, source); - } - else - { - // We need to perform the conversion code-unit by code-unit. - length = Detail::Length(source); - SinkType sink(target, length); - if (sink.CanWrite()) - { - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - } - } - return length; - } - - // ConvertSafe(target, source): - // Safely trans-code a string from InputEncoding to OutputEncoding using the specified Recovery to handle encoding errors. - // This is the generic function called by ConvertSafe and AppendSafe overloads. - template - inline size_t ConvertSafe(OutputStringType& target, const InputStringType& source) - { - // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding::value); - - // Bind methods. - const EBind inputBindMethod = SBindObject::value; - const EBind outputBindMethod = SBindOutput::value; - integral_constant tag; - typedef SWriteSink SinkType; - - // We can't optimize with block-copy here, since we cannot assume the input is validly encoded. - const size_t length = Detail::LengthSafe(source); - SinkType sink(target, length); - if (sink.CanWrite()) - { - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - } - return length; - } - - // SReqAutoObj: - // Require that T is usable as input object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoObj - : SRequire< - SBindObject::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAutoIts: - // Require that T is usable as input iterator, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoIts - : SRequire< - SBindIterator::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyObj: - // Require that T is usable as input object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyObj - : SRequire< - SBindObject::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyIts: - // Require that T is usable as input iterator, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyIts - : SRequire< - SBindIterator::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAutoObjOut: - // Require that I is usable as input object, and O as output object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoObjOut - : SRequire< - SBindObject::value != eBind_Impossible&& - SBindOutput, O>::type, true>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAutoItsOut: - // Require that I is usable as input iterator, and O as output object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoItsOut - : SRequire< - SBindIterator::value != eBind_Impossible&& - SBindOutput, O>::type, true>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyObjOut: - // Require that I is usable as input object, and O as output object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyObjOut - : SRequire< - SBindObject::value != eBind_Impossible&& - SBindOutput, O>::type, false>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyItsOut: - // Require that I is usable as input object, and O as output object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyItsOut - : SRequire< - SBindIterator::value != eBind_Impossible&& - SBindOutput, O>::type, false>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - } - - // SAnalysisResult Analyze(str): - // Analyze the given string with the given encoding, providing information on validity and encoding length. - template - inline SAnalysisResult Analyze(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - SAnalysisResult result; - Detail::Analyze(result, str); - return result; - } - - // SAnalysisResult Analyze(str): - // Analyze the (assumed) Unicode string input, providing information on validity and encoding length. - // The Unicode encoding is picked automatically depending on the input type. - template - inline SAnalysisResult Analyze(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - SAnalysisResult result; - Detail::Analyze(result, str); - return result; - } - - // SAnalysisResult Analyze(begin, end): - // Analyze the given range with the given encoding, providing information on validity and encoding length. - template - inline SAnalysisResult Analyze(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - SAnalysisResult result; - Detail::Analyze(result, its); - return result; - } - - // SAnalysisResult Analyze(begin, end): - // Analyze the given (assumed) Unicode range, providing information on validity and encoding length. - // The Unicode encoding is picked automatically depending on the input type. - template - inline SAnalysisResult Analyze(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - SAnalysisResult result; - Detail::Analyze(result, its); - return result; - } - - // bool Validate(str): - // Checks if the given string is valid in the given encoding. - template - inline bool Validate(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - return Detail::Validate(str); - } - - // bool Validate(str): - // Checks if the given string is a valid Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - template - inline bool Validate(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - return Detail::Validate(str); - } - - // bool Validate(begin, end): - // Checks if the given range is valid in the given encoding. - template - inline bool Validate(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Validate(its); - } - - // bool Validate(begin, end): - // Checks if the given range is valid Unicode. - // The Unicode encoding is picked automatically depending on the input type. - template - inline bool Validate(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Validate(its); - } - - // size_t Length(str): - // Get the length (in OutputEncoding) of the given known-valid string with the given InputEncoding. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - return Detail::Length(str); - } - - // size_t Length(str): - // Get the length (in OutputEncoding) of the given known-valid Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - return Detail::Length(str); - } - - // size_t Length(begin, end): - // Get the length (in OutputEncoding) of the known-valid range with the given InputEncoding. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Length(its); - } - - // size_t Length(begin, end): - // Get the length (in OutputEncoding) of the known-valid Unicode range. - // The Unicode encoding is picked automatically depending on the input type. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Length(its); - } - - // size_t LengthSafe(str): - // Get the length (in OutputEncoding) of the given string with the given InputEncoding. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - return Detail::LengthSafe(str); - } - - // size_t LengthSafe(str): - // Get the length (in OutputEncoding) of the given Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - return Detail::LengthSafe(str); - } - - // size_t LengthSafe(begin, end): - // Get the length (in OutputEncoding) of the range with the given InputEncoding. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::LengthSafe(its); - } - - // size_t LengthSafe(begin, end): - // Get the length (in OutputEncoding) of the Unicode range. - // The Unicode encoding is picked automatically depending on the input type. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::LengthSafe(its); - } - - // OutputStringType &Convert(result, str): - // Converts the given string in the given input encoding and stores into the result string with the given output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Convert(result, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Convert(result, begin, end): - // Converts the given range in the given input encoding and stores into the result string with the given output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // OutputStringType &Convert(result, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // size_t Convert(buffer, length, str): - // Converts the given string in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Convert(buffer, length, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Convert(buffer, length, begin, end): - // Converts the given range in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // size_t Convert(buffer, length, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // OutputStringType Convert(str): - // Converts the given string in the given input encoding to a new string of the given type and output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - OutputStringType result; - Detail::Convert(result, str); - return result; - } - - // OutputStringType Convert(str): - // Converts the (assumed) Unicode string input to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - OutputStringType result; - Detail::Convert(result, str); - return result; - } - - // OutputStringType Convert(begin, end): - // Converts the given range in the given input encoding to a new string of the given type and output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::Convert(result, its); - return result; - } - - // OutputStringType Convert(begin, end): - // Converts the (assumed) Unicode range to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::Convert(result, its); - return result; - } - - // OutputStringType &ConvertSafe(result, str): - // Converts the given string in the given input encoding and stores into the result string with the given output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &ConvertSafe(result, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &ConvertSafe(result, begin, end): - // Converts the given range in the given input encoding and stores into the result string with the given output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType &ConvertSafe(result, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // size_t ConvertSafe(buffer, length, str): - // Converts the given string in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t ConvertSafe(buffer, length, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t ConvertSafe(buffer, length, begin, end): - // Converts the given range in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, its) + 1; - } - - // size_t ConvertSafe(buffer, length, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // OutputStringType ConvertSafe(str): - // Converts the given string in the given input encoding to a new string of the given type and output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - OutputStringType result; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType ConvertSafe(str): - // Converts the (assumed) Unicode string input to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - OutputStringType result; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType ConvertSafe(begin, end): - // Converts the given range in the given input encoding to a new string of the given type and output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType ConvertSafe(begin, end): - // Converts the (assumed) Unicode range to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType &Append(result, str): - // Appends the given string in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Append(result, str): - // Appends the (assumed) Unicode string input and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Append(result, begin, end): - // Appends the given range in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // OutputStringType &Append(result, begin, end): - // Appends the (assumed) Unicode range and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // size_t Append(buffer, length, str): - // Appends the given string in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Append(buffer, length, str): - // Appends the (assumed) Unicode string input to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Append(buffer, length, begin, end): - // Appends the given range in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // size_t Append(buffer, length, begin, end): - // Appends the (assumed) Unicode range to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // OutputStringType &AppendSafe(result, str): - // Appends the given string in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &AppendSafe(result, str): - // Appends the (assumed) Unicode string input and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &AppendSafe(result, begin, end): - // Appends the given range in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType &AppendSafe(result, begin, end): - // Appends the (assumed) Unicode range and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // size_t AppendSafe(buffer, length, str): - // Appends the given string in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t AppendSafe(buffer, length, str): - // Appends the (assumed) Unicode string input to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t AppendSafe(buffer, length, begin, end): - // Appends the given range in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, its) + 1; - } - - // size_t AppendSafe(buffer, length, begin, end): - // Appends the (assumed) Unicode range to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } -} diff --git a/Code/Legacy/CryCommon/UnicodeIterator.h b/Code/Legacy/CryCommon/UnicodeIterator.h deleted file mode 100644 index d939eaa721..0000000000 --- a/Code/Legacy/CryCommon/UnicodeIterator.h +++ /dev/null @@ -1,615 +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 : Encoded Unicode sequence iteration. -// -// For lower level accessing of encoded text, an STL compatible iterator wrapper is provided. -// This iterator will decode the underlying sequence, abstracting it to a sequence of UCS code-points. -// Using the iterator wrapper, you can find where in an encoded string code-points (or encoding errors) are located. -// Note: The iterator is an input-only iterator, you cannot write to the underlying sequence. - - -#pragma once -#include "UnicodeBinding.h" -namespace Unicode -{ - namespace Detail - { - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Non-specialized version (for 1:1 code-unit to code-point). - template - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, const integral_constant) - { - COMPILE_TIME_ASSERT( - Encoding == eEncoding_ASCII || - Encoding == eEncoding_UTF32 || - Encoding == eEncoding_Latin1 || - Encoding == eEncoding_Win1252); - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // All of these encodings use a single code-unit for each code-point. - ++it; - } - - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Specialized for UTF-8. - template - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // UTF-8: just need to skip up to 3 continuation bytes. - for (int i = 0; i < 4; ++i) - { - ++it; - if (checker.IsEnd(it)) // :WARN: always returns false if "safe" bool is false! - { - break; - } - uint32 val = static_cast(*it); - if ((val & 0xC0) != 0x80) - { - break; - } - } - } - - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Specialized for UTF-16. - template - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // UTF-16: just need to skip one lead surrogate. - ++it; - uint32 val = static_cast(*it); - if (val >= cLeadSurrogateFirst && val <= cLeadSurrogateLast) - { - if (!checker.IsEnd(it)) - { - ++it; - } - } - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Non-specialized version (for 1:1 code-unit to code-point). - template - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, const integral_constant) - { - COMPILE_TIME_ASSERT( - Encoding == eEncoding_ASCII || - Encoding == eEncoding_UTF32 || - Encoding == eEncoding_Latin1 || - Encoding == eEncoding_Win1252); - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // All of these encodings use a single code-unit for each code-point. - --it; - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Specialized for UTF-8. - template - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // UTF-8: just need to skip up to 3 continuation bytes. - for (int i = 0; i < 4; ++i) - { - --it; - if (checker.IsBegin(it)) - { - break; - } - uint32 val = static_cast(*it); - if ((val & 0xC0) != 0x80) - { - break; - } - } - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Specialized for UTF-16. - template - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // UTF-16: just need to skip one lead surrogate. - --it; - uint32 val = static_cast(*it); - if (val >= cLeadSurrogateFirst && val <= cLeadSurrogateLast) - { - if (!checker.IsBegin(it)) - { - --it; - } - } - } - - // SBaseIterators: - // Utility to access base iterators properties from CIterator. - // This is the bounds-checked specialization, the range information is kept to defend against malformed sequences. - template - struct SBaseIterators - { - typedef BaseIterator type; - type begin, end; - type it; - - SBaseIterators(const BaseIterator& _begin, const BaseIterator& _end) - : begin(_begin) - , end(_end) - , it(_begin) {} - - SBaseIterators(const SBaseIterators& other) - : begin(other.begin) - , end(other.end) - , it(other.it) {} - - SBaseIterators& operator =(const SBaseIterators& other) - { - begin = other.begin; - end = other.end; - it = other.it; - return *this; - } - - bool IsBegin(const BaseIterator& _it) const - { - return begin == _it; - } - - bool IsEnd(const BaseIterator& _it) const - { - return end == _it; - } - - bool IsEqual(const SBaseIterators& other) const - { - return it == other.it - && begin == other.begin - && end == other.end; - } - - // Note: Only called inside assert. - // O(N) version; works with any forward-iterator (or better) - bool IsInRange(const BaseIterator& _it, std::forward_iterator_tag) const - { - for (BaseIterator i = begin; i != end; ++i) - { - if (_it == i) - { - return true; - } - } - return false; - } - - // Note: Only called inside assert. - // O(1) version; requires random-access-iterator. - bool IsInRange(const BaseIterator& _it, std::random_access_iterator_tag) const - { - return (begin <= _it && _it < end); - } - - // Note: Only called inside assert. - // Dispatches to the O(1) version if a random-access iterator is used (common case). - bool IsInRange(const BaseIterator& _it) const - { - return IsInRange(_it, typename std::iterator_traits::iterator_category()); - } - }; - - // SBaseIterators: - // Utility to access base iterators properties from CIterator. - // This is the un-checked specialization for known-safe sequences. - template - struct SBaseIterators - { - typedef BaseIterator type; - type it; - - explicit SBaseIterators(const BaseIterator& begin) - : it(begin) {} - - SBaseIterators(const BaseIterator& begin, const BaseIterator& end) - : it(begin) {} - - SBaseIterators(const SBaseIterators& other) - : it(other.it) {} - - SBaseIterators& operator =(const SBaseIterators& other) - { - it = other.it; - return *this; - } - - bool IsBegin(const BaseIterator&) const - { - return false; - } - - bool IsEnd(const BaseIterator&) const - { - return false; - } - - bool IsEqual(const SBaseIterators& other) const - { - return it == other.it; - } - - bool IsInRange(const BaseIterator&) const - { - return true; - } - }; - - // SIteratorSink: - // Helper to store the last code-point and error bit that was decoded. - // This is the safe specialization for potentially malformed sequences. - template - struct SIteratorSink - { - static const uint32 cEmpty = 0xFFFFFFFFU; - uint32 value; - bool error; - - void Clear() - { - value = cEmpty; - error = false; - } - - bool IsEmpty() const - { - return value == cEmpty; - } - - bool IsError() const - { - return error; - } - - const uint32& GetValue() const - { - return value; - } - - void MarkDecodingError() - { - value = cReplacementCharacter; - error = true; - } - - template - void Decode(const SBaseIterators& its, integral_constant) - { - typedef SDecoder DecoderType; - DecoderType decoder(*this, *this); - Clear(); - for (BaseIterator it = its.it; IsEmpty(); ++it) - { - uint32 val = static_cast(*it); - decoder(val); - if (its.IsEnd(it)) - { - break; - } - } - if (IsEmpty()) - { - // If we still have neither a new value or an error flag, just treat as error. - // This can happen if we reached the end of the sequence, but it ends in an incomplete code-sequence. - MarkDecodingError(); - } - } - - template - void DecodeIfEmpty(const SBaseIterators& its, integral_constant tag) - { - if (IsEmpty()) - { - Decode(its, tag); - } - } - - void operator()(uint32 unit) - { - value = unit; - } - - void operator()(SIteratorSink&, uint32, uint32) - { - MarkDecodingError(); - } - }; - - // SIteratorSink: - // Helper to store the last code-point that was decoded. - // This is the un-safe specialization for known-valid sequences. - // Note: No error-state is tracked since we won't handle that regardless for un-safe CIterator. - template<> - struct SIteratorSink - { - static const uint32 cEmpty = 0xFFFFFFFFU; - uint32 value; - - void Clear() - { - value = cEmpty; - } - - bool IsEmpty() const - { - return value == cEmpty; - } - - bool IsError() const - { - return false; - } - - const uint32& GetValue() const - { - return value; - } - - template - void Decode(const SBaseIterators& its, integral_constant) - { - typedef SDecoder DecoderType; - DecoderType decoder(*this); - for (BaseIterator it = its.it; IsEmpty(); ++it) - { - uint32 val = static_cast(*it); - decoder(val); - } - } - - template - void DecodeIfEmpty(const SBaseIterators& its, integral_constant tag) - { - if (IsEmpty()) - { - Decode(its, tag); - } - } - - void operator()(uint32 unit) - { - value = unit; - } - }; - } - - // CIterator: - // Helper class that can iterate over an encoded text sequence and read the underlying UCS code-points. - // If the Safe flag is set, bounds checking is performed inside multi-unit sequences to guard against decoding errors. - // This requires the user to know where the sequence ends (use the constructor taking two parameters). - // Note: The BaseIterator must be forward-iterator or better when Safe flag is set. - // If the Safe flag is not set, you must guarantee the sequence is validly encoded, and allows the use of the single argument constructor. - // In the case of unsafe iterator used for C-style string pointer, look for a U+0000 dereferenced value to end the iteration. - // Regardless of the Safe flag, the user must ensure that the iterator is never moved past the beginning or end of the range (just like any other STL iterator). - // Example of typical usage: - // string utf8 = "foo"; // UTF-8 - // for (Unicode::CIterator it(utf8.begin(), utf8.end()); it != utf8.end(); ++it) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - // Example unsafe usage: (for known-valid encoded C-style strings): - // const char *pValid = "foo"; // UTF-8 - // for (Unicode::CIterator it = pValid; *it != 0; ++it) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - template::value> - class CIterator - { - // The iterator value in the encoded sequence. - // Optionally provides bounds-checking. - Detail::SBaseIterators its; - - // The cached UCS code-point at the current position. - // Mutable because dereferencing is conceptually const, but does cache some state in this case. - mutable Detail::SIteratorSink sink; - - public: - // Types for compatibility with STL bidirectional iterator requirements. - typedef const uint32 value_type; - typedef const uint32& reference; - typedef const uint32* pointer; - typedef const ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - - // Construct an iterator for the given range. - // The initial position of the iterator as at the beginning of the range. - CIterator(const BaseIterator& begin, const BaseIterator& end) - : its(begin, end) - { - sink.Clear(); - } - - // Construct an iterator from a single iterator (typically C-style string pointer). - // This can only be used for unsafe iterators. - template - CIterator(const IteratorType& it, typename Detail::SRequire::value, IteratorType>::type* = 0) - : its(static_cast(it)) - { - sink.Clear(); - } - - // Copy-construct an iterator. - CIterator(const CIterator& other) - : its(other.its) - , sink(other.sink) {} - - // Copy-assign an iterator. - CIterator& operator =(const CIterator& other) - { - its = other.its; - sink = other.sink; - return *this; - } - - // Test if the iterator points at an encoding error in the underlying encoded sequence. - // If so, the function returns false. - // When using an un-safe iterator, this function always returns true, if a sequence can contain encoding errors, you must use the safe variant. - // Note: This requires the underlying iterator to be dereferenced, so you cannot use it only while the iterator is inside the valid range. - bool IsAtValidCodepoint() const - { - assert(!its.IsEnd(its.it) && "Attempt to dereference the past-the-end iterator"); - Detail::integral_constant tag; - sink.DecodeIfEmpty(its, tag); - return !sink.IsError(); - } - - // Gets the current position in the underlying encoded sequence. - // If the iterator points to an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // In that case the returned position is approximated; to work around this: move all iterators of which the position is compared in the same direction. - const BaseIterator& GetPosition() const - { - return its.it; - } - - // Sets the current position in the underlying encoded sequence. - // You may not set the position outside the range for which this iterator was constructed. - void SetPosition(const BaseIterator& it) - { - assert(its.IsInRange(it) && "Attempt to set the underlying iterator outside of the supported range"); - its.it = it; - } - - // Test if this iterator is equal to another iterator instance. - // Note: In the presence of an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // To work around this, you can either: - // 1) Move all iterators that will be compared in the same direction; or - // 2) Compare the dereferenced iterator value(s) instead (if applicable). - bool operator ==(const CIterator& other) const - { - return its.IsEqual(other.its); - } - - // Test if this iterator is equal to another base iterator. - // Note: If the provided iterator does not point to the the first code-unit of an UCS code-point, the behavior is undefined. - bool operator ==(const BaseIterator& other) const - { - return its.it == other; - } - - // Test if this iterator is equal to another iterator instance. - // Note: In the presence of an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // To work around this, you can either: - // 1) Move all iterators that will be compared in the same direction; or - // 2) Compare the dereferenced iterator value(s) instead (if applicable). - bool operator !=(const CIterator& other) const - { - return !its.IsEqual(other.its); - } - - // Test if this iterator is equal to another base iterator. - // Note: If the provided iterator does not point to the the first code-unit of an UCS code-point, the behavior is undefined. - bool operator !=(const BaseIterator& other) const - { - return its.it != other; - } - - // Get the decoded UCS code-point at the current position in the sequence. - // If the iterator points to an invalidly encoded sequence (ie, IsError() returns true) the function returns U+FFFD (replacement character). - reference operator *() const - { - assert(!its.IsEnd(its.it) && "Attempt to dereference the past-the-end iterator"); - Detail::integral_constant tag; - sink.DecodeIfEmpty(its, tag); - return sink.GetValue(); - } - - // Advance the iterator to the next UCS code-point. - // Note: You must make sure the iterator is not at the end of the sequence, even in Safe mode. - // However, in Safe mode, the iterator will never move past the end of the sequence in the presence of encoding errors. - CIterator& operator ++() - { - Detail::integral_constant tag; - Detail::MoveNext(its.it, its, tag); - sink.Clear(); - return *this; - } - - // Go back to the previous UCS code-point. - // Note: You must make sure the iterator is not at the beginning of the sequence, even in Safe mode. - // However, in Safe mode, the iterators will never move past the beginning of the sequence in the presence of encoding errors. - CIterator& operator --() - { - Detail::integral_constant tag; - Detail::MovePrev(its.it, its, tag); - sink.Clear(); - return *this; - } - - // Advance the iterator to the next UCS code-point, return a copy of the iterator position before advancing. - // Note: You must make sure the iterator is not at the end of the sequence, even in Safe mode. - // However, in Safe mode, the iterator will never move past the end of the sequence in the presence of encoding errors. - CIterator operator ++(int) - { - CIterator result = *this; - ++*this; - return result; - } - - // Go back to the previous UCS code-point, return a copy of the iterator position before going back. - // Note: You must make sure the iterator is not at the beginning of the sequence, even in Safe mode. - // However, in Safe mode, the iterators will never move past the beginning of the sequence in the presence of encoding errors. - CIterator operator --(int) - { - CIterator result = *this; - --*this; - return result; - } - }; - - namespace Detail - { - // SIteratorSpecializer: - // Specializes the CIterator template to use for a given string type. - // Note: The reason we use this is because MSVC doesn't want to deduce this on the MakeIterator declaration. - template - struct SIteratorSpecializer - { - typedef CIterator type; - }; - } - - // MakeIterator(const StringType &str): - // Helper function to make an UCS code-point iterator given an Unicode string. - // Example usage: - // string utf8 = "foo"; // UTF-8 - // auto it = Unicode::MakeIterator(utf8); - // while (it != utf8.end()) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - // Or, in a for-loop: - // for (auto it = Unicode::MakeIterator(utf8); it != utf8.end(); ++it) {} - template - inline typename Detail::SIteratorSpecializer::type MakeIterator(const StringType& str) - { - return typename Detail::SIteratorSpecializer::type(str.begin(), str.end()); - } -} diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index 63c5b49513..c78a6a4df0 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -116,10 +116,6 @@ set(FILES TimeValue_info.h TypeInfo_decl.h TypeInfo_impl.h - UnicodeBinding.h - UnicodeEncoding.h - UnicodeFunctions.h - UnicodeIterator.h VectorMap.h VectorSet.h VertexFormats.h From b86349c3bf909d8181af535cd6efff77c8a8b446 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:50:39 -0700 Subject: [PATCH 038/251] Some fixes for AzCore Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../AzCore/Debug/StackTracer_Windows.cpp | 18 +++++++-------- .../IO/Streamer/StorageDrive_Windows.cpp | 15 +++++++++---- .../AzCore/IPC/SharedMemory_Windows.cpp | 13 +++++++---- .../NativeUISystemComponent_Windows.cpp | 13 ++++++++--- .../Windows/AzCore/Platform_Windows.cpp | 8 +++---- .../Windows/AzCore/Utils/Utils_Windows.cpp | 7 +++++- .../std/parallel/internal/thread_Windows.cpp | 22 +++++++++++-------- 7 files changed, 62 insertions(+), 34 deletions(-) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index d2cdac84c7..8a99616de3 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -90,7 +90,7 @@ namespace AZ { { case CBA_EVENT: evt = (PIMAGEHLP_CBA_EVENT)CallbackData; - _tprintf(_T("%s"), (PTSTR)evt->desc); + _tprintf(_T("%s"), evt->desc); break; default: @@ -300,7 +300,7 @@ namespace AZ { return; } - const HMODULE hNtDll = GetModuleHandle(_T("ntdll.dll")); + const HMODULE hNtDll = GetModuleHandleW(L"ntdll.dll"); m_LdrRegisterDllNotification = reinterpret_cast(GetProcAddress(hNtDll, "LdrRegisterDllNotification")); if (m_LdrRegisterDllNotification) @@ -324,7 +324,7 @@ namespace AZ { return; } - const HMODULE hNtDll = GetModuleHandle(_T("ntdll.dll")); + const HMODULE hNtDll = GetModuleHandleW(L"ntdll.dll"); m_LdrUnregisterDllNotification = reinterpret_cast(GetProcAddress(hNtDll, "LdrUnregisterDllNotification")); if (m_LdrUnregisterDllNotification) @@ -609,8 +609,8 @@ namespace AZ { if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0) { UINT len; - TCHAR szSubBlock[] = _T("\\"); - if (VerQueryValue(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0) + TCHAR szSubBlock[] = L"\\"; + if (VerQueryValueW(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0) { fInfo = NULL; } @@ -711,7 +711,7 @@ namespace AZ { typedef BOOL (__stdcall * tM32N)(HANDLE hSnapshot, LPMODULEENTRY32 lpme); // try both dlls... - const TCHAR* dllname[] = { _T("kernel32.dll"), _T("tlhelp32.dll") }; + const TCHAR* dllname[] = { L"kernel32.dll", L"tlhelp32.dll" }; HINSTANCE hToolhelp = NULL; tCT32S pCT32S = NULL; tM32F pM32F = NULL; @@ -822,7 +822,7 @@ namespace AZ { const SIZE_T TTBUFLEN = 8096; int cnt = 0; - hPsapi = LoadLibrary(_T("psapi.dll")); + hPsapi = LoadLibraryW(L"psapi.dll"); if (hPsapi == NULL) { return FALSE; @@ -956,10 +956,10 @@ cleanup: // In that scenario, we may try to load and older dbghelp.dll which could cause issues // To overcome this, we try to load dbghelp.dll from the Win 10 SDK folder, if that doesn't // work, load the default. - g_dbgHelpDll = LoadLibrary(_T(R"(C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbghelp.dll)")); + g_dbgHelpDll = LoadLibraryW(LR"(C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbghelp.dll)"); if (g_dbgHelpDll == NULL) { - g_dbgHelpDll = LoadLibrary(_T("dbghelp.dll")); + g_dbgHelpDll = LoadLibrary(L"dbghelp.dll"); } } if (g_dbgHelpDll == NULL) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp index 671cc99aac..2489749b51 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp @@ -16,6 +16,7 @@ #include #include #include +#include namespace AZ::IO { @@ -467,8 +468,10 @@ namespace AZ::IO DWORD createFlags = m_constructionOptions.m_enableUnbufferedReads ? (FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING) : FILE_FLAG_OVERLAPPED; DWORD shareMode = (m_constructionOptions.m_enableSharing || data.m_sharedRead) ? FILE_SHARE_READ: 0; - file = ::CreateFile( - data.m_path.GetAbsolutePath(), // file name + AZStd::wstring filenameW; + AZStd::to_wstring(filenameW, data.m_path.GetAbsolutePath()); + file = ::CreateFileW( + filenameW.c_str(), // file name FILE_GENERIC_READ, // desired access shareMode, // share mode nullptr, // security attributes @@ -806,7 +809,9 @@ namespace AZ::IO } WIN32_FILE_ATTRIBUTE_DATA attributes; - if (::GetFileAttributesEx(fileExists.m_path.GetAbsolutePath(), GetFileExInfoStandard, &attributes)) + AZStd::wstring filenameW; + AZStd::to_wstring(filenameW, fileExists.m_path.GetAbsolutePath()); + if (::GetFileAttributesExW(filenameW.c_str(), GetFileExInfoStandard, &attributes)) { if ((attributes.dwFileAttributes != INVALID_FILE_ATTRIBUTES) && ((attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) @@ -863,7 +868,9 @@ namespace AZ::IO else { WIN32_FILE_ATTRIBUTE_DATA attributes; - if (::GetFileAttributesEx(command.m_path.GetAbsolutePath(), GetFileExInfoStandard, &attributes) && + AZStd::wstring filenameW; + AZStd::to_wstring(filenameW, command.m_path.GetAbsolutePath()); + if (::GetFileAttributesExW(filenameW.c_str(), GetFileExInfoStandard, &attributes) && (attributes.dwFileAttributes != INVALID_FILE_ATTRIBUTES) && ((attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) { fileSize.LowPart = attributes.nFileSizeLow; diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp index 0797541652..21b2a76ba0 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp @@ -10,6 +10,7 @@ #include #include +#include namespace AZ { @@ -41,7 +42,9 @@ namespace AZ SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE); // Obtain global mutex - m_globalMutex = CreateMutex(&secAttr, FALSE, fullName); + AZStd::wstring fullNameW; + AZStd::to_wstring(fullNameW, fullName); + m_globalMutex = CreateMutexW(&secAttr, FALSE, fullNameW.c_str()); DWORD error = GetLastError(); if (m_globalMutex == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false)) { @@ -51,7 +54,7 @@ namespace AZ // Create the file mapping. azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name); - m_mapHandle = CreateFileMapping(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullName); + m_mapHandle = CreateFileMappingW(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullNameW.c_str()); error = GetLastError(); if (m_mapHandle == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false)) { @@ -66,8 +69,10 @@ namespace AZ { char fullName[256]; ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name); + AZStd::wstring fullNameW; + AZStd::to_wstring(fullNameW, fullName); - m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullName); + m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullNameW.c_str()); AZ_Warning("AZSystem", m_globalMutex != NULL, "Failed to open OS mutex [%s]\n", m_name); if (m_globalMutex == NULL) { @@ -76,7 +81,7 @@ namespace AZ } azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name); - m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullName); + m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullNameW.c_str()); if (m_mapHandle == NULL) { AZ_TracePrintf("AZSystem", "OpenFileMapping %s failed with error %d\n", m_name, GetLastError()); diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp index 568f727905..af2a629092 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp @@ -10,6 +10,7 @@ #include #include +#include namespace { @@ -105,11 +106,17 @@ namespace { // Set the text for window title, message, buttons. info = (DlgInfo*)lParam; - SetWindowText(hDlg, info->m_title.c_str()); - SetWindowText(GetDlgItem(hDlg, 0), info->m_message.c_str()); + AZStd::wstring titleW; + AZStd::to_wstring(titleW, info->m_title.c_str()); + SetWindowTextW(hDlg, titleW.c_str()); + AZStd::wstring messageW; + AZStd::to_wstring(messageW, info->m_message.c_str()); + SetWindowTextW(GetDlgItem(hDlg, 0), messageW.c_str()); for (int i = 0; i < info->m_options.size(); i++) { - SetWindowText(GetDlgItem(hDlg, i + 1), info->m_options[i].c_str()); + AZStd::wstring optionW; + AZStd::to_wstring(optionW, info->m_options[i].c_str()); + SetWindowTextW(GetDlgItem(hDlg, i + 1), optionW.c_str()); } } break; diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp index 27e0bd11e1..dc675cd931 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp @@ -37,7 +37,7 @@ namespace AZ { DWORD dataType = REG_SZ; DWORD dataSize = sizeof(machineInfo); - ret = RegQueryValueEx(key, "MachineGuid", 0, &dataType, (LPBYTE)machineInfo, &dataSize); + ret = RegQueryValueExW(key, L"MachineGuid", 0, &dataType, (LPBYTE)machineInfo, &dataSize); RegCloseKey(key); } else @@ -45,7 +45,7 @@ namespace AZ AZ_Error("System", false, "Failed to open HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid!") } - TCHAR* hostname = machineInfo + _tcslen(machineInfo); + TCHAR* hostname = machineInfo + wcslen(machineInfo); // salt the guid time with ComputerName/UserName DWORD bufCharCount = DWORD(sizeof(machineInfo) - (hostname - machineInfo)); if (!::GetComputerName(hostname, &bufCharCount)) @@ -53,7 +53,7 @@ namespace AZ AZ_Error("System", false, "GetComputerName filed with code %d", GetLastError()); } - TCHAR* username = hostname + _tcslen(hostname); + TCHAR* username = hostname + wcslen(hostname); bufCharCount = DWORD(sizeof(machineInfo) - (username - machineInfo)); if( !GetUserName( username, &bufCharCount ) ) { @@ -62,7 +62,7 @@ namespace AZ Sha1 hash; AZ::u32 digest[5] = { 0 }; - hash.ProcessBytes(machineInfo, _tcslen(machineInfo) * sizeof(TCHAR)); + hash.ProcessBytes(machineInfo, wcslen(machineInfo) * sizeof(TCHAR)); hash.GetDigest(digest); s_machineId = digest[0]; if (s_machineId == 0) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp index 749cf1ba82..fd8353b45f 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp @@ -8,6 +8,7 @@ #include #include +#include #include @@ -15,7 +16,11 @@ namespace AZ::Utils { void NativeErrorMessageBox(const char* title, const char* message) { - ::MessageBox(0, message, title, MB_OK | MB_ICONERROR); + AZStd::wstring wtitle; + AZStd::to_wstring(wtitle, title); + AZStd::wstring wmessage; + AZStd::to_wstring(wmessage, message); + ::MessageBoxW(0, wmessage.c_str(), wtitle.c_str(), MB_OK | MB_ICONERROR); } AZ::IO::FixedMaxPathString GetHomeDirectory() diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp index ea92a16838..246181334a 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp @@ -8,6 +8,7 @@ #include #include +#include #include @@ -37,17 +38,20 @@ namespace AZStd // SetThreadDescription was added in 1607 (aka RS1). Since we can't guarantee the user is running 1607 or later, we need to ask for the function from the kernel. using SetThreadDescriptionFunc = HRESULT(WINAPI*)(_In_ HANDLE hThread, _In_ PCWSTR lpThreadDescription); - auto setThreadDescription = reinterpret_cast(::GetProcAddress(::GetModuleHandle("Kernel32.dll"), "SetThreadDescription")); - if (setThreadDescription) + HMODULE kernel32Handle = ::GetModuleHandleW(L"Kernel32.dll"); + if (kernel32Handle) { - // Convert the thread name to Unicode - wchar_t threadNameW[MAX_PATH]; - size_t numCharsConverted; - errno_t wcharResult = mbstowcs_s(&numCharsConverted, threadNameW, threadName, AZ_ARRAY_SIZE(threadNameW) - 1); - if (wcharResult == 0) + SetThreadDescriptionFunc setThreadDescription = reinterpret_cast(::GetProcAddress(kernel32Handle, "SetThreadDescription")); + if (setThreadDescription) { - setThreadDescription(hThread, threadNameW); - return true; + // Convert the thread name to Unicode + AZStd::wstring threadNameW; + AZStd::to_wstring(threadNameW, threadName); + if (!threadNameW.empty()) + { + setThreadDescription(hThread, threadNameW.c_str()); + return true; + } } } From 95c6fd83ead69bad55b067fe3eb3a9549064738a Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:53:16 -0700 Subject: [PATCH 039/251] remove !defined(RESOURCE_COMPILER) since is not defined anywhere (resource compiler was removed) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/ILog.h | 2 -- Code/Legacy/CryCommon/IXml.h | 10 ---------- Code/Legacy/CryCommon/ProjectDefines.h | 7 ++----- Code/Legacy/CryCommon/platform_impl.cpp | 2 -- 4 files changed, 2 insertions(+), 19 deletions(-) diff --git a/Code/Legacy/CryCommon/ILog.h b/Code/Legacy/CryCommon/ILog.h index de60c1e9e0..e71e1f036d 100644 --- a/Code/Legacy/CryCommon/ILog.h +++ b/Code/Legacy/CryCommon/ILog.h @@ -145,9 +145,7 @@ struct ILog virtual void Unindent(class CLogIndenter* indenter) = 0; #endif -#if !defined(RESOURCE_COMPILER) virtual void FlushAndClose() = 0; -#endif }; #if !defined(SUPPORT_LOG_IDENTER) diff --git a/Code/Legacy/CryCommon/IXml.h b/Code/Legacy/CryCommon/IXml.h index e4cb752234..a380ce167b 100644 --- a/Code/Legacy/CryCommon/IXml.h +++ b/Code/Legacy/CryCommon/IXml.h @@ -147,13 +147,11 @@ public: XmlNodeRef& operator=(IXmlNode* newp); XmlNodeRef& operator=(const XmlNodeRef& newp); -#if !defined(RESOURCE_COMPILER) template void GetMemoryUsage(Sizer* pSizer) const { pSizer->AddObject(p); } -#endif //Support for range based for, and stl algorithms. class XmlNodeRefIterator begin(); @@ -399,7 +397,6 @@ public: // -#if !defined(RESOURCE_COMPILER) // // Summary: // Collect all allocated memory @@ -423,7 +420,6 @@ public: // Save in small memory chunks. virtual bool saveToFile(const char* fileName, size_t chunkSizeBytes, AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle) = 0; // -#endif //##@} @@ -792,12 +788,9 @@ struct IXmlSerializer virtual ISerialize* GetWriter(XmlNodeRef& node) = 0; virtual ISerialize* GetReader(XmlNodeRef& node) = 0; // -#if !defined(RESOURCE_COMPILER) virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; -#endif }; -#if !defined(RESOURCE_COMPILER) ////////////////////////////////////////////////////////////////////////// // Summary: // XML Parser interface. @@ -867,7 +860,6 @@ struct IXmlTableReader virtual float GetCurrentRowHeight() = 0; // }; -#endif ////////////////////////////////////////////////////////////////////////// // Summary: @@ -900,7 +892,6 @@ struct IXmlUtils virtual IXmlSerializer* CreateXmlSerializer() = 0; // -#if !defined(RESOURCE_COMPILER) // // Summary: // Creates XML Parser. @@ -945,7 +936,6 @@ struct IXmlUtils // Set to NULL to clear an existing transform and disable further patching virtual void SetXMLPatcher(XmlNodeRef* pPatcher) = 0; // -#endif }; #endif // CRYINCLUDE_CRYCOMMON_IXML_H diff --git a/Code/Legacy/CryCommon/ProjectDefines.h b/Code/Legacy/CryCommon/ProjectDefines.h index 3d635c491c..e359fe669b 100644 --- a/Code/Legacy/CryCommon/ProjectDefines.h +++ b/Code/Legacy/CryCommon/ProjectDefines.h @@ -42,10 +42,7 @@ // Type used for vertex indices // WARNING: If you change this typedef, you need to update AssetProcessorPlatformConfig.ini to convert cgf and abc files to the proper index format. -#if defined(RESOURCE_COMPILER) -typedef uint32 vtx_idx; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(MOBILE) +#if defined(MOBILE) typedef uint16 vtx_idx; #define AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(AZ_RESTRICTED_PLATFORM) @@ -138,7 +135,7 @@ typedef uint32 vtx_idx; # define PHYSICS_STACK_SIZE (128U << 10) #endif -#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !defined(RESOURCE_COMPILER) +#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) #ifndef ENABLE_PROFILING_CODE #define ENABLE_PROFILING_CODE #endif diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 6ec8df0365..54bf38aaa0 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -240,13 +240,11 @@ void CryLowLatencySleep(unsigned int dwMilliseconds) int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const char* lpCaption, [[maybe_unused]] unsigned int uType) { #ifdef WIN32 -#if !defined(RESOURCE_COMPILER) ICVar* const pCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_crash_dialog") : NULL; if ((pCVar && pCVar->GetIVal() != 0) || (gEnv && gEnv->bNoAssertDialog)) { return 0; } -#endif return MessageBox(NULL, lpText, lpCaption, uType); #else return 0; From 99bf5e54c4a7db18bf20b3029259771375d3ddc8 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:53:32 -0700 Subject: [PATCH 040/251] More string fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/IMovieSystem.h | 11 +- Code/Legacy/CryCommon/LyShine/ILyShine.h | 10 +- Code/Legacy/CrySystem/CmdLine.h | 8 +- Code/Legacy/CrySystem/CmdLineArg.h | 4 +- Code/Legacy/CrySystem/ConsoleBatchFile.cpp | 26 +-- Code/Legacy/CrySystem/ConsoleHelpGen.cpp | 68 +++--- Code/Legacy/CrySystem/ConsoleHelpGen.h | 10 +- Code/Legacy/CrySystem/DebugCallStack.cpp | 38 ++-- Code/Legacy/CrySystem/DebugCallStack.h | 10 +- Code/Legacy/CrySystem/IDebugCallStack.cpp | 2 +- Code/Legacy/CrySystem/IDebugCallStack.h | 10 +- .../CrySystem/LevelSystem/LevelSystem.cpp | 2 +- .../CrySystem/LocalizedStringManager.cpp | 209 ++++++++++-------- .../Legacy/CrySystem/LocalizedStringManager.h | 66 +++--- Code/Legacy/CrySystem/Log.cpp | 28 +-- Code/Legacy/CrySystem/System.cpp | 30 +-- Code/Legacy/CrySystem/System.h | 14 +- Code/Legacy/CrySystem/SystemCFG.cpp | 62 +++--- Code/Legacy/CrySystem/SystemCFG.h | 16 +- Code/Legacy/CrySystem/SystemInit.cpp | 1 - Code/Legacy/CrySystem/SystemWin32.cpp | 8 +- Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h | 2 +- Code/Legacy/CrySystem/XML/ReadXMLSink.cpp | 9 +- .../CrySystem/XML/SerializeXMLWriter.cpp | 4 +- .../Legacy/CrySystem/XML/SerializeXMLWriter.h | 2 +- Code/Legacy/CrySystem/XML/WriteXMLSource.cpp | 4 +- Code/Legacy/CrySystem/XML/XMLBinaryWriter.h | 12 +- Code/Legacy/CrySystem/XML/XMLPatcher.cpp | 17 +- Code/Legacy/CrySystem/XML/XmlUtils.cpp | 2 +- Code/Legacy/CrySystem/XML/xml.cpp | 18 +- Code/Tools/GridHub/GridHub/gridhub.cpp | 4 - Code/Tools/Standalone/CMakeLists.txt | 2 - .../Platform/Windows/FFontXML_Windows.cpp | 12 +- .../Platform/Windows/FontTexture_Windows.cpp | 2 +- .../AtomFont/Code/Source/AtomFont.cpp | 121 +++++----- .../AtomFont/Code/Source/FFont.cpp | 4 +- .../Code/Editor/PropertyHandlerChar.cpp | 3 +- .../Platform/Windows/UiClipboard_Windows.cpp | 6 +- Gems/LyShine/Code/Source/StringUtfUtils.h | 3 +- .../LyShine/Code/Source/UiButtonComponent.cpp | 2 +- Gems/LyShine/Code/Source/UiImageComponent.cpp | 2 +- Gems/LyShine/Code/Source/UiTextComponent.cpp | 2 +- .../Code/Source/UiTextInputComponent.cpp | 5 +- 43 files changed, 439 insertions(+), 432 deletions(-) diff --git a/Code/Legacy/CryCommon/IMovieSystem.h b/Code/Legacy/CryCommon/IMovieSystem.h index 074c7ab01d..915dc925bf 100644 --- a/Code/Legacy/CryCommon/IMovieSystem.h +++ b/Code/Legacy/CryCommon/IMovieSystem.h @@ -112,7 +112,7 @@ public: CAnimParamType() : m_type(kAnimParamTypeInvalid) {} - CAnimParamType(const string& name) + CAnimParamType(const AZStd::string& name) { *this = name; } @@ -128,17 +128,12 @@ public: m_type = type; } - void operator =(const string& name) - { - m_type = kAnimParamTypeByString; - m_name = name; - } - void operator =(const AZStd::string& name) { m_type = kAnimParamTypeByString; m_name = name; } + // Convert to enum. This needs to be explicit, // otherwise operator== will be ambiguous AnimParamType GetType() const { return m_type; } @@ -1437,7 +1432,7 @@ inline void SAnimContext::Serialize(XmlNodeRef& xmlNode, bool bLoading) { if (sequence) { - string fullname = sequence->GetName(); + AZStd::string fullname = sequence->GetName(); xmlNode->setAttr("sequence", fullname.c_str()); } xmlNode->setAttr("dt", dt); diff --git a/Code/Legacy/CryCommon/LyShine/ILyShine.h b/Code/Legacy/CryCommon/LyShine/ILyShine.h index 07bffda0fe..7832497d8c 100644 --- a/Code/Legacy/CryCommon/LyShine/ILyShine.h +++ b/Code/Legacy/CryCommon/LyShine/ILyShine.h @@ -46,7 +46,7 @@ public: virtual AZ::EntityId CreateCanvas() = 0; //! Load a UI Canvas from in-game - virtual AZ::EntityId LoadCanvas(const string& assetIdPathname) = 0; + virtual AZ::EntityId LoadCanvas(const AZStd::string& assetIdPathname) = 0; //! Create an empty UI Canvas (for the UI editor) // @@ -54,7 +54,7 @@ public: virtual AZ::EntityId CreateCanvasInEditor(UiEntityContext* entityContext) = 0; //! Load a UI Canvas from the UI editor - virtual AZ::EntityId LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext) = 0; + virtual AZ::EntityId LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext) = 0; //! Reload a UI Canvas from xml. For use in the editor for the undo system only virtual AZ::EntityId ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext) = 0; @@ -65,7 +65,7 @@ public: //! Get a loaded canvas by path name //! NOTE: this only searches canvases loaded in the game (not the editor) - virtual AZ::EntityId FindLoadedCanvasByPathName(const string& assetIdPathname) = 0; + virtual AZ::EntityId FindLoadedCanvasByPathName(const AZStd::string& assetIdPathname) = 0; //! Release a canvas from use either in-game or in editor, destroy UI Canvas if no longer used in either virtual void ReleaseCanvas(AZ::EntityId canvas, bool forEditor = false) = 0; @@ -74,10 +74,10 @@ public: virtual void ReleaseCanvasDeferred(AZ::EntityId canvas) = 0; //! Load a sprite object. - virtual ISprite* LoadSprite(const string& pathname) = 0; + virtual ISprite* LoadSprite(const AZStd::string& pathname) = 0; //! Create a sprite that references the specified render target - virtual ISprite* CreateSprite(const string& renderTargetName) = 0; + virtual ISprite* CreateSprite(const AZStd::string& renderTargetName) = 0; //! Check if a sprite's texture asset exists. The .sprite sidecar file is optional and is not checked virtual bool DoesSpriteTextureAssetExist(const AZStd::string& pathname) = 0; diff --git a/Code/Legacy/CrySystem/CmdLine.h b/Code/Legacy/CrySystem/CmdLine.h index 9ad7effebd..5e5c6466f1 100644 --- a/Code/Legacy/CrySystem/CmdLine.h +++ b/Code/Legacy/CrySystem/CmdLine.h @@ -29,13 +29,13 @@ public: virtual const ICmdLineArg* GetArg(int n) const; virtual int GetArgCount() const; virtual const ICmdLineArg* FindArg(const ECmdLineArgType ArgType, const char* name, bool caseSensitive = false) const; - virtual const char* GetCommandLine() const { return m_sCmdLine; }; + virtual const char* GetCommandLine() const { return m_sCmdLine.c_str(); }; private: - void PushCommand(const string& sCommand, const string& sParameter); - string Next(char*& str); + void PushCommand(const AZStd::string& sCommand, const AZStd::string& sParameter); + AZStd::string Next(char*& str); - string m_sCmdLine; + AZStd::string m_sCmdLine; std::vector m_args; }; diff --git a/Code/Legacy/CrySystem/CmdLineArg.h b/Code/Legacy/CrySystem/CmdLineArg.h index cc79981a72..5e3a629e7c 100644 --- a/Code/Legacy/CrySystem/CmdLineArg.h +++ b/Code/Legacy/CrySystem/CmdLineArg.h @@ -34,8 +34,8 @@ public: private: ECmdLineArgType m_type; - string m_name; - string m_value; + AZStd::string m_name; + AZStd::string m_value; }; #endif // CRYINCLUDE_CRYSYSTEM_CMDLINEARG_H diff --git a/Code/Legacy/CrySystem/ConsoleBatchFile.cpp b/Code/Legacy/CrySystem/ConsoleBatchFile.cpp index 6e36780ac0..8b25773c45 100644 --- a/Code/Legacy/CrySystem/ConsoleBatchFile.cpp +++ b/Code/Legacy/CrySystem/ConsoleBatchFile.cpp @@ -57,7 +57,7 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) Init(); } - string filename; + AZStd::string filename; if (sFilename[0] != '@') // console config files are actually by default in @root@ instead of @assets@ { @@ -78,7 +78,7 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) filename = sFilename; } - if (strlen(PathUtil::GetExt(filename)) == 0) + if (strlen(PathUtil::GetExt(filename.c_str())) == 0) { filename = PathUtil::ReplaceExtension(filename, "cfg"); } @@ -88,20 +88,20 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) { const char* szLog = "Executing console batch file (try game,config,root):"; - string filenameLog; - string sfn = PathUtil::GetFile(filename); + AZStd::string filenameLog; + AZStd::string sfn = PathUtil::GetFile(filename); - if (file.Open(filename, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) + if (file.Open(filename.c_str(), "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) { - filenameLog = string("game/") + sfn; + filenameLog = AZStd::string("game/") + sfn; } - else if (file.Open(string("config/") + sfn, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) + else if (file.Open((AZStd::string("config/") + sfn).c_str(), "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) { - filenameLog = string("game/config/") + sfn; + filenameLog = AZStd::string("game/config/") + sfn; } - else if (file.Open(string("./") + sfn, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) + else if (file.Open((AZStd::string("./") + sfn).c_str(), "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) { - filenameLog = string("./") + sfn; + filenameLog = AZStd::string("./") + sfn; } else { @@ -142,11 +142,11 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) str++; } - string strLine = s; + AZStd::string strLine = s; //trim all whitespace characters at the beginning and the end of the current line and store its size - strLine.Trim(); + AZ::StringFunc::TrimWhiteSpace(strLine, true, true); size_t strLineSize = strLine.size(); //skip comments, comments start with ";" or "--" but may have preceding whitespace characters @@ -168,7 +168,7 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) } { - m_pConsole->ExecuteString(strLine); + m_pConsole->ExecuteString(strLine.c_str()); } } // See above diff --git a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp index 0740e3a0f7..ff86577258 100644 --- a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp +++ b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp @@ -17,9 +17,9 @@ // remove bad characters, toupper, not very fast -string CConsoleHelpGen::FixAnchorName(const char* szName) +AZStd::string CConsoleHelpGen::FixAnchorName(const char* szName) { - string ret; + AZStd::string ret; const char* p = szName; @@ -45,9 +45,9 @@ string CConsoleHelpGen::FixAnchorName(const char* szName) return ret; } -string CConsoleHelpGen::GetCleanPrefix(const char* p) +AZStd::string CConsoleHelpGen::GetCleanPrefix(const char* p) { - string sRet; + AZStd::string sRet; while (*p != '_' && *p != 0) { @@ -58,9 +58,9 @@ string CConsoleHelpGen::GetCleanPrefix(const char* p) } -string CConsoleHelpGen::SplitPrefixString_Part1(const char* p) +AZStd::string CConsoleHelpGen::SplitPrefixString_Part1(const char* p) { - string sRet; + AZStd::string sRet; while (*p != 10 && *p != 13 && *p != 0) { @@ -140,7 +140,7 @@ void CConsoleHelpGen::LogVersion(FILE* f) const char fext[_MAX_PATH]; _splitpath_s(s, fdrive, fdir, file, fext); - KeyValue(f, "Executable", (string(file) + fext).c_str()); + KeyValue(f, "Executable", (AZStd::string(file) + fext).c_str()); } { @@ -273,11 +273,11 @@ void CConsoleHelpGen::SingleLinePrefix(FILE* f, const char* szPrefix, const char } else if (m_eWorkMode == eWM_Confluence) { - string sPrefix; + AZStd::string sPrefix; if (*szPrefix) { - sPrefix = string(szPrefix) + "_"; + sPrefix = AZStd::string(szPrefix) + "_"; } // fprintf(f,"| %s | [%s|%s] |\n",sPrefix.c_str(),szPrefixDesc,szLink); // e.g. "" "CL_" "CC_" "I_" "T_" @@ -406,7 +406,7 @@ void CConsoleHelpGen::InsertConsoleCommands(std::setsecond; - if (_strnicmp(cmd.m_sName, szLocalPrefix, strlen(szLocalPrefix)) == 0) + if (_strnicmp(cmd.m_sName.c_str(), szLocalPrefix, strlen(szLocalPrefix)) == 0) { setCmdAndVars.insert(cmd.m_sName.c_str()); } @@ -415,7 +415,7 @@ void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const +void CConsoleHelpGen::InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const { CXConsole::ConsoleVariablesMap::const_iterator itrVar, itrVarEnd = m_rParent.m_mapVariables.end(); @@ -425,11 +425,11 @@ void CConsoleHelpGen::InsertConsoleVars(std::set& bool bInsert = true; { - std::map::const_iterator it2, end = mapPrefix.end(); + std::map::const_iterator it2, end = mapPrefix.end(); for (it2 = mapPrefix.begin(); it2 != end; ++it2) { - if (it2->first != "___" && _strnicmp(var->GetName(), it2->first, it2->first.size()) == 0) + if (it2->first != "___" && _strnicmp(var->GetName(), it2->first.c_str(), it2->first.size()) == 0) { bInsert = false; break; @@ -446,7 +446,7 @@ void CConsoleHelpGen::InsertConsoleVars(std::set& -void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const +void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const { CXConsole::ConsoleCommandsMap::const_iterator itrCmd, itrCmdEnd = m_rParent.m_mapCommands.end(); @@ -456,11 +456,11 @@ void CConsoleHelpGen::InsertConsoleCommands(std::set::const_iterator it2, end = mapPrefix.end(); + std::map::const_iterator it2, end = mapPrefix.end(); for (it2 = mapPrefix.begin(); it2 != end; ++it2) { - if (it2->first != "___" && _strnicmp(cmd.m_sName, it2->first, it2->first.size()) == 0) + if (it2->first != "___" && _strnicmp(cmd.m_sName.c_str(), it2->first.c_str(), it2->first.size()) == 0) { bInsert = false; break; @@ -480,7 +480,7 @@ void CConsoleHelpGen::CreateSingleEntryFile(const char* szName) const assert(m_eWorkMode == eWM_Confluence); // only needed for confluence FILE* f3 = nullptr; - azfopen(&f3, (string(GetFolderName()) + GetFileExtension() + "/" + FixAnchorName(szName)).c_str(), "w"); + azfopen(&f3, (AZStd::string(GetFolderName()) + GetFileExtension() + "/" + FixAnchorName(szName)).c_str(), "w"); if (!f3) { @@ -582,7 +582,7 @@ void CConsoleHelpGen::IncludeSingleEntry(FILE* f, const char* szName) const { fprintf(f, "

\n");
 
-            string sHelp = szHelp;
+            AZStd::string sHelp = szHelp;
 
             // currently not required as the {noformat} is used
             //          sHelp.replace("[","\\[");       sHelp.replace("]","\\]");
@@ -604,7 +604,7 @@ void CConsoleHelpGen::IncludeSingleEntry(FILE* f, const char* szName) const
 
 void CConsoleHelpGen::Work()
 {
-    //  string sEngineFolder = string("@user@/")+GetFolderName();
+    //  AZStd::string sEngineFolder = AZStd::string("@user@/")+GetFolderName();
     //  gEnv->pCryPak->RemoveDir(sEngineFolder.c_str());            // todo: check if that works
     //  gEnv->pFileIO->CreatePath(sEngineFolder.c_str());
 
@@ -653,7 +653,7 @@ void CConsoleHelpGen::CreateMainPages()
 {
     gEnv->pFileIO->CreatePath(GetFolderName());
 
-    std::map mapPrefix;
+    std::map mapPrefix;
 
     // order here doesn't matter, after the name some help can be added (after the first return)
     mapPrefix[     "AI_"] = "Artificial Intelligence";
@@ -701,7 +701,7 @@ void CConsoleHelpGen::CreateMainPages()
     mapPrefix[     "___"] = "Remaining";            // key defined to get it sorted in the end
 
     FILE* f1 = nullptr;
-    azfopen(&f1, (string(GetFolderName()) + "/index" + GetFileExtension()).c_str(), "w");
+    azfopen(&f1, (AZStd::string(GetFolderName()) + "/index" + GetFileExtension()).c_str(), "w");
     if (!f1)
     {
         return;
@@ -729,17 +729,17 @@ void CConsoleHelpGen::CreateMainPages()
 
     // show all registered Prefix with one line
     {
-        std::map::const_iterator it, end = mapPrefix.end();
+        std::map::const_iterator it, end = mapPrefix.end();
 
         StartH3(f1, "Registered Prefixes");
 
         for (it = mapPrefix.begin(); it != end; ++it)
         {
             const char* szLocalPrefix = it->first.c_str();      // can be 0 for remaining ones
-            string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
-            string sPrefixName = SplitPrefixString_Part1(it->second);
+            AZStd::string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
+            AZStd::string sPrefixName = SplitPrefixString_Part1(it->second);
 
-            SingleLinePrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (string("CONSOLEPREFIX") + FixAnchorName(sCleanPrefix.c_str()) + GetFileExtension()).c_str());
+            SingleLinePrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (AZStd::string("CONSOLEPREFIX") + FixAnchorName(sCleanPrefix.c_str()) + GetFileExtension()).c_str());
             //          fprintf(f1,"   * [[CONSOLEPREFIX%s][%s_ %s]]\n",FixAnchorName(sCleanPrefix.c_str()).c_str(),sCleanPrefix.c_str(),sPrefixName.c_str());
         }
 
@@ -750,15 +750,15 @@ void CConsoleHelpGen::CreateMainPages()
 
 
     {
-        std::map::const_iterator it, it2, end = mapPrefix.end();
+        std::map::const_iterator it, it2, end = mapPrefix.end();
 
         StartH3(f1, "Console Commands and Variables Sorted by Prefix");
 
         for (it = mapPrefix.begin(); it != end; ++it)
         {
             const char* szLocalPrefix = it->first.c_str();      // can be 0 for remaining ones
-            string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
-            string sPrefixName = SplitPrefixString_Part1(it->second);
+            AZStd::string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
+            AZStd::string sPrefixName = SplitPrefixString_Part1(it->second);
 
             std::set setCmdAndVars;      // to get console variables and commands sorted together
 
@@ -777,11 +777,11 @@ void CConsoleHelpGen::CreateMainPages()
 
             // -------------------------------
 
-            string sSubName = string("CONSOLEPREFIX") + sCleanPrefix;
+            AZStd::string sSubName = AZStd::string("CONSOLEPREFIX") + sCleanPrefix;
 
             StartPrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (sSubName + GetFileExtension()).c_str());
 
-            string sFileOut = string(GetFolderName()) + "/" + sSubName + GetFileExtension();
+            AZStd::string sFileOut = AZStd::string(GetFolderName()) + "/" + sSubName + GetFileExtension();
             FILE* f2 = nullptr;
             azfopen(&f2, sFileOut.c_str(), "w");
             if (!f2)
@@ -792,7 +792,7 @@ void CConsoleHelpGen::CreateMainPages()
 
             // headline
             {
-                string sHeadline;
+                AZStd::string sHeadline;
 
                 if (sCleanPrefix.empty())
                 {
@@ -800,7 +800,7 @@ void CConsoleHelpGen::CreateMainPages()
                 }
                 else
                 {
-                    sHeadline = string("Console Commands and Variables with Prefix ") + sCleanPrefix + "_";
+                    sHeadline = AZStd::string("Console Commands and Variables with Prefix ") + sCleanPrefix + "_";
                 }
 
                 StartH1(f2, sHeadline.c_str());
@@ -821,7 +821,7 @@ void CConsoleHelpGen::CreateMainPages()
                 for (itI = setCmdAndVars.begin(); itI != endI; ++itI)
                 {
                     SingleLineEntry_InGlobal(f1, *itI, (sSubName + GetFileExtension() + "#Anchor" + FixAnchorName(*itI)).c_str());
-                    SingleLineEntry_InGroup(f2, *itI, (string("#Anchor") + FixAnchorName(*itI)).c_str());
+                    SingleLineEntry_InGroup(f2, *itI, (AZStd::string("#Anchor") + FixAnchorName(*itI)).c_str());
                 }
 
                 EndH3(f2);
@@ -842,7 +842,7 @@ void CConsoleHelpGen::CreateMainPages()
                         }
                         bFirst = false;
 
-                        Anchor(f2, (string("Anchor") + FixAnchorName(*itI)).c_str());      // anchor
+                        Anchor(f2, (AZStd::string("Anchor") + FixAnchorName(*itI)).c_str());      // anchor
 
                         IncludeSingleEntry(f2, *itI);
                     }
diff --git a/Code/Legacy/CrySystem/ConsoleHelpGen.h b/Code/Legacy/CrySystem/ConsoleHelpGen.h
index 9ff797ca07..576232fe7a 100644
--- a/Code/Legacy/CrySystem/ConsoleHelpGen.h
+++ b/Code/Legacy/CrySystem/ConsoleHelpGen.h
@@ -59,19 +59,19 @@ private: // --------------------------------------------------------
     // insert if the name starts with the with prefix
     void InsertConsoleCommands(std::set& setCmdAndVars, const char* szPrefix) const;
     // insert if the name does not start with any of the prefix in the map
-    void InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const;
+    void InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const;
     // insert if the name does not start with any of the prefix in the map
-    void InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const;
+    void InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const;
 
     // a single file for the entry is generate
     void CreateSingleEntryFile(const char* szName) const;
 
     void IncludeSingleEntry(FILE* f, const char* szName) const;
 
-    static string FixAnchorName(const char* szName);
-    static string GetCleanPrefix(const char* p);
+    static AZStd::string FixAnchorName(const char* szName);
+    static AZStd::string GetCleanPrefix(const char* p);
     // split before "|" (to get the prefix itself)
-    static string SplitPrefixString_Part1(const char* p);
+    static AZStd::string SplitPrefixString_Part1(const char* p);
     // split string after "|" (to get the optional help)
     static const char* SplitPrefixString_Part2(const char* p);
 
diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp
index 1914e82515..c5d932429c 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/DebugCallStack.cpp
@@ -348,7 +348,7 @@ void DebugCallStack::ReportBug(const char* szErrorMessage)
     m_szBugMessage = NULL;
 }
 
-void DebugCallStack::dumpCallStack(std::vector& funcs)
+void DebugCallStack::dumpCallStack(std::vector& funcs)
 {
     WriteLineToLog("=============================================================================");
     int len = (int)funcs.size();
@@ -364,7 +364,7 @@ void DebugCallStack::dumpCallStack(std::vector& funcs)
 //////////////////////////////////////////////////////////////////////////
 void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
 {
-    string path("");
+    AZStd::string path("");
     if ((gEnv) && (gEnv->pFileIO))
     {
         const char* logAlias = gEnv->pFileIO->GetAlias("@log@");
@@ -379,12 +379,12 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         }
     }
 
-    string fileName = path;
+    AZStd::string fileName = path;
     fileName += "error.log";
 
     struct stat fileInfo;
-    string timeStamp;
-    string backupPath;
+    AZStd::string timeStamp;
+    AZStd::string backupPath;
     if (gEnv->IsDedicated())
     {
         backupPath = PathUtil::ToUnixPath(PathUtil::AddSlash(path + "DumpBackups"));
@@ -399,7 +399,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
             strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime);
             timeStamp = tempBuffer;
 
-            string backupFileName = backupPath + timeStamp + " error.log";
+            AZStd::string backupFileName = backupPath + timeStamp + " error.log";
             CopyFile(fileName.c_str(), backupFileName.c_str(), true);
         }
     }
@@ -414,8 +414,8 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
     char versionbuf[1024];
     azstrcpy(versionbuf, AZ_ARRAY_SIZE(versionbuf), "");
     PutVersion(versionbuf, AZ_ARRAY_SIZE(versionbuf));
-    cry_strcat(errorString, versionbuf);
-    cry_strcat(errorString, "\n");
+    azstrcat(errorString, versionbuf);
+    azstrcat(errorString, "\n");
 
     char excCode[MAX_WARNING_LENGTH];
     char excAddr[80];
@@ -481,9 +481,9 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         excCode, excAddr, m_excModule, excName, desc);
 
 
-    cry_strcat(errs, "\nCall Stack Trace:\n");
+    azstrcat(errs, "\nCall Stack Trace:\n");
 
-    std::vector funcs;
+    std::vector funcs;
     {
         AZ::Debug::StackFrame frames[25];
         AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)];
@@ -504,15 +504,15 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         {
             char temp[s_iCallStackSize];
             sprintf_s(temp, "%2zd) %s", funcs.size() - i, (const char*)funcs[i].c_str());
-            cry_strcat(str, temp);
-            cry_strcat(str, "\r\n");
-            cry_strcat(errs, temp);
-            cry_strcat(errs, "\n");
+            azstrcat(str, temp);
+            azstrcat(str, "\r\n");
+            azstrcat(errs, temp);
+            azstrcat(errs, "\n");
         }
         azstrcpy(m_excCallstack, str);
     }
 
-    cry_strcat(errorString, errs);
+    azstrcat(errorString, errs);
 
     if (f)
     {
@@ -593,7 +593,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
                     timeStamp = tempBuffer;
                 }
 
-                string backupFileName = backupPath + timeStamp + " error.dmp";
+                AZStd::string backupFileName = backupPath + timeStamp + " error.dmp";
                 CopyFile(fileName.c_str(), backupFileName.c_str(), true);
             }
 
@@ -818,7 +818,7 @@ void DebugCallStack::ResetFPU(EXCEPTION_POINTERS* pex)
     }
 }
 
-string DebugCallStack::GetModuleNameForAddr(void* addr)
+AZStd::string DebugCallStack::GetModuleNameForAddr(void* addr)
 {
     if (m_modules.empty())
     {
@@ -844,7 +844,7 @@ string DebugCallStack::GetModuleNameForAddr(void* addr)
     return m_modules.rbegin()->second;
 }
 
-void DebugCallStack::GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line)
+void DebugCallStack::GetProcNameForAddr(void* addr, AZStd::string& procName, void*& baseAddr, AZStd::string& filename, int& line)
 {
     AZ::Debug::SymbolStorage::StackLine func, file, module;
     AZ::Debug::SymbolStorage::FindFunctionFromIP(addr, &func, &file, &module, line, baseAddr);
@@ -852,7 +852,7 @@ void DebugCallStack::GetProcNameForAddr(void* addr, string& procName, void*& bas
     filename = file;
 }
 
-string DebugCallStack::GetCurrentFilename()
+AZStd::string DebugCallStack::GetCurrentFilename()
 {
     char fullpath[MAX_PATH_LENGTH + 1];
     GetModuleFileName(NULL, fullpath, MAX_PATH_LENGTH);
diff --git a/Code/Legacy/CrySystem/DebugCallStack.h b/Code/Legacy/CrySystem/DebugCallStack.h
index f0c708a2b5..28f587011e 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.h
+++ b/Code/Legacy/CrySystem/DebugCallStack.h
@@ -35,20 +35,20 @@ public:
 
     ISystem* GetSystem() { return m_pSystem; };
 
-    virtual string GetModuleNameForAddr(void* addr);
-    virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line);
-    virtual string GetCurrentFilename();
+    virtual AZStd::string GetModuleNameForAddr(void* addr);
+    virtual void GetProcNameForAddr(void* addr, AZStd::string& procName, void*& baseAddr, AZStd::string& filename, int& line);
+    virtual AZStd::string GetCurrentFilename();
 
     void installErrorHandler(ISystem* pSystem);
     virtual int handleException(EXCEPTION_POINTERS* exception_pointer);
 
     virtual void ReportBug(const char*);
 
-    void dumpCallStack(std::vector& functions);
+    void dumpCallStack(std::vector& functions);
 
     void SetUserDialogEnable(const bool bUserDialogEnable);
 
-    typedef std::map TModules;
+    typedef std::map TModules;
 protected:
     static void RemoveOldFiles();
     static void RemoveFile(const char* szFileName);
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp
index 4ca481be88..ff43f6e56f 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp
@@ -237,7 +237,7 @@ void IDebugCallStack::WriteLineToLog(const char* format, ...)
     char        szBuffer[MAX_WARNING_LENGTH];
     va_start(ArgList, format);
     vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, ArgList);
-    cry_strcat(szBuffer, "\n");
+    azstrcat(szBuffer, "\n");
     szBuffer[sizeof(szBuffer) - 1] = '\0';
     va_end(ArgList);
 
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.h b/Code/Legacy/CrySystem/IDebugCallStack.h
index c05d0827b0..a2c1d3f5e2 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.h
+++ b/Code/Legacy/CrySystem/IDebugCallStack.h
@@ -33,23 +33,23 @@ public:
     virtual int handleException([[maybe_unused]] EXCEPTION_POINTERS* exception_pointer){return 0; }
 
     // returns the module name of a given address
-    virtual string GetModuleNameForAddr([[maybe_unused]] void* addr) { return "[unknown]"; }
+    virtual AZStd::string GetModuleNameForAddr([[maybe_unused]] void* addr) { return "[unknown]"; }
 
     // returns the function name of a given address together with source file and line number (if available) of a given address
-    virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line)
+    virtual void GetProcNameForAddr(void* addr, AZStd::string& procName, void*& baseAddr, AZStd::string& filename, int& line)
     {
         filename = "[unknown]";
         line = 0;
         baseAddr = addr;
 #if defined(PLATFORM_64BIT)
-        procName.Format("[%016llX]", addr);
+        procName = AZStd::string::format("[%016llX]", addr);
 #else
-        procName.Format("[%08X]", addr);
+        procName = AZStd::string::format("[%08X]", addr);
 #endif
     }
 
     // returns current filename
-    virtual string GetCurrentFilename()  { return "[unknown]"; }
+    virtual AZStd::string GetCurrentFilename()  { return "[unknown]"; }
 
     //! Dumps Current Call Stack to log.
     virtual void LogCallstack();
diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
index 83db5e4a29..3e6432a721 100644
--- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
+++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
@@ -480,7 +480,7 @@ CLevelInfo* CLevelSystem::GetLevelInfoInternal(const AZStd::string& levelName)
     for (AZStd::vector::iterator it = m_levelInfos.begin(); it != m_levelInfos.end(); ++it)
     {
         {
-            if (!azstricmp(PathUtil::GetFileName(it->GetName()), levelName.c_str()))
+            if (!azstricmp(PathUtil::GetFileName(it->GetName()).c_str(), levelName.c_str()))
             {
                 return &(*it);
             }
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
index fe0fd9cb22..e3ccb22f88 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
@@ -20,7 +20,6 @@
 #include "System.h" // to access InitLocalization()
 #include 
 #include 
-#include 
 #include 
 #include 
 
@@ -146,9 +145,9 @@ static void ReloadDialogData([[maybe_unused]] IConsoleCmdArgs* pArgs)
 #if !defined(_RELEASE)
 static void TestFormatMessage ([[maybe_unused]] IConsoleCmdArgs* pArgs)
 {
-    string fmt1 ("abc %1 def % gh%2i %");
-    string fmt2 ("abc %[action:abc] %2 def % gh%1i %1");
-    string out1, out2;
+    AZStd::string fmt1 ("abc %1 def % gh%2i %");
+    AZStd::string fmt2 ("abc %[action:abc] %2 def % gh%1i %1");
+    AZStd::string out1, out2;
     LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::FormatStringMessage, out1, fmt1, "first", "second", "third", nullptr);
     CryLogAlways("%s", out1.c_str());
     LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::FormatStringMessage, out2, fmt2, "second", nullptr, nullptr, nullptr);
@@ -206,18 +205,18 @@ CLocalizedStringsManager::CLocalizedStringsManager(ISystem* pSystem)
 
     // Populate available languages by scanning the localization directory for paks
     // Default to US English if language is not supported
-    string sPath;
-    const string sLocalizationFolder(PathUtil::GetLocalizationFolder());
+    AZStd::string sPath;
+    const AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
     ILocalizationManager::TLocalizationBitfield availableLanguages = 0;
     
     AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
     // test language name against supported languages
     for (int i = 0; i < ILocalizationManager::ePILID_MAX_OR_INVALID; i++)
     {
-        string sCurrentLanguage = LangNameFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i);  
+        AZStd::string sCurrentLanguage = LangNameFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i);
         sPath = sLocalizationFolder.c_str() + sCurrentLanguage;
-        sPath.MakeLower();
-        if (fileIO && fileIO->IsDirectory(sPath))
+        AZStd::to_lower(sPath.begin(), sPath.end());
+        if (fileIO && fileIO->IsDirectory(sPath.c_str()))
         {
             availableLanguages |= ILocalizationManager::LocalizationBitfieldFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i);
             if (m_cvarLocalizationDebug >= 2)
@@ -366,7 +365,7 @@ bool CLocalizedStringsManager::SetLanguage(const char* sLanguage)
     // Check if already language loaded.
     for (uint32 i = 0; i < m_languages.size(); i++)
     {
-        if (_stricmp(sLanguage, m_languages[i]->sLanguage) == 0)
+        if (_stricmp(sLanguage, m_languages[i]->sLanguage.c_str()) == 0)
         {
             InternalSetCurrentLanguage(m_languages[i]);
             return true;
@@ -441,9 +440,9 @@ void CLocalizedStringsManager::AddControl([[maybe_unused]] int nKey)
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex)
+void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex)
 {
-    string sCellContent;
+    AZStd::string sCellContent;
 
     for (;; )
     {
@@ -466,7 +465,7 @@ void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader,
         }
 
         sCellContent.assign(pContent, contentSize);
-        sCellContent.MakeLower();
+        AZStd::to_lower(sCellContent.begin(), sCellContent.end());
 
         for (int i = 0; i < sizeof(sLocalizedColumnNames) / sizeof(sLocalizedColumnNames[0]); ++i)
         {
@@ -530,8 +529,8 @@ static void CopyLowercase(char* dst, size_t dstSize, const char* src, size_t src
 //////////////////////////////////////////////////////////////////////////
 static void ReplaceEndOfLine(AZStd::fixed_string& s)
 {
-    const string oldSubstr("\\n");
-    const string newSubstr(" \n");
+    const AZStd::string oldSubstr("\\n");
+    const AZStd::string newSubstr(" \n");
     size_t pos = 0;
     for (;; )
     {
@@ -565,7 +564,7 @@ void CLocalizedStringsManager::OnSystemEvent(
 
             for (TStringVec::iterator it = m_tagLoadRequests.begin(); it != m_tagLoadRequests.end(); ++it)
             {
-                LoadLocalizationDataByTag(*it);
+                LoadLocalizationDataByTag(it->c_str());
             }
         }
 
@@ -577,7 +576,7 @@ void CLocalizedStringsManager::OnSystemEvent(
         // Load all tags after the Editor has finished initialization.
         for (TTagFileNames::iterator it = m_tagFileNames.begin(); it != m_tagFileNames.end(); ++it)
         {
-            LoadLocalizationDataByTag(it->first);
+            LoadLocalizationDataByTag(it->first.c_str());
         }
 
         break;
@@ -600,7 +599,7 @@ bool CLocalizedStringsManager::InitLocalizationData(
     for (int i = 0; i < root->getChildCount(); i++)
     {
         XmlNodeRef typeNode = root->getChild(i);
-        string sType = typeNode->getTag();
+        AZStd::string sType = typeNode->getTag();
 
         // tags should be unique
         if (m_tagFileNames.find(sType) != m_tagFileNames.end())
@@ -678,9 +677,9 @@ bool CLocalizedStringsManager::LoadLocalizationDataByTag(
     for (TStringVec::iterator it2 = vEntries.begin(); it2 != vEntries.end(); ++it2)
     {
         //Only load files of the correct type for the configured format
-        if ((m_cvarLocalizationFormat == 0 && strstr(*it2, ".xml")) || (m_cvarLocalizationFormat == 1 && strstr(*it2, ".agsxml")))
+        if ((m_cvarLocalizationFormat == 0 && strstr(it2->c_str(), ".xml")) || (m_cvarLocalizationFormat == 1 && strstr(it2->c_str(), ".agsxml")))
         {
-            bResult &= (this->*loadFunction)(*it2, it->second.id, bReload);
+            bResult &= (this->*loadFunction)(it2->c_str(), it->second.id, bReload);
         }
     }
 
@@ -824,7 +823,7 @@ bool CLocalizedStringsManager::LoadAllLocalizationData(bool bReload)
 {
     for (TTagFileNames::iterator it = m_tagFileNames.begin(); it != m_tagFileNames.end(); ++it)
     {
-        if(!LoadLocalizationDataByTag(it->first, bReload))
+        if(!LoadLocalizationDataByTag(it->first.c_str(), bReload))
             return false;
     }
     return true;
@@ -837,6 +836,37 @@ bool CLocalizedStringsManager::LoadExcelXmlSpreadsheet(const char* sFileName, bo
     return (this->*loadFunction)(sFileName, 0, bReload);
 }
 
+enum class YesNoType
+{
+    Yes,
+    No,
+    Invalid
+};
+
+// parse the yes/no string
+/*!
+\param szString any of the following strings: yes, enable, true, 1, no, disable, false, 0
+\return YesNoType::Yes if szString is yes/enable/true/1, YesNoType::No if szString is no, disable, false, 0 and YesNoType::Invalid if the string is not one of the expected values.
+*/
+inline YesNoType ToYesNoType(const char* szString)
+{
+    if (!_stricmp(szString, "yes")
+        || !_stricmp(szString, "enable")
+        || !_stricmp(szString, "true")
+        || !_stricmp(szString, "1"))
+    {
+        return YesNoType::Yes;
+    }
+    if (!_stricmp(szString, "no")
+        || !_stricmp(szString, "disable")
+        || !_stricmp(szString, "false")
+        || !_stricmp(szString, "0"))
+    {
+        return YesNoType::No;
+    }
+    return YesNoType::Invalid;
+}
+
 //////////////////////////////////////////////////////////////////////
 // Loads a string-table from a Excel XML Spreadsheet file.
 bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName, uint8 nTagID, bool bReload)
@@ -850,7 +880,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
     //check if this table has already been loaded
     if (!bReload)
     {
-        if (m_loadedTables.find(CONST_TEMP_STRING(sFileName)) != m_loadedTables.end())
+        if (m_loadedTables.find(AZStd::string(sFileName)) != m_loadedTables.end())
         {
             return (true);
         }
@@ -866,12 +896,12 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
     }
 
     XmlNodeRef root;
-    string sPath;
+    AZStd::string sPath;
     {
-        const string sLocalizationFolder(PathUtil::GetLocalizationRoot());
-        const string& languageFolder = m_pLanguage->sLanguage;
+        const AZStd::string sLocalizationFolder(PathUtil::GetLocalizationRoot());
+        const AZStd::string& languageFolder = m_pLanguage->sLanguage;
         sPath = sLocalizationFolder.c_str() + languageFolder + PathUtil::GetSlash() + sFileName;
-        root = m_pSystem->LoadXmlFromFile(sPath);
+        root = m_pSystem->LoadXmlFromFile(sPath.c_str());
         if (!root)
         {
             CryLog("Loading Localization File %s failed!", sPath.c_str());
@@ -948,10 +978,10 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
     memset(nCellIndexToType, 0, sizeof(nCellIndexToType));
 
     // SoundMood Index
-    std::map SoundMoodIndex;
+    std::map SoundMoodIndex;
 
     // EventParameter Index
-    std::map EventParameterIndex;
+    std::map EventParameterIndex;
 
     bool bFirstRow = true;
 
@@ -1083,7 +1113,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
                 break;
             case ELOCALIZED_COLUMN_USE_SUBTITLE:
                 sTmp.assign(cell.ptr, cell.count);
-                bUseSubtitle = CryStringUtils::ToYesNoType(sTmp.c_str()) == CryStringUtils::YesNoType::No ? false : true; // favor yes (yes and invalid -> yes)
+                bUseSubtitle = ToYesNoType(sTmp.c_str()) == YesNoType::No ? false : true; // favor yes (yes and invalid -> yes)
                 break;
             case ELOCALIZED_COLUMN_VOLUME:
                 sTmp.assign(cell.ptr, cell.count);
@@ -1121,7 +1151,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
                 {
                     bIsIntercepted = true;
                 }
-                bIsDirectRadio = bIsIntercepted || (CryStringUtils::ToYesNoType(sTmp.c_str()) == CryStringUtils::YesNoType::Yes ? true : false); // favor no (no and invalid -> no)
+                bIsDirectRadio = bIsIntercepted || (ToYesNoType(sTmp.c_str()) == YesNoType::Yes ? true : false); // favor no (no and invalid -> no)
                 ++nItems;
                 break;
             // legacy names
@@ -1358,7 +1388,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
             }
             else
             {
-                pEntry->TranslatedText.psUtf8Uncompressed = new string(sTmp.c_str(), sTmp.c_str() + sTmp.length());
+                pEntry->TranslatedText.psUtf8Uncompressed = new AZStd::string(sTmp.c_str(), sTmp.c_str() + sTmp.length());
             }
         }
 
@@ -1367,7 +1397,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
         // the CryString makes sure, that only the ref-count is increment on assignment
         if (*szLowerCaseEvent)
         {
-            PrototypeSoundEvents::iterator it = m_prototypeEvents.find(CONST_TEMP_STRING(szLowerCaseEvent));
+            PrototypeSoundEvents::iterator it = m_prototypeEvents.find(AZStd::string(szLowerCaseEvent));
             if (it != m_prototypeEvents.end())
             {
                 pEntry->sPrototypeSoundEvent = *it;
@@ -1384,8 +1414,8 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
         {
             sTmp.assign(sWho.ptr, sWho.count);
             ReplaceEndOfLine(sTmp);
-            sTmp.replace(" ", "_");
-            string tmp;
+            AZStd::replace(sTmp.begin(), sTmp.end(), ' ', '_');
+            AZStd::string tmp;
             {
                 tmp = sTmp.c_str();
             }
@@ -1531,19 +1561,19 @@ bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8
     }
     if (!bReload)
     {
-        if (m_loadedTables.find(CONST_TEMP_STRING(sFileName)) != m_loadedTables.end())
+        if (m_loadedTables.find(AZStd::string(sFileName)) != m_loadedTables.end())
         {
             return true;
         }
     }
     ListAndClearProblemLabels();
     XmlNodeRef root;
-    string sPath;
+    AZStd::string sPath;
     {
-        const string sLocalizationFolder(PathUtil::GetLocalizationRoot());
-        const string& languageFolder = m_pLanguage->sLanguage;
+        const AZStd::string sLocalizationFolder(PathUtil::GetLocalizationRoot());
+        const AZStd::string& languageFolder = m_pLanguage->sLanguage;
         sPath = sLocalizationFolder.c_str() + languageFolder + PathUtil::GetSlash() + sFileName;
-        root = m_pSystem->LoadXmlFromFile(sPath);
+        root = m_pSystem->LoadXmlFromFile(sPath.c_str());
         if (!root)
         {
             AZ_TracePrintf(LOC_WINDOW, "Loading Localization File %s failed!", sPath.c_str());
@@ -1654,7 +1684,7 @@ bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8
             }
             else
             {
-                pEntry->TranslatedText.psUtf8Uncompressed = new string(textString, textString + textLength);
+                pEntry->TranslatedText.psUtf8Uncompressed = new AZStd::string(textString, textString + textLength);
             }
         }
         {
@@ -1714,7 +1744,7 @@ void CLocalizedStringsManager::ReloadData()
     FreeLocalizationData();
     for (tmapFilenames::iterator it = temp.begin(); it != temp.end(); it++)
     {
-        (this->*loadFunction)((*it).first, (*it).second.nTagID, true);
+        (this->*loadFunction)((*it).first.c_str(), (*it).second.nTagID, true);
     }
 }
 
@@ -1732,19 +1762,19 @@ void CLocalizedStringsManager::AddLocalizedString(SLanguage* pLanguage, SLocaliz
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish)
 {
     return LocalizeStringInternal(sString, strlen(sString), outLocalizedString, bEnglish);
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish)
 {
     return LocalizeStringInternal(sString.c_str(), sString.length(), outLocalizedString, bEnglish);
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t len, string& outLocalizedString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t len, AZStd::string& outLocalizedString, bool bEnglish)
 {
     assert (m_pLanguage);
     if (m_pLanguage == 0)
@@ -1755,7 +1785,7 @@ bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t l
     }
 
     // note: we don't write directly to outLocalizedString, in case it aliases pStr
-    string out;
+    AZStd::string out;
 
     // scan the string
     const char* pPos = pStr;
@@ -1783,8 +1813,8 @@ bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t l
         }
 
         // localize token
-        string token(pLabel, pLabelEnd);
-        string sLocalizedToken;
+        AZStd::string token(pLabel, pLabelEnd);
+        AZStd::string sLocalizedToken;
         if (bEnglish)
         {
             GetEnglishString(token.c_str(), sLocalizedToken);
@@ -1803,7 +1833,7 @@ bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t l
 
 void CLocalizedStringsManager::LocalizeAndSubstituteInternal(AZStd::string& locString, const AZStd::vector& keys, const AZStd::vector& values)
 {
-    string outString;
+    AZStd::string outString;
     LocalizeString_ch(locString.c_str(), outString);
     locString = outString .c_str();
     if (values.size() != keys.size())
@@ -1866,7 +1896,7 @@ static void LogDecompTimer(__int64 nTotalTicks, __int64 nDecompTicks, __int64 nA
 }
 #endif
 
-string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const SLanguage* pLanguage) const
+AZStd::string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const SLanguage* pLanguage) const
 {
     FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled);
     if ((flags & IS_COMPRESSED) != 0)
@@ -1876,7 +1906,7 @@ string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const
         nTotalTicks = CryGetTicks();
 #endif  //LOG_DECOMP_TIMES
 
-        string outputString;
+        AZStd::string outputString;
         if (TranslatedText.szCompressed != NULL)
         {
             uint8 decompressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH];
@@ -1923,7 +1953,7 @@ string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const
         }
         else
         {
-            string emptyOutputString;
+            AZStd::string emptyOutputString;
             return emptyOutputString;
         }
     }
@@ -1949,7 +1979,7 @@ void CLocalizedStringsManager::ListAndClearProblemLabels()
         CryLog ("These labels caused localization problems:");
         INDENT_LOG_DURING_SCOPE();
 
-        for (std::map::iterator iter = m_warnedAboutLabels.begin(); iter != m_warnedAboutLabels.end(); iter++)
+        for (std::map::iterator iter = m_warnedAboutLabels.begin(); iter != m_warnedAboutLabels.end(); iter++)
         {
             CryLog ("%s", iter->first.c_str());
         }
@@ -1961,7 +1991,7 @@ void CLocalizedStringsManager::ListAndClearProblemLabels()
 #endif
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, string& outLocalString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, AZStd::string& outLocalString, bool bEnglish)
 {
     assert(sLabel);
     if (!m_pLanguage || !sLabel)
@@ -1979,8 +2009,7 @@ bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, string& outLoca
 
             if (entry != NULL)
             {
-                
-                string translatedText = entry->GetTranslatedText(m_pLanguage);
+                AZStd::string translatedText = entry->GetTranslatedText(m_pLanguage);
                 if ((bEnglish || translatedText.empty()) && entry->pEditorExtension != NULL)
                 {
                     //assert(!"No Localization Text available!");
@@ -2011,7 +2040,7 @@ bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, string& outLoca
 
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::GetEnglishString(const char* sKey, string& sLocalizedString)
+bool CLocalizedStringsManager::GetEnglishString(const char* sKey, AZStd::string& sLocalizedString)
 {
     assert(sKey);
     if (!m_pLanguage || !sKey)
@@ -2086,7 +2115,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalize
         const SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL);
         if (entry != NULL)
         {
-            outGameInfo.szCharacterName = entry->sCharacterName;
+            outGameInfo.szCharacterName = entry->sCharacterName.c_str();
             outGameInfo.sUtf8TranslatedText = entry->GetTranslatedText(m_pLanguage);
 
             outGameInfo.bUseSubtitle = (entry->flags & SLocalizedStringEntry::USE_SUBTITLE);
@@ -2119,7 +2148,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalize
         {
             bResult = true;
 
-            pOutSoundInfo->szCharacterName = pEntry->sCharacterName;
+            pOutSoundInfo->szCharacterName = pEntry->sCharacterName.c_str();
             pOutSoundInfo->sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage);
 
             //pOutSoundInfo->sOriginalActorLine = pEntry->sOriginalActorLine.c_str();
@@ -2213,7 +2242,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInf
     }
     const SLocalizedStringEntry* pEntry = entryVec[nIndex];
 
-    outGameInfo.szCharacterName = pEntry->sCharacterName;
+    outGameInfo.szCharacterName = pEntry->sCharacterName.c_str();
     outGameInfo.sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage);
 
     outGameInfo.bUseSubtitle = (pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE);
@@ -2233,18 +2262,18 @@ bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInf
         return false;
     }
     const SLocalizedStringEntry* pEntry = entryVec[nIndex];
-    outEditorInfo.szCharacterName = pEntry->sCharacterName;
+    outEditorInfo.szCharacterName = pEntry->sCharacterName.c_str();
     outEditorInfo.sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage);
 
     assert(pEntry->pEditorExtension != NULL);
 
-    outEditorInfo.sKey = pEntry->pEditorExtension->sKey;
+    outEditorInfo.sKey = pEntry->pEditorExtension->sKey.c_str();
 
-    outEditorInfo.sOriginalActorLine = pEntry->pEditorExtension->sOriginalActorLine;
-    outEditorInfo.sUtf8TranslatedActorLine = pEntry->pEditorExtension->sUtf8TranslatedActorLine;
+    outEditorInfo.sOriginalActorLine = pEntry->pEditorExtension->sOriginalActorLine.c_str();
+    outEditorInfo.sUtf8TranslatedActorLine = pEntry->pEditorExtension->sUtf8TranslatedActorLine.c_str();
 
     //outEditorInfo.sOriginalText = pEntry->sOriginalText;
-    outEditorInfo.sOriginalCharacterName = pEntry->pEditorExtension->sOriginalCharacterName;
+    outEditorInfo.sOriginalCharacterName = pEntry->pEditorExtension->sOriginalCharacterName.c_str();
 
     outEditorInfo.nRow = pEntry->pEditorExtension->nRow;
     outEditorInfo.bUseSubtitle = (pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE);
@@ -2252,7 +2281,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInf
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle)
+bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, AZStd::string& outSubtitle, bool bForceSubtitle)
 {
     assert(sKeyOrLabel);
     if (!m_pLanguage || !sKeyOrLabel || !*sKeyOrLabel)
@@ -2376,13 +2405,13 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CLocalizedStringsManager::FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams)
+void CLocalizedStringsManager::FormatStringMessage_List(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams)
 {
     InternalFormatStringMessage(outString, sString, sParams, nParams);
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CLocalizedStringsManager::FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2, const char* param3, const char* param4)
+void CLocalizedStringsManager::FormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2, const char* param3, const char* param4)
 {
     InternalFormatStringMessage(outString, sString, param1, param2, param3, param4);
 }
@@ -2462,7 +2491,7 @@ void CLocalizedStringsManager::InternalSetCurrentLanguage(CLocalizedStringsManag
 #if defined (WIN32) || defined(WIN64)
     if (m_pLanguage != 0)
     {
-        g_currentLanguageID = GetLanguageID(m_pLanguage->sLanguage);
+        g_currentLanguageID = GetLanguageID(m_pLanguage->sLanguage.c_str());
     }
     else
     {
@@ -2494,7 +2523,7 @@ void CLocalizedStringsManager::InternalSetCurrentLanguage(CLocalizedStringsManag
     }
 }
 
-void CLocalizedStringsManager::LocalizeDuration(int seconds, string& outDurationString)
+void CLocalizedStringsManager::LocalizeDuration(int seconds, AZStd::string& outDurationString)
 {
     int s = seconds;
     int d, h, m;
@@ -2504,27 +2533,27 @@ void CLocalizedStringsManager::LocalizeDuration(int seconds, string& outDuration
     s -= h * 3600;
     m = s / 60;
     s = s - m * 60;
-    string str;
+    AZStd::string str;
     if (d > 1)
     {
-        str.Format("%d @ui_days %02d:%02d:%02d", d, h, m, s);
+        str = AZStd::string::format("%d @ui_days %02d:%02d:%02d", d, h, m, s);
     }
     else if (d > 0)
     {
-        str.Format("%d @ui_day %02d:%02d:%02d", d, h, m, s);
+        str = AZStd::string::format("%d @ui_day %02d:%02d:%02d", d, h, m, s);
     }
     else if (h > 0)
     {
-        str.Format("%02d:%02d:%02d", h, m, s);
+        str = AZStd::string::format("%02d:%02d:%02d", h, m, s);
     }
     else
     {
-        str.Format("%02d:%02d", m, s);
+        str = AZStd::string::format("%02d:%02d", m, s);
     }
     LocalizeString_s(str, outDurationString);
 }
 
-void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberString)
+void CLocalizedStringsManager::LocalizeNumber(int number, AZStd::string& outNumberString)
 {
     if (number == 0)
     {
@@ -2535,7 +2564,7 @@ void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberStrin
     outNumberString.assign("");
 
     int n = abs(number);
-    string separator;
+    AZStd::string separator;
     AZStd::fixed_string<64> tmp;
     LocalizeString_ch("@ui_thousand_separator", separator);
     while (n > 0)
@@ -2544,41 +2573,41 @@ void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberStrin
         int b = n - (a * 1000);
         if (a > 0)
         {
-            tmp.Format("%s%03d%s", separator.c_str(), b, tmp.c_str());
+            tmp = AZStd::string::format("%s%03d%s", separator.c_str(), b, tmp.c_str());
         }
         else
         {
-            tmp.Format("%d%s", b, tmp.c_str());
+            tmp = AZStd::string::format("%d%s", b, tmp.c_str());
         }
         n = a;
     }
 
     if (number < 0)
     {
-        tmp.Format("-%s", tmp.c_str());
+        tmp = AZStd::string::format("-%s", tmp.c_str());
     }
 
     outNumberString.assign(tmp.c_str());
 }
 
-void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals, string& outNumberString)
+void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals, AZStd::string& outNumberString)
 {
     if (number == 0.0f)
     {
         AZStd::fixed_string<64> tmp;
-        tmp.Format("%.*f", decimals, number);
+        tmp = AZStd::fixed_string<64>::format("%.*f", decimals, number);
         outNumberString.assign(tmp.c_str());
         return;
     }
 
     outNumberString.assign("");
 
-    string commaSeparator;
+    AZStd::string commaSeparator;
     LocalizeString_ch("@ui_decimal_separator", commaSeparator);
     float f = number > 0.0f ? number : -number;
     int d = (int)f;
 
-    string intPart;
+    AZStd::string intPart;
     LocalizeNumber(d, intPart);
 
     float decimalsOnly = f - (float)d;
@@ -2586,7 +2615,7 @@ void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals
     int decimalsAsInt = aznumeric_cast(int_round(decimalsOnly * pow(10.0f, decimals)));
 
     AZStd::fixed_string<64> tmp;
-    tmp.Format("%s%s%0*d", intPart.c_str(), commaSeparator.c_str(), decimals, decimalsAsInt);
+    tmp = AZStd::fixed_string<64>::format("%s%s%0*d", intPart.c_str(), commaSeparator.c_str(), decimals, decimalsAsInt);
 
     outNumberString.assign(tmp.c_str());
 }
@@ -2640,7 +2669,7 @@ namespace
     }
 };
 
-void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString)
+void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString)
 {
     if (bMakeLocalTime)
     {
@@ -2664,7 +2693,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
     }
 }
 
-void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString)
+void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString)
 {
     if (bMakeLocalTime)
     {
@@ -2689,7 +2718,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
             // len includes terminating null!
             tmpString.resize(len);
             ::GetDateFormatW(lcID, 0, &systemTime, L"ddd", (wchar_t*) tmpString.c_str(), len);
-            string utf8;
+            AZStd::string utf8;
             Unicode::Convert(utf8, tmpString);
             outDateString.append(utf8);
             outDateString.append(" ");
@@ -2702,7 +2731,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
         // len includes terminating null!
         tmpString.resize(len);
         ::GetDateFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len);
-        string utf8;
+        AZStd::string utf8;
         Unicode::Convert(utf8, tmpString);
         outDateString.append(utf8);
     }
@@ -2710,7 +2739,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
 
 #else // #if defined (WIN32) || defined(WIN64)
 
-void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString)
+void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString)
 {
     struct tm theTime;
     if (bMakeLocalTime)
@@ -2737,7 +2766,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
     Unicode::Convert(outTimeString, buf);
 }
 
-void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString)
+void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString)
 {
     struct tm theTime;
     if (bMakeLocalTime)
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.h b/Code/Legacy/CrySystem/LocalizedStringManager.h
index 581a657c81..72a7916d1f 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.h
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.h
@@ -25,7 +25,7 @@ class CLocalizedStringsManager
     , public ISystemEventListener
 {
 public:
-    typedef std::vector TLocalizationTagVec;
+    typedef std::vector TLocalizationTagVec;
 
     constexpr const static size_t LOADING_FIXED_STRING_LENGTH = 2048;
     constexpr const static size_t COMPRESSION_FIXED_BUFFER_LENGTH = 6144;
@@ -56,11 +56,11 @@ public:
     void ReloadData() override;
     void FreeData();
 
-    bool LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish = false) override;
-    bool LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish = false) override;
+    bool LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish = false) override;
+    bool LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish = false) override;
 
     void LocalizeAndSubstituteInternal(AZStd::string& locString, const AZStd::vector& keys, const AZStd::vector& values) override;
-    bool LocalizeLabel(const char* sLabel, string& outLocalizedString, bool bEnglish = false) override;
+    bool LocalizeLabel(const char* sLabel, AZStd::string& outLocalizedString, bool bEnglish = false) override;
     bool IsLocalizedInfoFound(const char* sKey);
     bool GetLocalizedInfoByKey(const char* sKey, SLocalizedInfoGame& outGameInfo);
     bool GetLocalizedInfoByKey(const char* sKey, SLocalizedSoundInfoGame* pOutSoundInfoGame);
@@ -68,17 +68,17 @@ public:
     bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoGame& outGameInfo);
     bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoEditor& outEditorInfo);
 
-    bool GetEnglishString(const char* sKey, string& sLocalizedString) override;
-    bool GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle = false) override;
+    bool GetEnglishString(const char* sKey, AZStd::string& sLocalizedString) override;
+    bool GetSubtitle(const char* sKeyOrLabel, AZStd::string& outSubtitle, bool bForceSubtitle = false) override;
 
-    void FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams) override;
-    void FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) override;
+    void FormatStringMessage_List(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams) override;
+    void FormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) override;
 
-    void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) override;
-    void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) override;
-    void LocalizeDuration(int seconds, string& outDurationString) override;
-    void LocalizeNumber(int number, string& outNumberString) override;
-    void LocalizeNumber_Decimal(float number, int decimals, string& outNumberString) override;
+    void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString) override;
+    void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString) override;
+    void LocalizeDuration(int seconds, AZStd::string& outDurationString) override;
+    void LocalizeNumber(int number, AZStd::string& outNumberString) override;
+    void LocalizeNumber_Decimal(float number, int decimals, AZStd::string& outNumberString) override;
 
     bool ProjectUsesLocalization() const override;
     // ~ILocalizationManager
@@ -95,7 +95,7 @@ public:
 private:
     void SetAvailableLocalizationsBitfield(const ILocalizationManager::TLocalizationBitfield availableLocalizations);
 
-    bool LocalizeStringInternal(const char* pStr, size_t len, string& outLocalizedString, bool bEnglish);
+    bool LocalizeStringInternal(const char* pStr, size_t len, AZStd::string& outLocalizedString, bool bEnglish);
 
     bool DoLoadExcelXmlSpreadsheet(const char* sFileName, uint8 tagID, bool bReload);
     typedef bool(CLocalizedStringsManager::*LoadFunc)(const char*, uint8, bool);
@@ -104,11 +104,11 @@ private:
 
     struct SLocalizedStringEntryEditorExtension
     {
-        string  sKey;                                           // Map key text equivalent (without @)
-        string  sOriginalActorLine;             // english text
-        string  sUtf8TranslatedActorLine;       // localized text
-        string  sOriginalText;                      // subtitle. if empty, uses English text
-        string  sOriginalCharacterName;     // english character name speaking via XML asset
+        AZStd::string  sKey;                                           // Map key text equivalent (without @)
+        AZStd::string  sOriginalActorLine;             // english text
+        AZStd::string  sUtf8TranslatedActorLine;       // localized text
+        AZStd::string  sOriginalText;                      // subtitle. if empty, uses English text
+        AZStd::string  sOriginalCharacterName;     // english character name speaking via XML asset
 
         unsigned int nRow;                              // Number of row in XML file
 
@@ -141,15 +141,15 @@ private:
 
         union trans_text
         {
-            string*     psUtf8Uncompressed;
+            AZStd::string*     psUtf8Uncompressed;
             uint8*      szCompressed;       // Note that no size information is stored. This is for struct size optimization and unfortunately renders the size info inaccurate.
         };
 
-        string sCharacterName;  // character name speaking via XML asset
+        AZStd::string sCharacterName;  // character name speaking via XML asset
         trans_text TranslatedText;  // Subtitle of this line
 
         // audio specific part
-        string      sPrototypeSoundEvent;           // associated sound event prototype (radio, ...)
+        AZStd::string      sPrototypeSoundEvent;           // associated sound event prototype (radio, ...)
         CryHalf     fVolume;
         CryHalf     fRadioRatio;
         // SoundMoods
@@ -191,7 +191,7 @@ private:
             }
         };
 
-        string GetTranslatedText(const SLanguage* pLanguage) const;
+        AZStd::string GetTranslatedText(const SLanguage* pLanguage) const;
 
         void GetMemoryUsage(ICrySizer* pSizer) const
         {
@@ -224,7 +224,7 @@ private:
         typedef std::vector TLocalizedStringEntries;
         typedef std::vector THuffmanCoders;
 
-        string sLanguage;
+        AZStd::string sLanguage;
         StringsKeyMap m_keysMap;
         TLocalizedStringEntries m_vLocalizedStrings;
         THuffmanCoders m_vEncoders;
@@ -246,7 +246,7 @@ private:
     };
 
 #ifndef _RELEASE
-    std::map m_warnedAboutLabels;
+    std::map m_warnedAboutLabels;
     bool m_haveWarnedAboutAtLeastOneLabel;
 
     void LocalizedStringsManagerWarning(const char* label, const char* message);
@@ -259,45 +259,45 @@ private:
     void AddLocalizedString(SLanguage* pLanguage, SLocalizedStringEntry* pEntry, const uint32 keyCRC32);
     void AddControl(int nKey);
     //////////////////////////////////////////////////////////////////////////
-    void ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex);
+    void ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex);
     void InternalSetCurrentLanguage(SLanguage* pLanguage);
     ISystem* m_pSystem;
     // Pointer to the current language.
     SLanguage* m_pLanguage;
 
     // all loaded Localization Files
-    typedef std::pair pairFileName;
-    typedef std::map tmapFilenames;
+    typedef std::pair pairFileName;
+    typedef std::map tmapFilenames;
     tmapFilenames m_loadedTables;
 
 
     // filenames per tag
-    typedef std::vector TStringVec;
+    typedef std::vector TStringVec;
     struct STag
     {
         TStringVec  filenames;
         uint8               id;
         bool                loaded;
     };
-    typedef std::map TTagFileNames;
+    typedef std::map TTagFileNames;
     TTagFileNames m_tagFileNames;
     TStringVec m_tagLoadRequests;
 
     // Array of loaded languages.
     std::vector m_languages;
 
-    typedef std::set PrototypeSoundEvents;
+    typedef std::set PrototypeSoundEvents;
     PrototypeSoundEvents m_prototypeEvents;  // this set is purely used for clever string/string assigning to save memory
 
     struct less_strcmp
     {
-        bool operator()(const string& left, const string& right) const
+        bool operator()(const AZStd::string& left, const AZStd::string& right) const
         {
             return strcmp(left.c_str(), right.c_str()) < 0;
         }
     };
 
-    typedef std::set CharacterNameSet;
+    typedef std::set CharacterNameSet;
     CharacterNameSet m_characterNameSet; // this set is purely used for clever string/string assigning to save memory
 
     // CVARs
diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp
index 2c7c307d50..c23ed6e264 100644
--- a/Code/Legacy/CrySystem/Log.cpp
+++ b/Code/Legacy/CrySystem/Log.cpp
@@ -466,7 +466,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
     {
     case eWarning:
     case eWarningAlways:
-        cry_strcpy(szString, MAX_WARNING_LENGTH, "$6[Warning] ");
+        azstrcpy(szString, MAX_WARNING_LENGTH, "$6[Warning] ");
         szString += 12;     // strlen("$6[Warning] ");
         szAfterColour += 2;
         prefixSize = 12;
@@ -474,7 +474,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
 
     case eError:
     case eErrorAlways:
-        cry_strcpy(szString, MAX_WARNING_LENGTH, "$4[Error] ");
+        azstrcpy(szString, MAX_WARNING_LENGTH, "$4[Error] ");
         szString += 10;     // strlen("$4[Error] ");
         szAfterColour += 2;
         prefixSize = 10;
@@ -532,7 +532,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
             }
         }
         i = m_iLastHistoryItem = m_iLastHistoryItem + 1 & sz - 1;
-        cry_strcpy(m_history[i].str, m_history[i].ptr = szSpamCheck);
+        azstrcpy(m_history[i].str, m_history[i].ptr = szSpamCheck);
         m_history[i].type = type;
         m_history[i].time = time;
     }
@@ -956,7 +956,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
             {
                 timeStr.clear();
                 uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
-                timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
+                timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
                 tempString = timeStr + tempString;
             }
             lasttime = currenttime;
@@ -983,7 +983,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
             {
                 timeStr.clear();
                 uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
-                timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
+                timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
                 tempString = timeStr + tempString;
             }
             lasttime = currenttime;
@@ -1000,7 +1000,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
                 {
                     timeStr.clear();
                     uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
-                    timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
+                    timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
                     tempString = timeStr + tempString;
                 }
                 if (bFirst)
@@ -1218,10 +1218,10 @@ void CLog::CreateBackupFile() const
 
     // boswej: only create a backup if logging to the engine root, otherwise the
     // log output has been overridden and the user is responsible
-    string logDir = PathUtil::RemoveSlash(PathUtil::ToUnixPath(PathUtil::GetParentDirectory(m_szFilename)));
+    AZStd::string logDir = PathUtil::RemoveSlash(PathUtil::ToUnixPath(PathUtil::GetParentDirectory(m_szFilename)));
 
-    string sExt = PathUtil::GetExt(m_szFilename);
-    string sFileWithoutExt = PathUtil::GetFileName(m_szFilename);
+    AZStd::string sExt = PathUtil::GetExt(m_szFilename);
+    AZStd::string sFileWithoutExt = PathUtil::GetFileName(m_szFilename);
 
     {
         assert(::strstr(sFileWithoutExt, ":") == 0);
@@ -1234,14 +1234,14 @@ void CLog::CreateBackupFile() const
     AZ::IO::HandleType inFileHandle = AZ::IO::InvalidHandle;
     fileSystem->Open(m_szFilename, AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, inFileHandle);
 
-    string sBackupNameAttachment;
+    AZStd::string sBackupNameAttachment;
 
     // parse backup name attachment
     // e.g. BackupNameAttachment="attachment name"
     if (inFileHandle != AZ::IO::InvalidHandle)
     {
         bool bKeyFound = false;
-        string sName;
+        AZStd::string sName;
 
         while (!fileSystem->Eof(inFileHandle))
         {
@@ -1253,7 +1253,7 @@ void CLog::CreateBackupFile() const
                 {
                     bKeyFound = true;
 
-                    if (sName.find("BackupNameAttachment=") == string::npos)
+                    if (sName.find("BackupNameAttachment=") == AZStd::string::npos)
                     {
 #ifdef WIN32
                         OutputDebugString("Log::CreateBackupFile ERROR '");
@@ -1284,12 +1284,12 @@ void CLog::CreateBackupFile() const
         fileSystem->Close(inFileHandle);
     }
 
-    string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt);
+    AZStd::string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt);
     fileSystem->CreatePath(LOG_BACKUP_PATH);
     azstrcpy(m_sBackupFilename, bakdest.c_str());
     // Remove any existing backup file with the same name first since the copy will fail otherwise.
     fileSystem->Remove(m_sBackupFilename);
-    fileSystem->Copy(m_szFilename, bakdest);
+    fileSystem->Copy(m_szFilename, bakdest.c_str());
 #endif // AZ_LEGACY_CRYSYSTEM_TRAIT_ALLOW_CREATE_BACKUP_LOG_FILE
 }
 
diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp
index bf4de8489d..9c2e1b1129 100644
--- a/Code/Legacy/CrySystem/System.cpp
+++ b/Code/Legacy/CrySystem/System.cpp
@@ -88,14 +88,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
     }
 
     // Handle with the default procedure
-#if defined(UNICODE) || defined(_UNICODE)
     assert(IsWindowUnicode(hWnd) && "Window should be Unicode when compiling with UNICODE");
-#else
-    if (!IsWindowUnicode(hWnd))
-    {
-        return DefWindowProcA(hWnd, uMsg, wParam, lParam);
-    }
-#endif
     return DefWindowProcW(hWnd, uMsg, wParam, lParam);
 }
 #endif
@@ -138,7 +131,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
 #include "RemoteConsole/RemoteConsole.h"
 
 #include 
-#include 
 
 #include 
 #include 
@@ -1209,10 +1201,11 @@ void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CSystem::GetLocalizedPath(const char* sLanguage, string& sLocalizedPath)
+void CSystem::GetLocalizedPath(const char* sLanguage, AZStd::string& sLocalizedPath)
 {
     // Omit the trailing slash!
-    string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
+    AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
+    sLocalizationFolder.pop_back();
 
     int locFormat = 0;
     LocalizationManagerRequestBus::BroadcastResult(locFormat, &LocalizationManagerRequestBus::Events::GetLocalizationFormat);
@@ -1228,16 +1221,17 @@ void CSystem::GetLocalizedPath(const char* sLanguage, string& sLocalizedPath)
     }
     else
     {
-        sLocalizedPath = string("Localized/") + sLanguage + "_xml.pak";
+        sLocalizedPath = AZStd::string("Localized/") + sLanguage + "_xml.pak";
         }
     }
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CSystem::GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPath)
+void CSystem::GetLocalizedAudioPath(const char* sLanguage, AZStd::string& sLocalizedPath)
 {
     // Omit the trailing slash!
-    string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
+    AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
+    sLocalizationFolder.pop_back();
 
     if (sLocalizationFolder.compareNoCase("Languages") != 0)
     {
@@ -1245,14 +1239,14 @@ void CSystem::GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPat
     }
     else
     {
-        sLocalizedPath = string("Localized/") + sLanguage + ".pak";
+        sLocalizedPath = AZStd::string("Localized/") + sLanguage + ".pak";
     }
 }
 
 //////////////////////////////////////////////////////////////////////////
 void CSystem::CloseLanguagePak(const char* sLanguage)
 {
-    string sLocalizedPath;
+    AZStd::string sLocalizedPath;
     GetLocalizedPath(sLanguage, sLocalizedPath);
     m_env.pCryPak->ClosePacks({ sLocalizedPath.c_str(), sLocalizedPath.size() });
 }
@@ -1260,7 +1254,7 @@ void CSystem::CloseLanguagePak(const char* sLanguage)
 //////////////////////////////////////////////////////////////////////////
 void CSystem::CloseLanguageAudioPak(const char* sLanguage)
 {
-    string sLocalizedPath;
+    AZStd::string sLocalizedPath;
     GetLocalizedAudioPath(sLanguage, sLocalizedPath);
     m_env.pCryPak->ClosePacks({ sLocalizedPath.c_str(), sLocalizedPath.size() });
 }
@@ -1334,11 +1328,11 @@ void CSystem::ExecuteCommandLine(bool deferred)
 
         if (pCmd->GetType() == eCLAT_Post)
         {
-            string sLine = pCmd->GetName();
+            AZStd::string sLine = pCmd->GetName();
             {
                 if (pCmd->GetValue())
                 {
-                    sLine += string(" ") + pCmd->GetValue();
+                    sLine += AZStd::string(" ") + pCmd->GetValue();
                 }
 
                 GetILog()->Log("Executing command from command line: \n%s\n", sLine.c_str()); // - the actual command might be executed much later (e.g. level load pause)
diff --git a/Code/Legacy/CrySystem/System.h b/Code/Legacy/CrySystem/System.h
index c66b2aab60..b6c4e0a96a 100644
--- a/Code/Legacy/CrySystem/System.h
+++ b/Code/Legacy/CrySystem/System.h
@@ -453,7 +453,7 @@ private:
     bool ReLaunchMediaCenter();
     void UpdateAudioSystems();
 
-    void AddCVarGroupDirectory(const string& sPath);
+    void AddCVarGroupDirectory(const AZStd::string& sPath);
 
     AZStd::unique_ptr LoadDynamiclibrary(const char* dllName) const;
 
@@ -623,7 +623,7 @@ private: // ------------------------------------------------------
     //  ICVar *m_sys_filecache;
     ICVar* m_gpu_particle_physics;
 
-    string  m_sSavedRDriver;                                //!< to restore the driver when quitting the dedicated server
+    AZStd::string  m_sSavedRDriver;                                //!< to restore the driver when quitting the dedicated server
 
     //////////////////////////////////////////////////////////////////////////
     //! User define callback for system events.
@@ -672,8 +672,8 @@ public:
     void OpenBasicPaks();
     void OpenLanguagePak(const char* sLanguage);
     void OpenLanguageAudioPak(const char* sLanguage);
-    void GetLocalizedPath(const char* sLanguage, string& sLocalizedPath);
-    void GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPath);
+    void GetLocalizedPath(const char* sLanguage, AZStd::string& sLocalizedPath);
+    void GetLocalizedAudioPath(const char* sLanguage, AZStd::string& sLocalizedPath);
     void CloseLanguagePak(const char* sLanguage);
     void CloseLanguageAudioPak(const char* sLanguage);
     void UpdateMovieSystem(const int updateFlags, const float fFrameTime, const bool bPreUpdate);
@@ -718,14 +718,14 @@ protected: // -------------------------------------------------------------
 
     CCmdLine*                                      m_pCmdLine;
 
-    string  m_currentLanguageAudio;
-    string  m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_android.cfg or system_windows_pc.cfg
+    AZStd::string  m_currentLanguageAudio;
+    AZStd::string  m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_android.cfg or system_windows_pc.cfg
 
     std::vector< std::pair > m_updateTimes;
 
     struct SErrorMessage
     {
-        string m_Message;
+        AZStd::string m_Message;
         float m_fTimeToShow;
         float m_Color[4];
         bool m_HardFailure;
diff --git a/Code/Legacy/CrySystem/SystemCFG.cpp b/Code/Legacy/CrySystem/SystemCFG.cpp
index 719928384b..062713c015 100644
--- a/Code/Legacy/CrySystem/SystemCFG.cpp
+++ b/Code/Legacy/CrySystem/SystemCFG.cpp
@@ -279,7 +279,7 @@ public:
         int nFlags = pCVar->GetFlags();
         if (((nFlags & VF_DUMPTODISK) && (nFlags & VF_MODIFIED)) || (nFlags & VF_WASINCONFIG))
         {
-            string szValue = pCVar->GetString();
+            AZStd::string szValue = pCVar->GetString();
             int pos;
 
             pos = 1;
@@ -287,7 +287,7 @@ public:
             {
                 pos = szValue.find_first_of("\\", pos);
 
-                if (pos == string::npos)
+                if (pos == AZStd::string::npos)
                 {
                     break;
                 }
@@ -302,7 +302,7 @@ public:
             {
                 pos = szValue.find_first_of("\"", pos);
 
-                if (pos == string::npos)
+                if (pos == AZStd::string::npos)
                 {
                     break;
                 }
@@ -311,7 +311,7 @@ public:
                 pos += 2;
             }
 
-            string szLine = pCVar->GetName();
+            AZStd::string szLine = pCVar->GetName();
 
             if (pCVar->GetType() == CVAR_STRING)
             {
@@ -344,7 +344,7 @@ void CSystem::SaveConfiguration()
 //////////////////////////////////////////////////////////////////////////
 // system cfg
 //////////////////////////////////////////////////////////////////////////
-CSystemConfiguration::CSystemConfiguration(const string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing)
+CSystemConfiguration::CSystemConfiguration(const AZStd::string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing)
     : m_strSysConfigFilePath(strSysConfigFilePath)
     , m_bError(false)
     , m_pSink(pSink)
@@ -364,14 +364,14 @@ CSystemConfiguration::~CSystemConfiguration()
 //////////////////////////////////////////////////////////////////////////
 bool CSystemConfiguration::ParseSystemConfig()
 {
-    string filename = m_strSysConfigFilePath;
-    if (strlen(PathUtil::GetExt(filename)) == 0)
+    AZStd::string filename = m_strSysConfigFilePath;
+    if (strlen(PathUtil::GetExt(filename.c_str())) == 0)
     {
         filename = PathUtil::ReplaceExtension(filename, "cfg");
     }
 
     CCryFile file;
-    string filenameLog;
+    AZStd::string filenameLog;
     {
         int flags = AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK;
 
@@ -380,7 +380,7 @@ bool CSystemConfiguration::ParseSystemConfig()
             // this is used when theres a very specific file to read, like @user@/game.cfg which is read
             // IN ADDITION to the one in the game folder, and afterwards to override values in it.
             // if the file is missing and its already prefixed with an alias, there is no need to look any further.
-            if (!(file.Open(filename, "rb", flags)))
+            if (!(file.Open(filename.c_str(), "rb", flags)))
             {
                 if (m_warnIfMissing)
                 {
@@ -394,11 +394,11 @@ bool CSystemConfiguration::ParseSystemConfig()
             // otherwise, if the file isn't prefixed with an alias, then its likely one of the convenience mappings
             // to either root or assets/config.  this is done so that code can just request a simple file name and get its data
             if (
-                !(file.Open(filename, "rb", flags)) &&
-                !(file.Open(string("@root@/") + filename, "rb", flags)) &&
-                !(file.Open(string("@assets@/") + filename, "rb", flags)) &&
-                !(file.Open(string("@assets@/config/") + filename, "rb", flags)) &&
-                !(file.Open(string("@assets@/config/spec/") + filename, "rb", flags))
+                !(file.Open(filename.c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@root@/") + filename).c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@assets@/") + filename).c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@assets@/config/") + filename).c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@assets@/config/spec/") + filename).c_str(), "rb", flags))
                 )
             {
                 if (m_warnIfMissing)
@@ -429,7 +429,7 @@ bool CSystemConfiguration::ParseSystemConfig()
     sAllText[nLen] = '\0';
     sAllText[nLen + 1] = '\0';
 
-    string strGroup;            // current group e.g. "[General]"
+    AZStd::string strGroup;            // current group e.g. "[General]"
 
     char* strLast = sAllText + nLen;
     char* str = sAllText;
@@ -447,11 +447,11 @@ bool CSystemConfiguration::ParseSystemConfig()
             str++;
         }
 
-        string strLine = s;
+        AZStd::string strLine = s;
 
         // detect groups e.g. "[General]"   should set strGroup="General"
         {
-            string strTrimmedLine(RemoveWhiteSpaces(strLine));
+            AZStd::string strTrimmedLine(RemoveWhiteSpaces(strLine));
             size_t size = strTrimmedLine.size();
 
             if (size >= 3)
@@ -466,7 +466,7 @@ bool CSystemConfiguration::ParseSystemConfig()
         }
 
         //trim all whitespace characters at the beginning and the end of the current line and store its size
-        strLine.Trim();
+        AZ::StringFunc::TrimWhiteSpace(strLine, true, true);
         size_t strLineSize = strLine.size();
 
         //skip comments, comments start with ";" or "--" but may have preceding whitespace characters
@@ -488,35 +488,35 @@ bool CSystemConfiguration::ParseSystemConfig()
         }
 
         //if line contains a '=' try to read and assign console variable
-        string::size_type posEq(strLine.find("=", 0));
-        if (string::npos != posEq)
+        AZStd::string::size_type posEq(strLine.find("=", 0));
+        if (AZStd::string::npos != posEq)
         {
-            string stemp(strLine, 0, posEq);
-            string strKey(RemoveWhiteSpaces(stemp));
+            AZStd::string stemp(strLine, 0, posEq);
+            AZStd::string strKey(RemoveWhiteSpaces(stemp));
 
             {
                 // extract value
-                string::size_type posValueStart(strLine.find("\"", posEq + 1) + 1);
-                string::size_type posValueEnd(strLine.rfind('\"'));
+                AZStd::string::size_type posValueStart(strLine.find("\"", posEq + 1) + 1);
+                AZStd::string::size_type posValueEnd(strLine.rfind('\"'));
 
-                string strValue;
+                AZStd::string strValue;
 
-                if (string::npos != posValueStart && string::npos != posValueEnd)
+                if (AZStd::string::npos != posValueStart && AZStd::string::npos != posValueEnd)
                 {
-                    strValue = string(strLine, posValueStart, posValueEnd - posValueStart);
+                    strValue = AZStd::string(strLine, posValueStart, posValueEnd - posValueStart);
                 }
                 else
                 {
-                    string strTmp(strLine, posEq + 1, strLine.size() - (posEq + 1));
+                    AZStd::string strTmp(strLine, posEq + 1, strLine.size() - (posEq + 1));
                     strValue = RemoveWhiteSpaces(strTmp);
                 }
 
                 {
                     // replace '\\\\' with '\\' and '\\\"' with '\"'
-                    strValue.replace("\\\\", "\\");
-                    strValue.replace("\\\"", "\"");
+                    AZ::StringFunc::Replace(strValue, "\\\\", "\\");
+                    AZ::StringFunc::Replace(strValue, "\\\"", "\"");
                     
-                    m_pSink->OnLoadConfigurationEntry(strKey, strValue, strGroup);
+                    m_pSink->OnLoadConfigurationEntry(strKey.c_str(), strValue.c_str(), strGroup.c_str());
                 }
             }
         }
diff --git a/Code/Legacy/CrySystem/SystemCFG.h b/Code/Legacy/CrySystem/SystemCFG.h
index ac4f04d146..cfaefd2e45 100644
--- a/Code/Legacy/CrySystem/SystemCFG.h
+++ b/Code/Legacy/CrySystem/SystemCFG.h
@@ -15,17 +15,17 @@
 #include 
 #include 
 
-typedef string SysConfigKey;
-typedef string SysConfigValue;
+typedef AZStd::string SysConfigKey;
+typedef AZStd::string SysConfigValue;
 
 //////////////////////////////////////////////////////////////////////////
 class CSystemConfiguration
 {
 public:
-    CSystemConfiguration(const string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing = true);
+    CSystemConfiguration(const AZStd::string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing = true);
     ~CSystemConfiguration();
 
-    string RemoveWhiteSpaces(string& s)
+    AZStd::string RemoveWhiteSpaces(AZStd::string& s)
     {
         s.Trim();
         return s;
@@ -39,10 +39,10 @@ private: // ----------------------------------------
     //   success
     bool ParseSystemConfig();
 
-    CSystem*                                               m_pSystem;
-    string                                                  m_strSysConfigFilePath;
-    bool                                                        m_bError;
-    ILoadConfigurationEntrySink*       m_pSink;                                         // never 0
+    CSystem*                           m_pSystem;
+    AZStd::string                      m_strSysConfigFilePath;
+    bool                               m_bError;
+    ILoadConfigurationEntrySink*       m_pSink;  // never 0
     bool m_warnIfMissing;
 };
 
diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp
index cce3cf4aec..ae177a9974 100644
--- a/Code/Legacy/CrySystem/SystemInit.cpp
+++ b/Code/Legacy/CrySystem/SystemInit.cpp
@@ -33,7 +33,6 @@
 
 #include "CryLibrary.h"
 #include "CryPath.h"
-#include 
 
 #include 
 #include 
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index 943a540ae6..a4be0e5054 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -505,9 +505,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
             if (bSucceeded)
             {
                 // Convert from UNICODE to UTF-8
-                AZStd::string str;
-                AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath));
-                azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str());
+                azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
                 CoTaskMemFree(wMyDocumentsPath);
             }
         }
@@ -521,9 +519,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
         bSucceeded = SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, wMyDocumentsPath));
         if (bSucceeded)
         {
-            AZStd::string str;
-            AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath));
-            azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str());
+            azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
         }
     }
 
diff --git a/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h b/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h
index 2634195f64..b4dd28e813 100644
--- a/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h
+++ b/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h
@@ -36,7 +36,7 @@ public:
     ELSE_LOAD_PROPERTY(Vec3);                       \
     ELSE_LOAD_PROPERTY(int);                        \
     ELSE_LOAD_PROPERTY(float);                      \
-    ELSE_LOAD_PROPERTY(string);                     \
+    ELSE_LOAD_PROPERTY(AZStd::string);              \
     ELSE_LOAD_PROPERTY(bool);
 
 
diff --git a/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp b/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp
index bddc538bba..e75fed22ed 100644
--- a/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp
+++ b/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp
@@ -13,7 +13,7 @@
 #include 
 #include 
 
-typedef std::map IdTable;
+typedef std::map IdTable;
 struct SParseParams
 {
     IdTable idTable;
@@ -98,7 +98,7 @@ struct ReadPropertyTyped
 };
 
 template <>
-struct ReadPropertyTyped
+struct ReadPropertyTyped
 {
     static bool Load(const SParseParams& parseParams, const char* name, XmlNodeRef& definition, XmlNodeRef& data, IReadXMLSink* pSink)
     {
@@ -235,8 +235,9 @@ bool LoadProperty(const SParseParams& parseParams, XmlNodeRef& definition, XmlNo
 
             dataToRead = GetISystem()->CreateXmlNode(data->getTag());
 
-            string content = childRef->getContent();
-            dataToRead->setAttr(name, content.Trim().c_str());
+            AZStd::string content = childRef->getContent();
+            AZ::StringFunc::TrimWhiteSpace(content, true, true);
+            dataToRead->setAttr(name, content.c_str());
         }
 
         if (!dataToRead->haveAttr(name))
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
index e98071ace0..26007eb229 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
@@ -114,7 +114,7 @@ void CSerializeXMLWriterImpl::GetMemoryUsage(ICrySizer* pSizer) const
 //////////////////////////////////////////////////////////////////////////
 const char* CSerializeXMLWriterImpl::GetStackInfo() const
 {
-    static string str;
+    static AZStd::string str;
     str.assign("");
     for (int i = 0; i < (int)m_nodeStack.size(); i++)
     {
@@ -138,7 +138,7 @@ const char* CSerializeXMLWriterImpl::GetStackInfo() const
 //////////////////////////////////////////////////////////////////////////
 const char* CSerializeXMLWriterImpl::GetLuaStackInfo() const
 {
-    static string str;
+    static AZStd::string str;
     str.assign("");
     for (int i = 0; i < (int)m_luaSaveStack.size(); i++)
     {
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
index 12a2f6f151..41dbe3dd7b 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
@@ -138,7 +138,7 @@ private:
     bool IsDefaultValue(const Quat& v) const { return v.w == 1.0f && v.v.x == 0 && v.v.y == 0 && v.v.z == 0; };
     bool IsDefaultValue(const CTimeValue& v) const { return v.GetValue() == 0; };
     bool IsDefaultValue(const char* str) const { return !str || !*str; };
-    bool IsDefaultValue(const string& str) const { return str.empty(); };
+    bool IsDefaultValue(const AZStd::string& str) const { return str.empty(); };
     bool IsDefaultValue(const SSerializeString& str) const { return str.empty(); };
     //////////////////////////////////////////////////////////////////////////
 
diff --git a/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp b/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp
index 2a532befd3..b0d7a6f1af 100644
--- a/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp
+++ b/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp
@@ -12,7 +12,7 @@
 
 #include 
 
-typedef std::map IdTable;
+typedef std::map IdTable;
 
 static bool IsOptionalWriteXML(XmlNodeRef& definition);
 
@@ -66,7 +66,7 @@ struct WritePropertyTyped
 };
 
 template <>
-struct WritePropertyTyped
+struct WritePropertyTyped
     : public WritePropertyTyped
 {
 };
diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h
index 7dcbe075cd..810a2268c9 100644
--- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h
+++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h
@@ -25,25 +25,25 @@ namespace XMLBinary
     {
     public:
         CXMLBinaryWriter();
-        bool WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, string& error);
+        bool WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, AZStd::string & error);
 
     private:
-        bool CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error);
+        bool CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error);
 
-        bool CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, string& error);
-        bool CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error);
+        bool CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, AZStd::string& error);
+        bool CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error);
         int AddString(const XmlString& sString);
 
     private:
         // tables.
         typedef std::map NodesMap;
-        typedef std::map StringMap;
+        typedef std::map StringMap;
 
         std::vector m_nodes;
         NodesMap m_nodesMap;
         std::vector m_attributes;
         std::vector m_childs;
-        std::vector m_strings;
+        std::vector m_strings;
         StringMap m_stringMap;
 
         uint m_nStringDataSize;
diff --git a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp
index ff4cfc91d2..03c5af92d3 100644
--- a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp
+++ b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp
@@ -9,7 +9,6 @@
 
 #include "CrySystem_precompiled.h"
 #include "XMLPatcher.h"
-#include "StringUtils.h"
 
 CXMLPatcher::CXMLPatcher(XmlNodeRef& patchXML)
 {
@@ -84,7 +83,7 @@ XmlNodeRef CXMLPatcher::FindPatchForFile(
             {
                 const char* pForFile = child->getAttr("forfile");
 
-                if (pForFile && CryStringUtils::stristr(pForFile, pInFileToPatch) != 0)
+                if (pForFile && AZ::StringFunc::Find(pForFile, pInFileToPatch) != AZStd::string::npos)
                 {
                     result = child;
                     break;
@@ -353,7 +352,7 @@ void CXMLPatcher::DumpXMLNodes(
 
     INDENT();
 
-    ioTempString->Format("<%s ", inNode->getTag());
+    *ioTempString = AZStd::fixed_string<512>::format("<%s ", inNode->getTag());
 
     pPak->FWrite(ioTempString->c_str(), ioTempString->length(), inFileHandle);
 
@@ -361,7 +360,7 @@ void CXMLPatcher::DumpXMLNodes(
     {
         const char* pKey, * pVal;
         inNode->getAttributeByIndex(i, &pKey, &pVal);
-        ioTempString->Format("%s=\"%s\" ", pKey, pVal);
+        *ioTempString = AZStd::fixed_string<512>::format("%s=\"%s\" ", pKey, pVal);
         pPak->FWrite(ioTempString->c_str(), ioTempString->length(), inFileHandle);
     }
     pPak->FWrite(">\n", 2, inFileHandle);
@@ -372,7 +371,7 @@ void CXMLPatcher::DumpXMLNodes(
     }
 
     INDENT();
-    ioTempString->Format("\n", inNode->getTag());
+    *ioTempString = AZStd::fixed_string<512>::format("\n", inNode->getTag());
     pPak->FWrite(ioTempString->c_str(), ioTempString->length(), inFileHandle);
 }
 
@@ -391,12 +390,12 @@ void CXMLPatcher::DumpFiles(
         {
             pOrigFileName++;
 
-            DumpXMLFile(string().Format("PATCH_%s", pOrigFileName), inBefore);
+            DumpXMLFile(AZStd::string::format("PATCH_%s", pOrigFileName).c_str(), inBefore);
 
-            AZStd::fixed_string<128>        newFileName(pOrigFileName);
-            newFileName.replace(".xml", "_patched.xml");
+            AZStd::string newFileName(pOrigFileName);
+            AZ::StringFunc::Replace(newFileName, ".xml", "_patched.xml");
 
-            DumpXMLFile(string().Format("PATCH_%s", newFileName.c_str()), inAfter);
+            DumpXMLFile(AZStd::string::format("PATCH_%s", newFileName.c_str()).c_str(), inAfter);
         }
         else
         {
diff --git a/Code/Legacy/CrySystem/XML/XmlUtils.cpp b/Code/Legacy/CrySystem/XML/XmlUtils.cpp
index 1b341ee99e..5e31fff8d7 100644
--- a/Code/Legacy/CrySystem/XML/XmlUtils.cpp
+++ b/Code/Legacy/CrySystem/XML/XmlUtils.cpp
@@ -313,7 +313,7 @@ bool CXmlUtils::SaveBinaryXmlFile(const char* filename, XmlNodeRef root)
         return false;
     }
     XMLBinary::CXMLBinaryWriter writer;
-    string error;
+    AZStd::string error;
     return writer.WriteNode(&fileSink, root, false, 0, error);
 }
 
diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp
index c6e660155f..728d9441f2 100644
--- a/Code/Legacy/CrySystem/XML/xml.cpp
+++ b/Code/Legacy/CrySystem/XML/xml.cpp
@@ -984,13 +984,13 @@ XmlString CXmlNode::MakeValidXmlString(const XmlString& instr) const
     XmlString str = instr;
 
     // check if str contains any invalid characters
-    str.replace("&", "&");
-    str.replace("\"", """);
-    str.replace("\'", "'");
-    str.replace("<", "<");
-    str.replace(">", ">");
-    str.replace("...", ">");
-    str.replace("\n", "
");
+    AZ::StringFunc::Replace(str, "&", "&");
+    AZ::StringFunc::Replace(str, "\"", """);
+    AZ::StringFunc::Replace(str, "\'", "'");
+    AZ::StringFunc::Replace(str, "<", "<");
+    AZ::StringFunc::Replace(str, ">", ">");
+    AZ::StringFunc::Replace(str, "...", ">");
+    AZ::StringFunc::Replace(str, "\n", "
");
 
     return str;
 }
@@ -1732,9 +1732,9 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString,
             return 0;
         }
         adjustedFilename = xmlFile.GetAdjustedFilename();
-        adjustedFilename.replace('\\', '/');
+        AZStd::replace(adjustedFilename.begin(), adjustedFilename.end(), '\\', '/');
         pakPath = xmlFile.GetPakPath();
-        pakPath.replace('\\', '/');
+        AZStd::replace(pakPath.begin(), pakPath.end(), '\\', '/');
     }
 
     if (g_bEnableBinaryXmlLoading)
diff --git a/Code/Tools/GridHub/GridHub/gridhub.cpp b/Code/Tools/GridHub/GridHub/gridhub.cpp
index f6f0988022..3dbecf681f 100644
--- a/Code/Tools/GridHub/GridHub/gridhub.cpp
+++ b/Code/Tools/GridHub/GridHub/gridhub.cpp
@@ -362,13 +362,9 @@ GridHubComponent::GridHubComponent()
     DWORD dwCompNameLen = AZ_ARRAY_SIZE(name);
     if ( GetComputerName(name, &dwCompNameLen) != 0 ) 
     {
-#ifdef _UNICODE
         char c[MAX_COMPUTERNAME_LENGTH + 1];
         wcstombs(c, name, AZ_ARRAY_SIZE(c));
         m_hubName = c;
-#else
-        m_hubName = name;
-#endif
     }
     else
 #endif
diff --git a/Code/Tools/Standalone/CMakeLists.txt b/Code/Tools/Standalone/CMakeLists.txt
index 479b8be11f..a8242022a8 100644
--- a/Code/Tools/Standalone/CMakeLists.txt
+++ b/Code/Tools/Standalone/CMakeLists.txt
@@ -36,7 +36,6 @@ ly_add_target(
             ${additional_dependencies}
     COMPILE_DEFINITIONS 
         PRIVATE
-            UNICODE
             STANDALONETOOLS_ENABLE_LUA_IDE
 )
 
@@ -68,6 +67,5 @@ ly_add_target(
             ${additional_dependencies}
     COMPILE_DEFINITIONS 
         PRIVATE
-            UNICODE
             STANDALONETOOLS_ENABLE_PROFILER
 )
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
index f72ba6e1ff..4c923c43c4 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
@@ -8,6 +8,8 @@
 
 #include 
 
+#include 
+
 #include 
 
 namespace AtomFontInternal
@@ -17,13 +19,11 @@ namespace AtomFontInternal
         TCHAR sysFontPath[MAX_PATH];
         if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPath)))
         {
-            const char* fontPath = m_strFontPath.c_str();
-            const char* fontName = AZ::IO::PathView(fontPath).Filename();
+            const AZ::IO::PathView fontName = AZ::IO::PathView(m_strFontPath.c_str()).Filename();
 
-            string newFontPath(sysFontPath);
-            newFontPath += "/";
-            newFontPath += fontName;
-            m_font->Load(newFontPath, m_FontTexSize.x, m_FontTexSize.y, m_slotSizes.x, m_slotSizes.y, CreateTTFFontFlag(m_FontSmoothMethod, m_FontSmoothAmount), m_SizeRatio);
+            AZ::IO::Path newFontPath(sysFontPath);
+            newFontPath /= fontName;
+            m_font->Load(newFontPath.c_str(), m_FontTexSize.x, m_FontTexSize.y, m_slotSizes.x, m_slotSizes.y, CreateTTFFontFlag(m_FontSmoothMethod, m_FontSmoothAmount), m_SizeRatio);
         }
     }
 }
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp
index 5aae754a7d..33950689f5 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp
@@ -11,7 +11,7 @@
 #include 
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontTexture::WriteToFile(const string& fileName)
+int AZ::FontTexture::WriteToFile(const AZStd::string& fileName)
 {
     AZ::IO::FileIOStream outputFile(fileName.c_str(), AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeBinary);
 
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp
index 35c2b26b48..ecf0789220 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp
@@ -46,7 +46,7 @@ static void DumfontTexture(IConsoleCmdArgs* cmdArgs)
 
     if (fontName && *fontName && *fontName != '0')
     {
-        string fontFilePath("@devroot@/");
+        AZStd::string fontFilePath("@devroot@/");
         fontFilePath += fontName;
         fontFilePath += ".bmp";
 
@@ -61,7 +61,7 @@ static void DumfontTexture(IConsoleCmdArgs* cmdArgs)
 
 static void DumfontNames([[maybe_unused]] IConsoleCmdArgs* cmdArgs)
 {
-    string names = gEnv->pCryFont->GetLoadedFontNames();
+    AZStd::string names = gEnv->pCryFont->GetLoadedFontNames();
     gEnv->pLog->LogWithType(IMiniLog::eInputResponse, "Currently loaded fonts: %s", names.c_str());
 }
 
@@ -97,15 +97,15 @@ namespace
                 && !m_boldItalicFontFilename.empty();
         }
 
-        string m_lang;                      //!< Stores a comma-separated list of languages this collection of fonts applies to.
+        AZStd::string m_lang;               //!< Stores a comma-separated list of languages this collection of fonts applies to.
                                             //!< If this is an empty string, it implies that these set of fonts will be applied
                                             //!< by default (when a language is being used but no fonts in the font family are
                                             //!< mapped to that language).
 
-        string m_fontFilename;              //!< Font used when no styling is applied.
-        string m_boldFontFilename;          //!< Bold-styled font
-        string m_italicFontFilename;        //!< Italic-styled font
-        string m_boldItalicFontFilename;    //!< Bold-italic-styled font
+        AZStd::string m_fontFilename;              //!< Font used when no styling is applied.
+        AZStd::string m_boldFontFilename;          //!< Bold-styled font
+        AZStd::string m_italicFontFilename;        //!< Italic-styled font
+        AZStd::string m_boldItalicFontFilename;    //!< Bold-italic-styled font
     };
 
     //! Stores parsed font family XML data.
@@ -152,7 +152,7 @@ namespace
             return !m_fontFamilyName.empty();
         }
 
-        string m_fontFamilyName;                  //!< Value of the "name" font-family tag attribute
+        AZStd::string m_fontFamilyName;                  //!< Value of the "name" font-family tag attribute
         AZStd::list m_fontTagsXml;    //!< List of child  tag data.
     };
 
@@ -179,7 +179,7 @@ namespace
                 return false;
             }
 
-            string name;
+            AZStd::string name;
 
             for (int i = 0, count = node->getNumAttributes(); i < count; ++i)
             {
@@ -187,7 +187,7 @@ namespace
                 const char* value = "";
                 if (node->getAttributeByIndex(i, &key, &value))
                 {
-                    if (string(key) == "name")
+                    if (AZStd::string(key) == "name")
                     {
                         name = value;
                     }
@@ -199,7 +199,7 @@ namespace
                 }
             }
 
-            name.Trim();
+            AZ::StringFunc::TrimWhiteSpace(name, true, true);
             if (!name.empty())
             {
                 xmlData.m_fontFamilyName = name;
@@ -216,14 +216,14 @@ namespace
         {
             xmlData.m_fontTagsXml.push_back(FontTagXml());
 
-            string lang;
+            AZStd::string lang;
             for (int i = 0, count = node->getNumAttributes(); i < count; ++i)
             {
                 const char* key = "";
                 const char* value = "";
                 if (node->getAttributeByIndex(i, &key, &value))
                 {
-                    if (string(key) == "lang")
+                    if (AZStd::string(key) == "lang")
                     {
                         lang = value;
                     }
@@ -235,7 +235,7 @@ namespace
                 }
             }
 
-            lang.Trim();
+            AZ::StringFunc::TrimWhiteSpace(lang, true, true);
             if (!lang.empty())
             {
                 xmlData.m_fontTagsXml.back().m_lang = lang;
@@ -253,8 +253,8 @@ namespace
                 return false;
             }
 
-            string path;
-            string tags;
+            AZStd::string path;
+            AZStd::string tags;
 
             for (int i = 0, count = node->getNumAttributes(); i < count; ++i)
             {
@@ -262,11 +262,11 @@ namespace
                 const char* value = "";
                 if (node->getAttributeByIndex(i, &key, &value))
                 {
-                    if (string(key) == "path")
+                    if (AZStd::string(key) == "path")
                     {
                         path = value;
                     }
-                    else if (string(key) == "tags")
+                    else if (AZStd::string(key) == "tags")
                     {
                         tags = value;
                     }
@@ -278,7 +278,7 @@ namespace
                 }
             }
 
-            tags.Trim();
+            AZ::StringFunc::TrimWhiteSpace(tags, true, true);
             if (tags.empty())
             {
                 xmlData.m_fontTagsXml.back().m_fontFilename = path;
@@ -315,7 +315,7 @@ namespace
     //! when referencing font family names from font family XML files), and
     //! attempting to load the XML files directly via ISystem() methods can
     //! produce a lot of warning noise.
-    XmlNodeRef SafeLoadXmlFromFile(const string& xmlPath)
+    XmlNodeRef SafeLoadXmlFromFile(const AZStd::string& xmlPath)
     {
         if (gEnv->pCryPak->IsFileExist(xmlPath.c_str()))
         {
@@ -383,8 +383,8 @@ void AZ::AtomFont::Release()
 
 IFFont* AZ::AtomFont::NewFont(const char* fontName)
 {
-    string name = fontName;
-    name.MakeLower();
+    AZStd::string name = fontName;
+    AZStd::to_lower(name.begin(), name.end());
     AzFramework::FontId fontId = GetFontId(name.c_str());
 
     FontMapItor it = m_fonts.find(fontId);
@@ -404,7 +404,9 @@ IFFont* AZ::AtomFont::NewFont(const char* fontName)
 
 IFFont* AZ::AtomFont::GetFont(const char* fontName) const
 {
-    AzFramework::FontId fontId = GetFontId(string(fontName).MakeLower().c_str());
+    AZStd::string name = fontName;
+    AZStd::to_lower(name.begin(), name.end());
+    AzFramework::FontId fontId = GetFontId(name.c_str());
     FontMapConstItor it = m_fonts.find(fontId);
     return it != m_fonts.end() ? it->second : 0;
 }
@@ -423,8 +425,8 @@ AzFramework::FontDrawInterface* AZ::AtomFont::GetDefaultFontDrawInterface() cons
 FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
 {
     FontFamilyPtr fontFamily(nullptr);
-    string fontFamilyPath;
-    string fontFamilyFullPath;
+    AZStd::string fontFamilyPath;
+    AZStd::string fontFamilyFullPath;
     
     XmlNodeRef root = LoadFontFamilyXml(fontFamilyName, fontFamilyPath, fontFamilyFullPath);
 
@@ -450,13 +452,13 @@ FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
                 }
                 else
                 {
-                    int searchPos = 0;
-                    string langToken;
-
                     // "lang" font-tag attribute could be comma-separated
-                    while (!(langToken = fontTagXml.m_lang.Tokenize(",", searchPos)).empty())
+                    AZStd::vector tokens;
+                    AZ::StringFunc::Tokenize(fontTagXml.m_lang, tokens, ',');
+                    for(AZStd::string& langToken : tokens)
                     {
-                        if (langToken.Trim() == currentLanguage)
+                        AZ::StringFunc::TrimWhiteSpace(langToken, true, true);
+                        if (langToken == currentLanguage)
                         {
                             langSpecificFont = &fontTagXml;
                             break;
@@ -494,7 +496,7 @@ FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
                     // Map the font family name both by path and by name defined
                     // within the Font Family XML itself. This allows font 
                     // families to also be referenced simply by name.
-                    if (!AddFontFamilyToMaps(fontFamilyFullPath, xmlData.m_fontFamilyName, fontFamily))
+                    if (!AddFontFamilyToMaps(fontFamilyFullPath.c_str(), xmlData.m_fontFamilyName.c_str(), fontFamily))
                     {
                         SAFE_RELEASE(normal);
                         SAFE_RELEASE(bold);
@@ -540,7 +542,7 @@ FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
             // Use filepath as familyName so font loading/unloading doesn't break with duplicate file names
             fontFamily->familyName = fontFamilyName;
 
-            if (!AddFontFamilyToMaps(fontFamilyName, fontFamily->familyName, fontFamily))
+            if (!AddFontFamilyToMaps(fontFamilyName, fontFamily->familyName.c_str(), fontFamily))
             {
                 SAFE_RELEASE(font);
 
@@ -581,7 +583,9 @@ FontFamilyPtr AZ::AtomFont::GetFontFamily(const char* fontFamilyName)
     // or just the filename of a font itself. Fonts are mapped by font family
     // name or by filepath, so attempt lookup using the map first since it's
     // the fastest.
-    string loweredName = string(fontFamilyName).Trim().MakeLower();
+    AZStd::string loweredName = AZStd::string(fontFamilyName);
+    AZ::StringFunc::TrimWhiteSpace(loweredName, true, true);
+    AZStd::to_lower(loweredName.begin(), loweredName.end());
     auto it = m_fontFamilies.find(PathUtil::MakeGamePath(loweredName).c_str());
     if (it != m_fontFamilies.end())
     {
@@ -596,9 +600,9 @@ FontFamilyPtr AZ::AtomFont::GetFontFamily(const char* fontFamilyName)
         for (const auto& fontFamilyIter : m_fontFamilies)
         {
             const AZStd::string& mappedFontFamilyName = fontFamilyIter.first;
-            string mappedFilenameNoExtension = PathUtil::GetFileName(mappedFontFamilyName.c_str());
+            AZStd::string mappedFilenameNoExtension = PathUtil::GetFileName(mappedFontFamilyName.c_str());
 
-            string searchStringFilenameNoExtension = PathUtil::GetFileName(loweredName);
+            AZStd::string searchStringFilenameNoExtension = PathUtil::GetFileName(loweredName);
 
             if (mappedFilenameNoExtension == searchStringFilenameNoExtension)
             {
@@ -619,9 +623,9 @@ void AZ::AtomFont::AddCharsToFontTextures(FontFamilyPtr fontFamily, const char*
     fontFamily->boldItalic->AddCharsToFontTexture(chars, glyphSizeX, glyphSizeY);
 }
 
-string AZ::AtomFont::GetLoadedFontNames() const
+AZStd::string AZ::AtomFont::GetLoadedFontNames() const
 {
-    string ret;
+    AZStd::string ret;
     for (FontMapConstItor it = m_fonts.begin(), itEnd = m_fonts.end(); it != itEnd; ++it)
     {
         FFont* font = it->second;
@@ -678,7 +682,9 @@ void AZ::AtomFont::ReloadAllFonts()
 
 void AZ::AtomFont::UnregisterFont(const char* fontName)
 {
-    AzFramework::FontId fontId = GetFontId(string(fontName).MakeLower().c_str());
+    AZStd::string name(fontName);
+    AZStd::to_lower(name.begin(), name.end());
+    AzFramework::FontId fontId = GetFontId(name.c_str());
     FontMapItor it = m_fonts.find(fontId);
 
 #if defined(AZ_ENABLE_TRACING)
@@ -715,10 +721,10 @@ void AZ::AtomFont::UnregisterFont(const char* fontName)
 
 IFFont* AZ::AtomFont::LoadFont(const char* fontName)
 {
-    string fontNameLower = fontName;
-    fontNameLower.MakeLower();
+    AZStd::string fontNameLower = fontName;
+    AZStd::to_lower(fontNameLower.begin(), fontNameLower.end());
 
-    IFFont* font = GetFont(fontNameLower);
+    IFFont* font = GetFont(fontNameLower.c_str());
     if (font)
     {
         font->AddRef(); // use existing loaded font
@@ -726,10 +732,10 @@ IFFont* AZ::AtomFont::LoadFont(const char* fontName)
     else
     {
         // attempt to create and load a new font, use the font pathname as the font name
-        font = NewFont(fontNameLower);
+        font = NewFont(fontNameLower.c_str());
         if (!font)
         {
-            string errorMsg = "Error creating a new font named ";
+            AZStd::string errorMsg = "Error creating a new font named ";
             errorMsg += fontNameLower;
             errorMsg += ".";
             CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg.c_str());
@@ -737,12 +743,12 @@ IFFont* AZ::AtomFont::LoadFont(const char* fontName)
         else
         {
             // creating font adds one to its refcount so no need for AddRef here
-            if (!font->Load(fontNameLower))
+            if (!font->Load(fontNameLower.c_str()))
             {
-                string errorMsg = "Error loading a font from ";
+                AZStd::string errorMsg = "Error loading a font from ";
                 errorMsg += fontNameLower;
                 errorMsg += ".";
-                CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg);
+                CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg.c_str());
                 font->Release();
                 font = nullptr;
             }
@@ -764,8 +770,9 @@ void AZ::AtomFont::ReleaseFontFamily(FontFamily* fontFamily)
     // Note that the FontFamily is mapped both by filename and by "family name"
     auto it = m_fontFamilyReverseLookup[fontFamily];
     m_fontFamilies.erase(it);
-    string familyName(fontFamily->familyName);
-    m_fontFamilies.erase(familyName.MakeLower().c_str());
+    AZStd::string familyName(fontFamily->familyName);
+    AZStd::to_lower(familyName.begin(), familyName.end());
+    m_fontFamilies.erase(familyName.c_str());
 
     // Reverse lookup is used to avoid needing to store filename path with
     // the font family, so we need to remove that entry also.
@@ -785,12 +792,11 @@ bool AZ::AtomFont::AddFontFamilyToMaps(const char* fontFamilyFilename, const cha
     }
 
     // We don't support "updating" mapped values. 
-    AZStd::string loweredFilename(PathUtil::MakeGamePath(string(fontFamilyFilename)).c_str());
+    AZStd::string loweredFilename(PathUtil::MakeGamePath(AZStd::string(fontFamilyFilename)).c_str());
     AZStd::to_lower(loweredFilename.begin(), loweredFilename.end());
     if (m_fontFamilies.find(loweredFilename) != m_fontFamilies.end())
     {
-        string warnMsg;
-        warnMsg.Format("Couldn't load Font Family '%s': already loaded", fontFamilyFilename);
+        AZStd::string warnMsg = AZStd::string::format("Couldn't load Font Family '%s': already loaded", fontFamilyFilename);
         CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, warnMsg.c_str());
         return false;
     }
@@ -801,8 +807,7 @@ bool AZ::AtomFont::AddFontFamilyToMaps(const char* fontFamilyFilename, const cha
     AZStd::to_lower(loweredFontFamilyName.begin(), loweredFontFamilyName.end());
     if (m_fontFamilies.find(loweredFontFamilyName) != m_fontFamilies.end())
     {
-        string warnMsg;
-        warnMsg.Format("Couldn't load Font Family '%s': already loaded", fontFamilyName);
+        AZStd::string warnMsg = AZStd::string::format("Couldn't load Font Family '%s': already loaded", fontFamilyName);
         CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, warnMsg.c_str());
         return false;
     }
@@ -819,7 +824,7 @@ bool AZ::AtomFont::AddFontFamilyToMaps(const char* fontFamilyFilename, const cha
     return true;
 }
 
-XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, string& outputDirectory, string& outputFullPath)
+XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, AZStd::string& outputDirectory, AZStd::string& outputFullPath)
 {
     outputFullPath = fontFamilyName;
     outputDirectory = PathUtil::GetPath(fontFamilyName);
@@ -829,8 +834,8 @@ XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, string& o
     // not a path, so we try to build a "best guess" path from the name.
     if (!root)
     {
-        string fileNoExtension(PathUtil::GetFileName(fontFamilyName));
-        string fileExtension(PathUtil::GetExt(fontFamilyName));
+        AZStd::string fileNoExtension(PathUtil::GetFileName(fontFamilyName));
+        AZStd::string fileExtension(PathUtil::GetExt(fontFamilyName));
 
         if (fileExtension.empty())
         {
@@ -838,14 +843,14 @@ XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, string& o
         }
 
         // Try: "fonts/fontName.fontfamily"
-        outputDirectory = string("fonts/");
+        outputDirectory = AZStd::string("fonts/");
         outputFullPath = outputDirectory + fileNoExtension + fileExtension;
         root = SafeLoadXmlFromFile(outputFullPath);
 
         // Finally, try: "fonts/fontName/fontName.fontfamily"
         if (!root)
         {
-            outputDirectory = string("fonts/") + fileNoExtension + "/";
+            outputDirectory = AZStd::string("fonts/") + fileNoExtension + "/";
             outputFullPath = outputDirectory + fileNoExtension + fileExtension;
             root = SafeLoadXmlFromFile(outputFullPath);
         }
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
index c07717945a..ddb2fa6292 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
@@ -126,7 +126,7 @@ bool AZ::FFont::Load(const char* fontFilePath, unsigned int width, unsigned int
 
     auto pPak = gEnv->pCryPak;
 
-    string fullFile;
+    AZStd::string fullFile;
     if (pPak->IsAbsPath(fontFilePath))
     {
         fullFile = fontFilePath;
@@ -1166,7 +1166,7 @@ size_t AZ::FFont::GetTextLength(const char* str, const bool asciiMultiLine) cons
     return len;
 }
 
-void AZ::FFont::WrapText(string& result, float maxWidth, const char* str, const TextDrawContext& ctx)
+void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str, const TextDrawContext& ctx)
 {
     result = str;
 
diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
index 98cbd22f71..ac55cd38e9 100644
--- a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
+++ b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
@@ -47,8 +47,7 @@ bool PropertyHandlerChar::ReadValuesIntoGUI(size_t index, AzToolsFramework::Prop
         // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
         // work for cases tested but may not in general.
         wchar_t wcharString[2] = { static_cast(instance), 0 };
-        AZStd::string val;
-        AZStd::to_string(val, AZStd::wstring(wcharString));
+        AZStd::string val(CryStringUtils::WStrToUTF8(wcharString));
         GUI->setValue(val);
     }
     GUI->blockSignals(false);
diff --git a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
index cbd0b2d6cb..7bcdc26712 100644
--- a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
+++ b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
@@ -9,7 +9,6 @@
 
 #include "UiClipboard.h"
 #include 
-#include 
 
 bool UiClipboard::SetText(const AZStd::string& text)
 {
@@ -20,8 +19,7 @@ bool UiClipboard::SetText(const AZStd::string& text)
         {
             if (text.length() > 0)
             {
-                AZStd::wstring wstr;
-                AZStd::to_wstring(wstr, text);
+                auto wstr = CryStringUtils::UTF8ToWStr(text.c_str());
                 const SIZE_T buffSize = (wstr.size() + 1) * sizeof(WCHAR);
                 if (HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, buffSize))
                 {
@@ -47,7 +45,7 @@ AZStd::string UiClipboard::GetText()
         if (HANDLE hText = GetClipboardData(CF_UNICODETEXT))
         {
             const WCHAR* text = static_cast(GlobalLock(hText));
-            AZStd::to_string(outText, AZStd::wstring(text));
+            outText = CryStringUtils::WStrToUTF8(text);
             GlobalUnlock(hText);
         }
         CloseClipboard();
diff --git a/Gems/LyShine/Code/Source/StringUtfUtils.h b/Gems/LyShine/Code/Source/StringUtfUtils.h
index e10e691a6f..74a27afe9f 100644
--- a/Gems/LyShine/Code/Source/StringUtfUtils.h
+++ b/Gems/LyShine/Code/Source/StringUtfUtils.h
@@ -36,8 +36,7 @@ namespace LyShine
         // In the long run it would be better to eliminate
         // this function and use Unicode::CIterator<>::Position instead.
         wchar_t wcharString[2] = { static_cast(multiByteChar), 0 };
-        AZStd::string utf8String;
-        AZStd::to_string(utf8String, AZStd::wstring(wcharString));
+        AZStd::string utf8String(CryStringUtils::WStrToUTF8(wcharString));
         int utf8Length = utf8String.length();
         return utf8Length;
     }
diff --git a/Gems/LyShine/Code/Source/UiButtonComponent.cpp b/Gems/LyShine/Code/Source/UiButtonComponent.cpp
index c6ba64848e..11bb088400 100644
--- a/Gems/LyShine/Code/Source/UiButtonComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiButtonComponent.cpp
@@ -222,7 +222,7 @@ bool UiButtonComponent::VersionConverter(AZ::SerializeContext& context,
     // - Need to convert Color to Color and Alpha
     // conversion from version 2 to 3:
     // - Need to convert CryString ActionName elements to AZStd::string
-    AZ_Assert(classElement.GetVersion() < 3, "Unsupported UiButtonComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() >= 3, "Unsupported UiButtonComponent version: %d", classElement.GetVersion());
 
     // conversion from version 3 to 4:
     // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference
diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp
index 8f4145c07b..06996fbb48 100644
--- a/Gems/LyShine/Code/Source/UiImageComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp
@@ -2663,7 +2663,7 @@ bool UiImageComponent::VersionConverter(AZ::SerializeContext& context,
     // conversion from version 1:
     // - Need to convert CryString elements to AZStd::string
     // - Need to convert Color to Color and Alpha
-    AZ_Assert(classElement.GetVersion() <= 1, "Unsupported UiImageComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() > 1, "Unsupported UiImageComponent version: %d", classElement.GetVersion());
 
     // conversion from version 1 or 2 to current:
     // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference
diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp
index 76a789c5cf..fadf09571f 100644
--- a/Gems/LyShine/Code/Source/UiTextComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp
@@ -4996,7 +4996,7 @@ bool UiTextComponent::VersionConverter(AZ::SerializeContext& context,
 {
     // conversion from version 1: Need to convert Color to Color and Alpha
     // conversion from version 1 or 2: Need to convert Text from CryString to AzString
-    AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() > 2, "Unsupported UiTextComponent version: %d", classElement.GetVersion());
 
     // Versions prior to v4: Change default font
     if (classElement.GetVersion() <= 3)
diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
index c746d14095..c149c5a4d4 100644
--- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
@@ -1185,8 +1185,7 @@ void UiTextInputComponent::UpdateDisplayedTextFunction()
                 // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
                 // work for cases tested but may not in general.
                 wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 };
-                AZStd::string replacementCharString;
-                AZStd::to_string(replacementCharString, AZStd::wstring(wcharString));
+                AZStd::string replacementCharString(CryStringUtils::WStrToUTF8(wcharString));
 
                 int numReplacementChars = LyShine::GetUtf8StringLength(originalText);
 
@@ -1478,7 +1477,7 @@ bool UiTextInputComponent::VersionConverter(AZ::SerializeContext& context,
     // - Need to convert Color to Color and Alpha
     // conversion from version 1 or 2 to current:
     // - Need to convert CryString ActionName elements to AZStd::string
-    AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextInputComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() > 2, "Unsupported UiTextInputComponent version: %d", classElement.GetVersion());
     
     // conversion from version 1, 2 or 3 to current:
     // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference

From 902bdeb6d6092d0b88066fbb873eaa043c3b788a Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 29 Jul 2021 16:50:50 -0700
Subject: [PATCH 041/251] Create RUN target as helpers for the project-centric
 workflow (#2520) (#2635)

* Create RUN target as helpers for the project-centric workflow

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>

* typo fix

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>

* rename target as ".Imported" and create "" as the metatarget that is used for debugging and building in o3de

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/CMakeLists.txt                 |  2 +
 cmake/Platform/Common/Install_common.cmake | 43 ++++++++++++++++++----
 cmake/SettingsRegistry.cmake               |  7 +---
 cmake/install/InstalledTarget.in           |  2 +
 4 files changed, 42 insertions(+), 12 deletions(-)

diff --git a/Code/Editor/CMakeLists.txt b/Code/Editor/CMakeLists.txt
index 5a846a267a..db6b8e958e 100644
--- a/Code/Editor/CMakeLists.txt
+++ b/Code/Editor/CMakeLists.txt
@@ -163,6 +163,8 @@ ly_add_target(
         editor_files.cmake
     PLATFORM_INCLUDE_FILES
         Platform/${PAL_PLATFORM_NAME}/editor_${PAL_PLATFORM_NAME_LOWERCASE}.cmake
+    TARGET_PROPERTIES
+        LY_INSTALL_GENERATE_RUN_TARGET TRUE
     BUILD_DEPENDENCIES
         PRIVATE
             3rdParty::Qt::Core
diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake
index 1ac59ee83f..8058fb5908 100644
--- a/cmake/Platform/Common/Install_common.cmake
+++ b/cmake/Platform/Common/Install_common.cmake
@@ -9,6 +9,15 @@ include(cmake/FileUtil.cmake)
 
 set(CMAKE_INSTALL_MESSAGE NEVER) # Simplify messages to reduce output noise
 
+define_property(TARGET PROPERTY LY_INSTALL_GENERATE_RUN_TARGET
+    BRIEF_DOCS "Defines if a \"RUN\" targets should be created when installing this target Gem"
+    FULL_DOCS [[
+        Property which is set on targets that should generate a "RUN"
+        target when installed. This \"RUN\" target helps to run the 
+        binary from the installed location directly from the IDE.
+    ]]
+)
+
 ly_set(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME Core)
 
 cmake_path(RELATIVE_PATH CMAKE_RUNTIME_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE runtime_output_directory)
@@ -105,15 +114,19 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
         set(NAMESPACE_PLACEHOLDER "")
         set(NAME_PLACEHOLDER ${TARGET_NAME})
     endif()
+    get_target_property(should_create_helper ${TARGET_NAME} LY_INSTALL_GENERATE_RUN_TARGET)
+    if(should_create_helper)
+        set(NAME_PLACEHOLDER ${NAME_PLACEHOLDER}.Imported)
+    endif()
 
     set(TARGET_TYPE_PLACEHOLDER "")
-    get_target_property(target_type ${NAME_PLACEHOLDER} TYPE)
+    get_target_property(target_type ${TARGET_NAME} TYPE)
     # Remove the _LIBRARY since we dont need to pass that to ly_add_targets
     string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type})
     # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead
     string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER})
     if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE")
-        get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE)
+        get_target_property(gem_module ${TARGET_NAME} GEM_MODULE)
         if(gem_module)
             set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE")
         endif()
@@ -146,7 +159,6 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
         unset(RUNTIME_DEPENDENCIES_PLACEHOLDER)
     endif()
 
-
     get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES)
     unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER)
     if(inteface_build_dependencies_props)
@@ -170,6 +182,23 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
     list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER)
     string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}")
 
+    # If the target is an executable/application, add a custom target so we can debug the target in project-centric workflow
+    if(should_create_helper)
+        string(REPLACE ".Imported" "" RUN_TARGET_NAME ${NAME_PLACEHOLDER})
+        set(target_types_with_debugging_helper EXECUTABLE APPLICATION)
+        if(NOT target_type IN_LIST target_types_with_debugging_helper)
+            message(FATAL_ERROR "Cannot generate a RUN target for ${TARGET_NAME}, type is ${target_type}")
+        endif()
+        set(TARGET_RUN_HELPER
+"add_custom_target(${RUN_TARGET_NAME})
+set_target_properties(${RUN_TARGET_NAME} PROPERTIES 
+    FOLDER \"CMakePredefinedTargets/SDK\"
+    VS_DEBUGGER_COMMAND \$>
+    VS_DEBUGGER_COMMAND_ARGUMENTS \"--project-path=\${LY_DEFAULT_PROJECT_PATH}\"
+)"
+)
+    endif()
+
     # Config file
     set(target_file_contents "# Generated by O3DE install\n\n")
     if(NOT target_type STREQUAL INTERFACE_LIBRARY)
@@ -182,13 +211,13 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
             set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$")
         elseif(target_type STREQUAL SHARED_LIBRARY)
             string(APPEND target_file_contents 
-"set_property(TARGET ${TARGET_NAME} 
+"set_property(TARGET ${NAME_PLACEHOLDER} 
     APPEND_STRING PROPERTY IMPORTED_IMPLIB
         $<$$:\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"$
 )
 ")
             string(APPEND target_file_contents 
-"set_property(TARGET ${TARGET_NAME} 
+"set_property(TARGET ${NAME_PLACEHOLDER} 
     PROPERTY IMPORTED_IMPLIB_$> 
         \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"
 )
@@ -200,11 +229,11 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
 
         if(target_location)
             string(APPEND target_file_contents
-"set_property(TARGET ${TARGET_NAME}
+"set_property(TARGET ${NAME_PLACEHOLDER}
     APPEND_STRING PROPERTY IMPORTED_LOCATION
         $<$$:${target_location}$
 )
-set_property(TARGET ${TARGET_NAME}
+set_property(TARGET ${NAME_PLACEHOLDER}
     PROPERTY IMPORTED_LOCATION_$>
         ${target_location}
 )
diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake
index 934bae4e30..a1e6de73f8 100644
--- a/cmake/SettingsRegistry.cmake
+++ b/cmake/SettingsRegistry.cmake
@@ -158,10 +158,6 @@ function(ly_delayed_generate_settings_registry)
                 message(FATAL_ERROR "Dependency ${gem_target} from ${target} does not exist")
             endif()
 
-            get_property(has_manually_added_dependencies TARGET ${gem_target} PROPERTY MANUALLY_ADDED_DEPENDENCIES SET)
-            get_target_property(target_type ${gem_target} TYPE)
-
-
             ly_get_gem_module_root(gem_module_root ${gem_target})
             file(RELATIVE_PATH gem_module_root_relative_to_engine_root ${LY_ROOT_FOLDER} ${gem_module_root})
 
@@ -179,7 +175,8 @@ function(ly_delayed_generate_settings_registry)
         list(JOIN target_gem_dependencies_names ",\n" target_gem_dependencies_names)
         string(CONFIGURE ${gems_json_template} gem_json @ONLY)
         get_target_property(is_imported ${target} IMPORTED)
-        if(is_imported)
+        get_target_property(target_type ${target} TYPE)
+        if(is_imported OR target_type STREQUAL UTILITY)
             unset(target_dir)
             foreach(conf IN LISTS CMAKE_CONFIGURATION_TYPES)
                 string(TOUPPER ${conf} UCONF)
diff --git a/cmake/install/InstalledTarget.in b/cmake/install/InstalledTarget.in
index 0503fd5f2b..a4f4fa4763 100644
--- a/cmake/install/InstalledTarget.in
+++ b/cmake/install/InstalledTarget.in
@@ -17,6 +17,8 @@ ly_add_target(
 @RUNTIME_DEPENDENCIES_PLACEHOLDER@
 )
 
+@TARGET_RUN_HELPER@
+
 set(configs @CMAKE_CONFIGURATION_TYPES@)
 foreach(config ${configs})
     include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL)

From 015424eb35cdb7b25abd07cdb4ee8ef77b47306e Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 11:51:21 -0700
Subject: [PATCH 042/251] Conversion to unicode, everything except
 StreamerConfiguration

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Framework/AzCore/AzCore/Debug/Trace.cpp  |  1 -
 Code/Framework/AzCore/AzCore/Debug/Trace.h    |  5 ++
 .../AzCore/AzCore/std/string/conversions.h    | 82 +++++++++++++++++++
 .../Common/Apple/AzCore/Debug/Trace_Apple.cpp |  1 +
 .../WinAPI/AzCore/Debug/Trace_WinAPI.cpp      | 19 +++--
 .../Linux/AzCore/Debug/Trace_Linux.cpp        |  4 +-
 .../Mac/AzCore/IPC/SharedMemory_Mac.cpp       |  2 +-
 .../Mac/AzCore/IPC/SharedMemory_Mac.h         |  1 -
 .../StreamerConfiguration_Windows.cpp         |  4 +-
 .../AzCore/IPC/SharedMemory_Windows.cpp       | 32 ++++----
 .../Windows/AzCore/IPC/SharedMemory_Windows.h |  3 -
 11 files changed, 121 insertions(+), 33 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/Debug/Trace.cpp b/Code/Framework/AzCore/AzCore/Debug/Trace.cpp
index 6d491c97b8..bd3b12a3b8 100644
--- a/Code/Framework/AzCore/AzCore/Debug/Trace.cpp
+++ b/Code/Framework/AzCore/AzCore/Debug/Trace.cpp
@@ -38,7 +38,6 @@ namespace AZ
             void DebugBreak();
 #endif
             void Terminate(int exitCode);
-            void OutputToDebugger(const char* window, const char* message);
         }
     }
 
diff --git a/Code/Framework/AzCore/AzCore/Debug/Trace.h b/Code/Framework/AzCore/AzCore/Debug/Trace.h
index a680cbdfed..bae074281c 100644
--- a/Code/Framework/AzCore/AzCore/Debug/Trace.h
+++ b/Code/Framework/AzCore/AzCore/Debug/Trace.h
@@ -15,6 +15,11 @@ namespace AZ
 {
     namespace Debug
     {
+        namespace Platform
+        {
+            void OutputToDebugger(const char* window, const char* message);
+        }
+    
         /// Global instance to the tracer.
         extern class Trace      g_tracer;
 
diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 3e5a393cf8..4dc5bbd547 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -49,6 +49,25 @@ namespace AZStd
                 }
             }
 
+            template
+            static inline void to_string(AZStd::basic_fixed_string& dest, const wchar_t* first, const wchar_t* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest));
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest));
+                }
+                else
+                {
+                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
+                    using StringType = AZStd::basic_string;
+                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
+                }
+            }
+
             template
             static inline void to_wstring(AZStd::basic_string& dest, const char* first, const char* last)
             {
@@ -67,6 +86,25 @@ namespace AZStd
                     static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
                 }
             }
+
+            template
+            static inline void to_wstring(AZStd::basic_fixed_string& dest, const char* first, const char* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest));
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest));
+                }
+                else
+                {
+                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
+                    using StringType = AZStd::basic_string;
+                    static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
+                }
+            }
         };
     }
     // 21.5: numeric conversions
@@ -266,6 +304,28 @@ namespace AZStd
         return to_string(dest, src.c_str(), src.length());
     }
 
+    template
+    void to_string(AZStd::basic_fixed_string& dest, const wchar_t* str, size_t srcLen = 0)
+    {
+        dest.clear();
+
+        if (srcLen == 0)
+        {
+            srcLen = wcslen(str);
+        }
+
+        if (srcLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_string(dest, str, str + srcLen);
+        }
+    }
+
+    template
+    void to_string(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src)
+    {
+        return to_string(dest, src.c_str(), src.length());
+    }
+
     template
     int stoi(const AZStd::basic_string& str, AZStd::size_t* idx = 0, int base = 10)
     {
@@ -384,6 +444,28 @@ namespace AZStd
         return to_wstring(dest, src.c_str(), src.length());
     }
 
+    template
+    void to_wstring(AZStd::basic_fixed_string& dest, const char* str, size_t strLen = 0)
+    {
+        dest.clear();
+
+        if (strLen == 0)
+        {
+            strLen = strlen(str);
+        }
+
+        if (strLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_wstring(dest, str, str + strLen);
+        }
+    }
+
+    template
+    void to_wstring(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src)
+    {
+        return to_wstring(dest, src.c_str(), src.length());
+    }
+
     // Convert a range of chars to lower case
 #if defined(AZSTD_USE_OLD_RW_STL)
     template
diff --git a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp
index 62fe849c36..4ae25bfaf9 100644
--- a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp
+++ b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp
@@ -72,6 +72,7 @@ namespace AZ
 
             void OutputToDebugger(const char*, const char*)
             {
+                // std::cout << title << ": " << message;
             }
         }
     }
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp
index 143bd8f9d0..99ea10e4bc 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp
@@ -12,6 +12,8 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 
 #include 
 
@@ -22,7 +24,7 @@ namespace AZ
     LPTOP_LEVEL_EXCEPTION_FILTER g_previousExceptionHandler = nullptr;
 #endif
 
-    const int g_maxMessageLength = 4096;
+    constexpr int g_maxMessageLength = 4096;
 
     namespace Debug
     {
@@ -58,15 +60,18 @@ namespace AZ
                 TerminateProcess(GetCurrentProcess(), exitCode);
             }
 
-            void OutputToDebugger(const char* window, const char* message)
+            void OutputToDebugger([[maybe_unused]] const char* window, const char* message)
             {
-                AZ_UNUSED(window);
-                wchar_t messageW[g_maxMessageLength];
-                size_t numCharsConverted;
-                if (mbstowcs_s(&numCharsConverted, messageW, message, g_maxMessageLength - 1) == 0)
+                AZStd::fixed_wstring tmpW;
+                if(window)
                 {
-                    OutputDebugStringW(messageW);
+                    AZStd::to_wstring(tmpW, window);
+                    tmpW += L": ";
+                    OutputDebugStringW(tmpW.c_str());
+                    tmpW.clear();
                 }
+                AZStd::to_wstring(tmpW, message);
+                OutputDebugStringW(tmpW.c_str());
             }
         }
     }
diff --git a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
index 3f9e475153..86c7e14ae6 100644
--- a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
+++ b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
@@ -7,6 +7,7 @@
  */
 
 #include 
+#include 
 
 namespace AZ
 {
@@ -14,8 +15,9 @@ namespace AZ
     {
         namespace Platform
         {
-            void OutputToDebugger(const char*, const char*)
+            void OutputToDebugger(const char* title, const char* message)
             {
+                // std::cout << title << ": " << message;
             }
         }
     }
diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
index 7f13ec442a..5555704040 100644
--- a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
+++ b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
@@ -29,7 +29,7 @@ namespace AZ
         return errno;
     }
 
-    void SharedMemory_Mac::ComposeMutexName(char* dest, size_t length, const char* name)
+    void ComposeMutexName(char* dest, size_t length, const char* name)
     {
         azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
 
diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h
index 8e172d920f..c0d5d7c2e9 100644
--- a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h
+++ b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h
@@ -29,7 +29,6 @@ namespace AZ
 
         static int GetLastError();
 
-        void ComposeMutexName(char* dest, size_t length, const char* name);
         CreateResult Create(const char* name, unsigned int size, bool openIfCreated);
         bool Open(const char* name);
         void Close();
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp
index 35835c374c..0813d2d057 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp
@@ -290,7 +290,7 @@ namespace AZ::IO
     static bool CollectHardwareInfo(HardwareInformation& hardwareInfo, bool addAllDrives, bool reportHardware)
     {
         char drives[512];
-        if (::GetLogicalDriveStrings(sizeof(drives) - 1, drives))
+        if (::GetLogicalDriveStringsA(sizeof(drives) - 1, drives))
         {
             AZStd::unordered_map driveMappings;
             char* driveIt = drives;
@@ -318,7 +318,7 @@ namespace AZ::IO
                     deviceName += driveIt;
                     deviceName.erase(deviceName.length() - 1); // Erase the slash.
 
-                    HANDLE deviceHandle = ::CreateFile(
+                    HANDLE deviceHandle = ::CreateFileA(
                         deviceName.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
                     if (deviceHandle != INVALID_HANDLE_VALUE)
                     {
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
index 21b2a76ba0..20c126f7a8 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
@@ -11,6 +11,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AZ
 {
@@ -21,16 +22,17 @@ namespace AZ
     {
     }
 
-    void SharedMemory_Windows::ComposeMutexName(char* dest, size_t length, const char* name)
+    void ComposeName(AZStd::fixed_wstring<256>& dest, const char* name, const wchar_t* suffix)
     {
-        azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
-        azsnprintf(dest, length, "%s_Mutex", name);
+        AZStd::to_wstring(dest, name);
+        dest += L"_";
+        dest += suffix;
     }
 
     SharedMemory_Common::CreateResult SharedMemory_Windows::Create(const char* name, unsigned int size, bool openIfCreated)
     {
-        char fullName[256];
-        ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name);
+        AZStd::fixed_wstring<256> fullName;
+        ComposeName(fullName, name, L"Mutex");
 
         // Security attributes
         SECURITY_ATTRIBUTES secAttr;
@@ -42,9 +44,7 @@ namespace AZ
         SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
 
         // Obtain global mutex
-        AZStd::wstring fullNameW;
-        AZStd::to_wstring(fullNameW, fullName);
-        m_globalMutex = CreateMutexW(&secAttr, FALSE, fullNameW.c_str());
+        m_globalMutex = CreateMutexW(&secAttr, FALSE, fullName.c_str());
         DWORD error = GetLastError();
         if (m_globalMutex == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false))
         {
@@ -53,8 +53,8 @@ namespace AZ
         }
 
         // Create the file mapping.
-        azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name);
-        m_mapHandle = CreateFileMappingW(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullNameW.c_str());
+        ComposeName(fullName, name, L"Data");
+        m_mapHandle = CreateFileMappingW(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullName.c_str());
         error = GetLastError();
         if (m_mapHandle == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false))
         {
@@ -67,12 +67,10 @@ namespace AZ
 
     bool SharedMemory_Windows::Open(const char* name)
     {
-        char fullName[256];
-        ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name);
-        AZStd::wstring fullNameW;
-        AZStd::to_wstring(fullNameW, fullName);
+        AZStd::fixed_wstring<256> fullName;
+        ComposeName(fullName, name, L"Mutex");
 
-        m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullNameW.c_str());
+        m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullName.c_str());
         AZ_Warning("AZSystem", m_globalMutex != NULL, "Failed to open OS mutex [%s]\n", m_name);
         if (m_globalMutex == NULL)
         {
@@ -80,8 +78,8 @@ namespace AZ
             return false;
         }
 
-        azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name);
-        m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullNameW.c_str());
+        ComposeName(fullName, name, L"Data");
+        m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullName.c_str());
         if (m_mapHandle == NULL)
         {
             AZ_TracePrintf("AZSystem", "OpenFileMapping %s failed with error %d\n", m_name, GetLastError());
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h
index 7f206f5413..7b10b9163e 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h
@@ -41,9 +41,6 @@ namespace AZ
         HANDLE m_mapHandle;
         HANDLE m_globalMutex;
         int m_lastLockResult;
-
-    private:
-        void ComposeMutexName(char* dest, size_t length, const char* name);
     };
 
     using SharedMemory_Platform = SharedMemory_Windows;

From 0ea11294abfcd69123143e7c48eef1fd23ba1ebe Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 12:29:06 -0700
Subject: [PATCH 043/251] fixes for crcfix

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Framework/Crcfix/crcfix.cpp | 87 +++++++++++++++++---------------
 1 file changed, 45 insertions(+), 42 deletions(-)

diff --git a/Code/Framework/Crcfix/crcfix.cpp b/Code/Framework/Crcfix/crcfix.cpp
index ce599e9a63..778b9e2185 100644
--- a/Code/Framework/Crcfix/crcfix.cpp
+++ b/Code/Framework/Crcfix/crcfix.cpp
@@ -12,6 +12,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -23,11 +24,11 @@ int g_longestFixTimeMs = 0;
 
 class Filename
 {
-    char    fullpath[MAX_PATH];
-    char    drive[_MAX_DRIVE];
-    char    dir[_MAX_DIR];
-    char    fname[_MAX_FNAME];
-    char    ext[_MAX_EXT];
+    wchar_t    fullpath[MAX_PATH];
+    wchar_t    drive[_MAX_DRIVE];
+    wchar_t    dir[_MAX_DIR];
+    wchar_t    fname[_MAX_FNAME];
+    wchar_t    ext[_MAX_EXT];
 
 public:
     Filename()
@@ -35,21 +36,21 @@ public:
         fullpath[0] = drive[0] = dir[0] = fname[0] = ext[0] = 0;
     }
 
-    Filename(const AZStd::string& filename)
+    Filename(const AZStd::wstring& filename)
     {
-        _splitpath(filename.c_str(), drive, dir, fname, ext);
-        strcpy(fullpath, filename.c_str());
+        _wsplitpath(filename.c_str(), drive, dir, fname, ext);
+        wcscpy(fullpath, filename.c_str());
     }
 
-    void        SetExt(const char* pExt)        { strcpy(ext, pExt); _makepath(fullpath, drive, dir, fname, pExt); }
-    const char* GetFullPath() const             { return fullpath; }
-    bool        Exists() const                  { return _access(fullpath, 0) == 0; }
-    bool        IsReadOnly() const              { return _access(fullpath, 6) == -1; }
-    bool        SetReadOnly() const             { return _chmod(fullpath, _S_IREAD) == 0; }
-    bool        SetWritable() const             { return _chmod(fullpath, _S_IREAD | _S_IWRITE) == 0; }
-    bool        Delete() const                  { return remove(fullpath) == 0; }
-    bool        Rename(const char* fn2) const   { return MoveFileEx(fullpath, fn2, MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING) == 0; }
-    bool        Copy(const char* dest) const    { return ::CopyFileA(fullpath, dest, FALSE) == TRUE; }
+    void        SetExt(const wchar_t* pExt)     { wcscpy(ext, pExt); _wmakepath(fullpath, drive, dir, fname, pExt); }
+    const wchar_t* GetFullPath() const          { return fullpath; }
+    bool        Exists() const                  { return _waccess(fullpath, 0) == 0; }
+    bool        IsReadOnly() const              { return _waccess(fullpath, 6) == -1; }
+    bool        SetReadOnly() const             { return _wchmod(fullpath, _S_IREAD) == 0; }
+    bool        SetWritable() const             { return _wchmod(fullpath, _S_IREAD | _S_IWRITE) == 0; }
+    bool        Delete() const                  { return _wremove(fullpath) == 0; }
+    bool        Rename(const wchar_t* fn2) const{ return MoveFileEx(fullpath, fn2, MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING) == 0; }
+    bool        Copy(const wchar_t* dest) const { return ::CopyFile(fullpath, dest, FALSE) == TRUE; }
 };
 
 class CRCfix
@@ -64,7 +65,7 @@ public:
     int     Fix(Filename srce);
 };
 
-void FixFiles(const AZStd::string& dir, const AZStd::string& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
+void FixFiles(const AZStd::wstring& dir, const AZStd::wstring& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
 {
     CRCfix fixer;
     WIN32_FIND_DATA wfd;
@@ -78,14 +79,14 @@ void FixFiles(const AZStd::string& dir, const AZStd::string& files, FILETIME* pL
             {
                 if (verbose)
                 {
-                    AZ_TracePrintf("CrcFix", "\tProcessing %s ...", wfd.cFileName);
+                    AZ_TracePrintf("CrcFix", "\tProcessing %ls ...", wfd.cFileName);
                 }
                 nFound++;
 
                 int n = 0;
                 if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0 && (!pLastRun || CompareFileTime(pLastRun, &wfd.ftLastWriteTime) <= 0))
                 {
-                    n = fixer.Fix(Filename(dir + "\\" + wfd.cFileName));
+                    n = fixer.Fix(Filename(dir + L"\\" + wfd.cFileName));
                     nProcessed++;
                 }
                 if (n < 0)
@@ -110,11 +111,11 @@ void FixFiles(const AZStd::string& dir, const AZStd::string& files, FILETIME* pL
     FindClose(hFind);
 }
 
-void FixDirectories(const AZStd::string& dirs, const AZStd::string& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
+void FixDirectories(const AZStd::wstring& dirs, const AZStd::wstring& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
 {
     if (verbose)
     {
-        AZ_TracePrintf("CrcFix", "Processing %s ...\n", dirs.c_str());
+        AZ_TracePrintf("CrcFix", "Processing %ls ...\n", dirs.c_str());
     }
 
     // do files
@@ -123,7 +124,7 @@ void FixDirectories(const AZStd::string& dirs, const AZStd::string& files, FILET
     // do folders
     WIN32_FIND_DATA wfd;
     HANDLE hFind;
-    hFind = FindFirstFile((dirs + "\\*").c_str(), &wfd);
+    hFind = FindFirstFile((dirs + L"\\*").c_str(), &wfd);
     if (hFind != INVALID_HANDLE_VALUE)
     {
         do
@@ -134,7 +135,7 @@ void FixDirectories(const AZStd::string& dirs, const AZStd::string& files, FILET
                 {
                     continue;
                 }
-                FixDirectories(AZStd::string(dirs + "\\" + wfd.cFileName), files, pLastRun, verbose, nFound, nProcessed, nFixed, nFailed);
+                FixDirectories(AZStd::wstring(dirs + L"\\" + wfd.cFileName), files, pLastRun, verbose, nFound, nProcessed, nFixed, nFailed);
             }
         } while (FindNextFile(hFind, &wfd));
     }
@@ -161,9 +162,9 @@ int main(int argc, char* argv[])
         char root[MAX_PATH];
         AZ::Utils::GetExecutableDirectory(root, MAX_PATH);
 
-        AZStd::vector entries;
+        AZStd::vector entries;
 
-        const char* logfilename = NULL;
+        AZStd::wstring logfilename;
         FILETIME    lastRun;
         FILETIME* pLastRun = NULL;
 
@@ -176,10 +177,12 @@ int main(int argc, char* argv[])
             {
                 continue;
             }
+            AZStd::wstring pArgW;
+            AZStd::to_wstring(pArgW, pArg);
             if (_strnicmp(pArg, "-log:", 5) == 0)
             {
-                logfilename = pArg + 5;
-                HANDLE hFile = CreateFile(logfilename, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
+                logfilename.assign(pArgW.begin() + 5, pArgW.end());
+                HANDLE hFile = CreateFile(logfilename.data(), 0, 0, NULL, OPEN_EXISTING, 0, NULL);
                 if (hFile != INVALID_HANDLE_VALUE)
                 {
                     pLastRun = &lastRun;
@@ -193,7 +196,7 @@ int main(int argc, char* argv[])
             }
             else
             {
-                entries.push_back(AZStd::string(pArg));
+                entries.emplace_back(AZStd::move(pArgW));
             }
         }
 
@@ -202,10 +205,10 @@ int main(int argc, char* argv[])
         int nProcessed = 0;
         int nFixed = 0;
         int nFailed = 0;
-        for (AZStd::vector::const_iterator iEntry = entries.begin(); iEntry != entries.end(); ++iEntry)
+        for (AZStd::vector::const_iterator iEntry = entries.begin(); iEntry != entries.end(); ++iEntry)
         {
-            AZStd::string entry = (iEntry->at(0) == '\\' || iEntry->find(":") != iEntry->npos) ? *iEntry : AZStd::string(root) + "\\" + *iEntry;
-            AZStd::string::size_type split = entry.find("*\\");
+            AZStd::wstring entry = (iEntry->at(0) == L'\\' || iEntry->find(L":") != iEntry->npos) ? *iEntry : AZStd::wstring(root) + L"\\" + *iEntry;
+            AZStd::wstring::size_type split = entry.find(L"*\\");
             bool doSubdirs = split != entry.npos;
             if (doSubdirs)
             {
@@ -213,7 +216,7 @@ int main(int argc, char* argv[])
             }
             else
             {
-                split = entry.rfind("\\");
+                split = entry.rfind(L"\\");
                 if (split == entry.npos)
                 {
                     split = 0;
@@ -223,9 +226,9 @@ int main(int argc, char* argv[])
         }
 
         // update timestamp
-        if (logfilename)
+        if (!logfilename.empty())
         {
-            HANDLE      hFile = CreateFile(logfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
+            HANDLE      hFile = CreateFile(logfilename.data(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
             GetSystemTimeAsFileTime(&lastRun);
             SetFileTime(hFile, NULL, NULL, &lastRun);
             char log[1024];
@@ -383,12 +386,12 @@ int CRCfix::Fix(Filename srce)
 
     bool        changed = false;
     Filename    dest(srce);
-    dest.SetExt("xxx");
+    dest.SetExt(L"xxx");
 
     linenum = 0;
 
-    FILE* infile = fopen(srce.GetFullPath(), "r");
-    FILE* outfile = fopen(dest.GetFullPath(), "w");
+    FILE* infile = _wfopen(srce.GetFullPath(), L"r");
+    FILE* outfile = _wfopen(dest.GetFullPath(), L"w");
 
     if (!infile || !outfile)
     {
@@ -475,7 +478,7 @@ int CRCfix::Fix(Filename srce)
     if (changed)
     {
         Filename    backup(srce);
-        backup.SetExt("crcfix_old");
+        backup.SetExt(L"crcfix_old");
 
         if (backup.Exists())
         {
@@ -486,7 +489,7 @@ int CRCfix::Fix(Filename srce)
 
         if (!srce.Copy(backup.GetFullPath()))
         {
-            AZ_TracePrintf("CrcFix", "Failed to copy %s to %s\n", srce, backup);
+            AZ_TracePrintf("CrcFix", "Failed to copy %ls to %ls\n", srce, backup);
 
             int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count());
             g_totalFixTimeMs += dt;
@@ -500,7 +503,7 @@ int CRCfix::Fix(Filename srce)
 
         if (!dest.Rename(srce.GetFullPath()))
         {
-            AZ_TracePrintf("CrcFix", "Failed to rename %s to %s\n", dest, srce);
+            AZ_TracePrintf("CrcFix", "Failed to rename %ls to %ls\n", dest, srce);
 
             int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count());
             g_totalFixTimeMs += dt;
@@ -514,7 +517,7 @@ int CRCfix::Fix(Filename srce)
 
         if (!backup.Delete())
         {
-            AZ_TracePrintf("CrcFix", "Failed to delete %s\n", backup);
+            AZ_TracePrintf("CrcFix", "Failed to delete %ls\n", backup);
         }
     }
     else

From 203532b91d508861738455636450812cb4299f14 Mon Sep 17 00:00:00 2001
From: chcurran <82187351+carlitosan@users.noreply.github.com>
Date: Fri, 30 Jul 2021 13:25:33 -0700
Subject: [PATCH 044/251] prove that SC tests are running

Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com>
---
 .../Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp           | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp
index c2fa59b037..df29a56fd5 100644
--- a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp
+++ b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp
@@ -84,6 +84,11 @@ public:
     }
 };
 
+TEST_F(ScriptCanvasTestFixture, ProveError)
+{
+    EXPECT_TRUE(false);
+}
+
 TEST_F(ScriptCanvasTestFixture, EntityIdInputForOnGraphStart)
 {
     RunUnitTestGraph("LY_SC_UnitTest_EntityIdInputForOnGraphStart");

From 188f2f5afec1d7449ab18fb93d056c3e48f6888b Mon Sep 17 00:00:00 2001
From: chcurran <82187351+carlitosan@users.noreply.github.com>
Date: Fri, 30 Jul 2021 14:36:57 -0700
Subject: [PATCH 045/251] remove failing tests, since the farm proved the SC
 suite is running

Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com>
---
 .../Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp           | 5 -----
 1 file changed, 5 deletions(-)

diff --git a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp
index df29a56fd5..c2fa59b037 100644
--- a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp
+++ b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_RuntimeInterpreted.cpp
@@ -84,11 +84,6 @@ public:
     }
 };
 
-TEST_F(ScriptCanvasTestFixture, ProveError)
-{
-    EXPECT_TRUE(false);
-}
-
 TEST_F(ScriptCanvasTestFixture, EntityIdInputForOnGraphStart)
 {
     RunUnitTestGraph("LY_SC_UnitTest_EntityIdInputForOnGraphStart");

From c5dcef180c38317bcb39ef1859ca33d299d62107 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:30:11 -0700
Subject: [PATCH 046/251] fixes/improvements to AzCore

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzCore/AzCore/std/string/conversions.h    | 47 +++++++++--
 .../AzCore/AzCore/std/string/utf8/unchecked.h | 79 +++++++++++++------
 .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp      |  9 ++-
 Code/Framework/AzCore/Tests/AZStd/String.cpp  |  9 ---
 4 files changed, 104 insertions(+), 40 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 4dc5bbd547..cb90881933 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -35,11 +35,11 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else
                 {
@@ -54,11 +54,29 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
+                }
+                else
+                {
+                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
+                    using StringType = AZStd::basic_string;
+                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
+                }
+            }
+
+            static inline void to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf16to8(first, last, dest, destSize);
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf32to8(first, last, dest, destSize);
                 }
                 else
                 {
@@ -73,11 +91,11 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else
                 {
@@ -92,11 +110,11 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else
                 {
@@ -326,6 +344,19 @@ namespace AZStd
         return to_string(dest, src.c_str(), src.length());
     }
 
+    inline void to_string(char* dest, size_t destSize, const wchar_t* str, size_t srcLen = 0)
+    {
+        if (srcLen == 0)
+        {
+            srcLen = wcslen(str) + 1;
+        }
+
+        if (srcLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen + 1); // copy null terminator
+        }
+    }
+
     template
     int stoi(const AZStd::basic_string& str, AZStd::size_t* idx = 0, int base = 10)
     {
diff --git a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
index 9608ff897b..cfc917ddc4 100644
--- a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
+++ b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
@@ -92,33 +92,58 @@ namespace Utf8::Unchecked
             return temp;
         }
 
-        static Iterator to_utf8_sequence(AZ::u32 cp, Iterator result)
+        static Iterator to_utf8_sequence(AZ::u32 cp, Iterator& result, size_t& resultMaxSize)
         {
             if (cp < 0x80)
             {
                 // one octet
+                resultMaxSize -= 1; // no need to check the calling function will exit the loop
                 *(result++) = static_cast(cp);
             }
             else if (cp < 0x800)
             {
                 // two octets
-                *(result++) = static_cast((cp >> 6) | 0xc0);
-                *(result++) = static_cast((cp & 0x3f) | 0x80);
+                if (resultMaxSize >= 2)
+                {
+                    *(result++) = static_cast((cp >> 6) | 0xc0);
+                    *(result++) = static_cast((cp & 0x3f) | 0x80);
+                    resultMaxSize -= 2;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             else if (cp < 0x10000)
             {
                 // three octets
-                *(result++) = static_cast((cp >> 12) | 0xe0);
-                *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
-                *(result++) = static_cast((cp & 0x3f) | 0x80);
+                if (resultMaxSize >= 3)
+                {
+                    *(result++) = static_cast((cp >> 12) | 0xe0);
+                    *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
+                    *(result++) = static_cast((cp & 0x3f) | 0x80);
+                    resultMaxSize -= 3;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             else
             {
                 // four octets
-                *(result++) = static_cast((cp >> 18) | 0xf0);
-                *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80);
-                *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
-                *(result++) = static_cast((cp & 0x3f) | 0x80);
+                if (resultMaxSize >= 4)
+                {
+                    *(result++) = static_cast((cp >> 18) | 0xf0);
+                    *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80);
+                    *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
+                    *(result++) = static_cast((cp & 0x3f) | 0x80);
+                    resultMaxSize -= 4;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             return result;
         }
@@ -155,9 +180,9 @@ namespace Utf8::Unchecked
     };
 
     template 
-    Utf8Iterator utf16to8(u16bit_iterator start, u16bit_iterator end, Utf8Iterator result)
+    Utf8Iterator utf16to8(u16bit_iterator start, u16bit_iterator end, Utf8Iterator result, size_t resultMaxSize)
     {
-        while (start != end)
+        while (start != end && resultMaxSize > 0)
         {
             AZ::u32 cp = Utf8::Internal::mask16(*start++);
             // Take care of surrogate pairs first
@@ -166,52 +191,62 @@ namespace Utf8::Unchecked
                 AZ::u32 trail_surrogate = Utf8::Internal::mask16(*start++);
                 cp = (cp << 10) + trail_surrogate + Internal::SURROGATE_OFFSET;
             }
-            octet_iterator::to_utf8_sequence(cp, result);
+            octet_iterator::to_utf8_sequence(cp, result, resultMaxSize);
         }
         return result;
     }
 
     template 
-    u16bit_iterator utf8to16(Utf8Iterator start, Utf8Iterator end, u16bit_iterator result)
+    u16bit_iterator utf8to16(Utf8Iterator start, Utf8Iterator end, u16bit_iterator result, size_t resultMaxSize)
     {
         octet_iterator utf8Start(start);
         octet_iterator utf8Last(end);
-        while (utf8Start != utf8Last)
+        while (utf8Start != utf8Last && resultMaxSize > 0)
         {
             AZ::u32 cp = *utf8Start++;
             if (cp > 0xffff)
             {
                 //make a surrogate pair
-                *result++ = static_cast((cp >> 10) + Internal::LEAD_OFFSET);
-                *result++ = static_cast((cp & 0x3ff) + Internal::TRAIL_SURROGATE_MIN);
+                if (resultMaxSize >= 2)
+                {
+                    *result++ = static_cast((cp >> 10) + Internal::LEAD_OFFSET);
+                    *result++ = static_cast((cp & 0x3ff) + Internal::TRAIL_SURROGATE_MIN);
+                    resultMaxSize -= 2;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             else
             {
                 *result++ = static_cast(cp);
+                resultMaxSize -= 1;
             }
         }
         return result;
     }
 
     template 
-    Utf8Iterator utf32to8(u32bit_iterator start, u32bit_iterator end, Utf8Iterator result)
+    Utf8Iterator utf32to8(u32bit_iterator start, u32bit_iterator end, Utf8Iterator result, size_t resultMaxSize)
     {
-        while (start != end)
+        while (start != end && resultMaxSize > 0)
         {
-            octet_iterator::to_utf8_sequence(*start++, result);
+            octet_iterator::to_utf8_sequence(*start++, result, resultMaxSize);
         }
 
         return result;
     }
 
     template 
-    u32bit_iterator utf8to32(Utf8Iterator start, Utf8Iterator end, u32bit_iterator result)
+    u32bit_iterator utf8to32(Utf8Iterator start, Utf8Iterator end, u32bit_iterator result, size_t resultMaxSize)
     {
         octet_iterator utf8Start(start);
         octet_iterator utf8Last(end);
-        while (utf8Start != utf8Last)
+        while (utf8Start != utf8Last && resultMaxSize > 0)
         {
             *result++ = *utf8Start++;
+            --resultMaxSize;
         }
 
         return result;
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
index 66257735b4..c57f2b31f6 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
@@ -11,6 +11,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
@@ -29,7 +30,9 @@ namespace AZ
             result.m_pathIncludesFilename = true;
             // Platform specific get exe path: http://stackoverflow.com/a/1024937
             // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
-            const DWORD pathLen = GetModuleFileNameA(nullptr, exeStorageBuffer, static_cast(exeStorageSize));
+            AZStd::wstring pathBuffer;
+            pathBuffer.resize(exeStorageSize);
+            const DWORD pathLen = GetModuleFileName(nullptr, pathBuffer.data(), static_cast(exeStorageSize));
             const DWORD errorCode = GetLastError();
             if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER)
             {
@@ -39,6 +42,10 @@ namespace AZ
             {
                 result.m_pathStored = ExecutablePathResult::GeneralError;
             }
+            else
+            {
+                AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBuffer.c_str());
+            }
 
             return result;
         }
diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp
index 0e6ea4727c..2d2602e456 100644
--- a/Code/Framework/AzCore/Tests/AZStd/String.cpp
+++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp
@@ -628,10 +628,6 @@ namespace UnitTest
         }
     }
 
-#if defined(AZ_COMPILER_MSVC)
-#   pragma warning(push)
-#   pragma warning( disable: 4428 )   // universal-character-name encountered in source
-#endif // AZ_COMPILER_MSVC
     TEST_F(String, Algorithms)
     {
         string str = string::format("%s %d", "BlaBla", 5);
@@ -1114,11 +1110,6 @@ namespace UnitTest
         EXPECT_FALSE(other2.Valid());
     }
 
-    // StringAlgorithmTest-End
-#if defined(AZ_COMPILER_MSVC)
-#   pragma warning(pop)
-#endif // AZ_COMPILER_MSVC
-
     TEST_F(String, ConstString)
     {
         string_view cstr1;

From 63445e107a0da2584475b16539d2499f54153909 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:33:50 -0700
Subject: [PATCH 047/251] fxies for AzFramework

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Network/AssetProcessorConnection.cpp      |  2 +-
 .../Android/platform_android_files.cmake      |  1 -
 .../AssetProcessorConnection_Default.cpp      | 24 ------------------
 .../AzFramework/IO/LocalFileIO_WinAPI.cpp     | 17 ++++++++-----
 .../AssetProcessorConnection_WinAPI.cpp       | 25 -------------------
 .../Platform/Linux/platform_linux_files.cmake |  1 -
 .../Platform/Mac/platform_mac_files.cmake     |  1 -
 .../AssetSystemComponentHelper_Windows.cpp    | 12 ++++++---
 .../TargetManagementComponent_Windows.cpp     |  9 ++++---
 .../Windowing/NativeWindow_Windows.cpp        | 17 ++++++++-----
 .../Windows/platform_windows_files.cmake      |  1 -
 .../Platform/iOS/platform_ios_files.cmake     |  1 -
 12 files changed, 36 insertions(+), 75 deletions(-)
 delete mode 100644 Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
 delete mode 100644 Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp

diff --git a/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp b/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp
index a65a3079a0..ebea29c2d9 100644
--- a/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp
+++ b/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp
@@ -136,7 +136,7 @@ namespace AzFramework
             AZStd::array buffer;
             azsnprintf(buffer.data(), buffer.size(), "(%p/%#" PRIxPTR "): %s\n", this, numericThreadId, msg.data());
 
-            Platform::DebugOutput(buffer.data());
+            AZ::Debug::Platform::OutputToDebugger("AssetProcessorConnection", buffer.data());
 #else // ASSETPROCESORCONNECTION_VERBOSE_LOGGING is not defined
             (void)format;
 #endif
diff --git a/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake b/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake
index 35b5a10151..c220bc1154 100644
--- a/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake
@@ -14,7 +14,6 @@ set(FILES
     AzFramework/Application/Application_Android.cpp
     ../Common/Unimplemented/AzFramework/Asset/AssetSystemComponentHelper_Unimplemented.cpp
     AzFramework/IO/LocalFileIO_Android.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     ../Common/Default/AzFramework/TargetManagement/TargetManagementComponent_Default.cpp
     AzFramework/Windowing/NativeWindow_Android.cpp
diff --git a/Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp b/Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
deleted file mode 100644
index 5bc020a1d6..0000000000
--- a/Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
+++ /dev/null
@@ -1,24 +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 AzFramework
-{
-    namespace AssetSystem
-    {
-        namespace Platform
-        {
-            void DebugOutput(const char* message)
-            {
-                fputs("AssetProcessorConnection:", stdout);
-                fputs(message, stdout);
-            }
-        }
-    }
-}
diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
index 4c7d84b511..58afebfb90 100644
--- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
+++ b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
@@ -9,6 +9,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AZ
 {
@@ -33,7 +34,7 @@ namespace AZ
             char resolvedPath[AZ_MAX_PATH_LEN];
             ResolvePath(filePath, resolvedPath, AZ_MAX_PATH_LEN);
 
-            AZ::OSString searchPattern;
+            AZStd::string searchPattern;
             if ((resolvedPath[0] == 0) || (resolvedPath[1] == 0))
             {
                 return ResultCode::Error; // not a valid path.
@@ -54,7 +55,9 @@ namespace AZ
             searchPattern += "\\*.*"; // use our own filtering function!
 
             WIN32_FIND_DATA findData;
-            HANDLE hFind = FindFirstFile(searchPattern.c_str(), &findData);
+            AZStd::wstring searchPatternW;
+            AZStd::to_wstring(searchPatternW, searchPattern.c_str());
+            HANDLE hFind = FindFirstFileW(searchPatternW.c_str(), &findData);
 
             if (hFind != INVALID_HANDLE_VALUE)
             {
@@ -63,15 +66,17 @@ namespace AZ
                 char tempBuffer[AZ_MAX_PATH_LEN];
                 do
                 {
-                    AZStd::string_view filenameView = findData.cFileName;
+                    AZStd::string fileName;
+                    AZStd::to_string(fileName, findData.cFileName);
+                    AZStd::string_view filenameView = fileName;
                     // Skip over the current directory and parent directory paths to prevent infinite recursion
-                    if (filenameView == "." || filenameView == ".." || !NameMatchesFilter(findData.cFileName, filter))
+                    if (filenameView == "." || filenameView == ".." || !NameMatchesFilter(fileName.c_str(), filter))
                     {
                         continue;
                     }
 
-                    AZ::OSString foundFilePath = CheckForTrailingSlash(resolvedPath);
-                    foundFilePath += findData.cFileName;
+                    AZStd::string foundFilePath = CheckForTrailingSlash(resolvedPath);
+                    foundFilePath += fileName;
                     AZStd::replace(foundFilePath.begin(), foundFilePath.end(), '\\', '/');
 
                     // if aliased, de-alias!
diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp
deleted file mode 100644
index a02e697df6..0000000000
--- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp
+++ /dev/null
@@ -1,25 +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 AzFramework
-{
-    namespace AssetSystem
-    {
-        namespace Platform
-        {
-            void DebugOutput(const char* message)
-            {
-                OutputDebugString("AssetProcessorConnection:");
-                OutputDebugString(message);
-            }
-        }
-    }
-}
diff --git a/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake b/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake
index 60b16938a1..21201d954d 100644
--- a/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake
@@ -17,7 +17,6 @@ set(FILES
     AzFramework/Process/ProcessCommon.h
     AzFramework/Process/ProcessCommunicator_Linux.cpp
     ../Common/UnixLike/AzFramework/IO/LocalFileIO_UnixLike.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     ../Common/Default/AzFramework/TargetManagement/TargetManagementComponent_Default.cpp
     AzFramework/Windowing/NativeWindow_Linux.cpp
diff --git a/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake b/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake
index c428160892..78f11a65da 100644
--- a/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake
@@ -17,7 +17,6 @@ set(FILES
     AzFramework/Process/ProcessCommon.h
     AzFramework/Process/ProcessCommunicator_Mac.cpp
     ../Common/UnixLike/AzFramework/IO/LocalFileIO_UnixLike.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     AzFramework/TargetManagement/TargetManagementComponent_Mac.cpp
     AzFramework/Windowing/NativeWindow_Mac.mm
diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp
index 4b685b25a3..a3782ae081 100644
--- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp
+++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp
@@ -48,10 +48,10 @@ namespace AzFramework::AssetSystem::Platform
                     // Get the first module, because that will be the executable
                     if (EnumProcessModules(processHandle, &moduleHandle, sizeof(moduleHandle), &bytesNeededForAllProcessModules))
                     {
-                        char processName[4096] = TEXT("");
-                        if (GetModuleBaseNameA(processHandle, moduleHandle, processName, AZ_ARRAY_SIZE(processName)) > 0)
+                        wchar_t processName[4096] = L"";
+                        if (GetModuleBaseName(processHandle, moduleHandle, processName, AZ_ARRAY_SIZE(processName)) > 0)
                         {
-                            if (azstricmp(processName, "AssetProcessor") == 0)
+                            if (azwcsicmp(processName, L"AssetProcessor") == 0)
                             {
                                 AllowSetForegroundWindow(processId);
                             }
@@ -126,7 +126,11 @@ namespace AzFramework::AssetSystem::Platform
         si.wShowWindow = SW_MINIMIZE;
         PROCESS_INFORMATION pi;
 
-        bool createResult = ::CreateProcessA(nullptr, fullLaunchCommand.data(), nullptr, nullptr, FALSE, 0, nullptr, AZ::IO::FixedMaxPathString{ executableDirectory }.c_str(), &si, &pi) != 0;
+        AZStd::wstring fullLaunchCommandW;
+        AZStd::to_wstring(fullLaunchCommandW, fullLaunchCommand.c_str());
+        AZStd::wstring execututableDirectoryW;
+        AZStd::to_wstring(execututableDirectoryW, executableDirectory.data());
+        bool createResult = ::CreateProcessW(nullptr, fullLaunchCommandW.data(), nullptr, nullptr, FALSE, 0, nullptr, execututableDirectoryW.c_str(), &si, &pi) != 0;
 
         if (ap_tether_lifetime && apJob && createResult)
         {
diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
index fbfb3778cb..e168968278 100644
--- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
+++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
@@ -10,6 +10,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AzFramework
 {
@@ -35,12 +36,12 @@ namespace AzFramework
         AZStd::string GetNeighborhoodName()
         {
             AZStd::string neighborhoodName;
-            
-            char localhost[MAX_COMPUTERNAME_LENGTH + 1];
+
+            wchar_t localhost[MAX_COMPUTERNAME_LENGTH + 1];
             DWORD len = AZ_ARRAY_SIZE(localhost);
-            if (GetComputerName(localhost, &len))
+            if (GetComputerNameW(localhost, &len))
             {
-                neighborhoodName = localhost;
+                AZStd::to_string(neighborhoodName, localhost);
             }
 
             return neighborhoodName;
diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp
index 0047929120..22a293891c 100644
--- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp
+++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp
@@ -11,6 +11,7 @@
 
 #include 
 #include 
+#include 
 
 namespace AzFramework
 {
@@ -41,7 +42,7 @@ namespace AzFramework
         static DWORD ConvertToWin32WindowStyleMask(const WindowStyleMasks& styleMasks);
         static LRESULT CALLBACK WindowCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
 
-        static const char* s_defaultClassName;
+        static const wchar_t* s_defaultClassName;
 
         void WindowSizeChanged(const uint32_t width, const uint32_t height);
 
@@ -57,7 +58,7 @@ namespace AzFramework
         GetDpiForWindowType* m_getDpiFunction = nullptr;
     };
 
-    const char* NativeWindowImpl_Win32::s_defaultClassName = "O3DEWin32Class";
+    const wchar_t* NativeWindowImpl_Win32::s_defaultClassName = L"O3DEWin32Class";
 
     NativeWindow::Implementation* NativeWindow::Implementation::Create()
     {
@@ -88,7 +89,7 @@ namespace AzFramework
 
         // register window class if it does not exist
         WNDCLASSEX windowClass;
-        if (GetClassInfoEx(hInstance, s_defaultClassName, &windowClass) == false)
+        if (GetClassInfoExW(hInstance, s_defaultClassName, &windowClass) == false)
         {
             windowClass.cbSize = sizeof(WNDCLASSEX);
             windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
@@ -127,8 +128,10 @@ namespace AzFramework
         m_height = geometry.m_height;
 
         // create main window
-        m_win32Handle = CreateWindow(
-            s_defaultClassName, title.c_str(),
+        AZStd::wstring titleW;
+        AZStd::to_wstring(titleW, title);
+        m_win32Handle = CreateWindowW(
+            s_defaultClassName, titleW.c_str(),
             windowStyle,
             geometry.m_posX, geometry.m_posY, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top,
             NULL, NULL, hInstance, NULL);
@@ -175,7 +178,9 @@ namespace AzFramework
 
     void NativeWindowImpl_Win32::SetWindowTitle(const AZStd::string& title)
     {
-        SetWindowText(m_win32Handle, title.c_str());
+        AZStd::wstring titleW;
+        AZStd::to_wstring(titleW, title);
+        SetWindowTextW(m_win32Handle, titleW.c_str());
     }
 
     DWORD NativeWindowImpl_Win32::ConvertToWin32WindowStyleMask(const WindowStyleMasks& styleMasks)
diff --git a/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake b/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake
index af43234bd0..b8f5b5f841 100644
--- a/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake
@@ -18,7 +18,6 @@ set(FILES
     AzFramework/Process/ProcessCommunicator_Win.cpp
     ../Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
     AzFramework/IO/LocalFileIO_Windows.cpp
-    ../Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
     AzFramework/Windowing/NativeWindow_Windows.cpp
diff --git a/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake b/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake
index f47eb136be..7745f43ec9 100644
--- a/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake
+++ b/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake
@@ -14,7 +14,6 @@ set(FILES
     AzFramework/Application/Application_iOS.mm
     ../Common/Unimplemented/AzFramework/Asset/AssetSystemComponentHelper_Unimplemented.cpp
     ../Common/UnixLike/AzFramework/IO/LocalFileIO_UnixLike.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     ../Common/Default/AzFramework/TargetManagement/TargetManagementComponent_Default.cpp
     AzFramework/Windowing/NativeWindow_ios.mm

From 3f6335dc324d0b80ec730af155026fbf97d2f8a4 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:34:14 -0700
Subject: [PATCH 048/251] Fixes for AzQtComponents

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzQtComponents/AzQtComponents/Gallery/main.cpp       | 9 ++-------
 1 file changed, 2 insertions(+), 7 deletions(-)

diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
index 51ca2b349f..2a4a29ffe6 100644
--- a/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
+++ b/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
@@ -40,13 +40,8 @@ const QString g_ui_1_0_SettingKey = QStringLiteral("useUI_1_0");
 
 static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
 {
-#ifdef Q_OS_WIN
-    OutputDebugStringW(L"Qt: ");
-    OutputDebugStringW(reinterpret_cast(message.utf16()));
-    OutputDebugStringW(L"\n");
-#else
-    std::wcerr << L"Qt: " << message.toStdWString() << std::endl;
-#endif
+    AZ::Debug::Platform::OutputToDebugger("Qt", message.toStdString().c_str());
+    AZ::Debug::Platform::OutputToDebugger(nullptr, "\n");
 }
 
 /*

From 1b4c06d03dbe44243cbf1dc03005aad85b0e36f0 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:38:46 -0700
Subject: [PATCH 049/251] other Framework fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzTest/AzTest/Platform/Windows/Platform_Windows.cpp        | 3 ++-
 .../Platform/Windows/GridMate/Session/LANSession_Windows.cpp   | 2 +-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp b/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp
index 08e86fdc16..777ba66c6d 100644
--- a/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp
+++ b/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp
@@ -9,6 +9,7 @@
 #include 
 #include 
 #include 
+#include 
 
 //-------------------------------------------------------------------------------------------------
 class ModuleHandle
@@ -151,7 +152,7 @@ namespace AZ
             va_start(mark, format);
             azvsnprintf(message, MAX_PRINT_MSG, format, mark);
             va_end(mark);
-            OutputDebugString(message);
+            AZ::Debug::Platform::OutputToDebugger(nullptr, message);
         }
 
         AZ::EnvironmentInstance Platform::GetTestRunnerEnvironment()
diff --git a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
index 4bf038a2cf..59a1c65781 100644
--- a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
+++ b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
@@ -21,7 +21,7 @@ namespace GridMate
 
             char procPath[256];
             char procName[256];
-            DWORD ret = GetModuleFileName(NULL, procPath, 256);
+            DWORD ret = GetModuleFileNameA(NULL, procPath, 256);
             if (ret > 0)
             {
                 ::_splitpath_s(procPath, 0, 0, 0, 0, procName, 256, 0, 0);

From 41ad6d7b7a9326f23c29abf6cef8fb3e442f1d05 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:39:02 -0700
Subject: [PATCH 050/251] Code/Legacy cleanup

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Legacy/CryCommon/platform_impl.cpp       |  38 ++--
 Code/Legacy/CrySystem/ConsoleHelpGen.cpp      |   6 +-
 Code/Legacy/CrySystem/DebugCallStack.cpp      |  19 +-
 Code/Legacy/CrySystem/IDebugCallStack.cpp     |   2 +-
 .../CrySystem/LocalizedStringManager.cpp      |  31 ++-
 Code/Legacy/CrySystem/Log.cpp                 |  21 +--
 Code/Legacy/CrySystem/System.cpp              |  18 +-
 Code/Legacy/CrySystem/SystemCFG.cpp           |  42 +++--
 Code/Legacy/CrySystem/SystemCFG.h             |   6 -
 Code/Legacy/CrySystem/SystemInit.cpp          |  57 +++---
 Code/Legacy/CrySystem/SystemWin32.cpp         |  40 ++--
 .../CrySystem/WindowsErrorReporting.cpp       |   4 +-
 Code/Legacy/CrySystem/XConsole.cpp            | 177 ++++++++----------
 Code/Legacy/CrySystem/XConsole.h              |  18 +-
 Code/Legacy/CrySystem/XConsoleVariable.cpp    |  32 ++--
 Code/Legacy/CrySystem/XConsoleVariable.h      |  52 +++--
 16 files changed, 267 insertions(+), 296 deletions(-)

diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp
index 54bf38aaa0..6badd2fe1e 100644
--- a/Code/Legacy/CryCommon/platform_impl.cpp
+++ b/Code/Legacy/CryCommon/platform_impl.cpp
@@ -10,13 +10,14 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 
 #include 
 #include 
 #include 
 #include 
+#include 
+#include 
 
 // Section dictionary
 #if defined(AZ_RESTRICTED_PLATFORM)
@@ -245,18 +246,23 @@ int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const ch
     {
         return 0;
     }
-    return MessageBox(NULL, lpText, lpCaption, uType);
+    AZStd::wstring lpTextW;
+    AZStd::to_wstring(lpTextW, lpText);
+    AZStd::wstring lpCaptionW;
+    AZStd::to_wstring(lpCaptionW, lpCaption);
+    return MessageBoxW(NULL, lpTextW.c_str(), lpCaptionW.c_str(), uType);
 #else
     return 0;
 #endif
 }
 
 // Initializes root folder of the game, optionally returns exe and path name.
-void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], [[maybe_unused]] uint nRootSize)
+void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], uint nRootSize)
 {
-    WCHAR szPath[_MAX_PATH];
-    size_t nLen = GetModuleFileNameW(GetModuleHandle(NULL), szPath, _MAX_PATH);
-    assert(nLen < _MAX_PATH && "The path to the current executable exceeds the expected length");
+    char szPath[_MAX_PATH];
+    AZ::Utils::GetExecutablePathReturnType ret = AZ::Utils::GetExecutablePath(szPath, _MAX_PATH);
+    AZ_Assert(ret.m_pathStored == AZ::Utils::ExecutablePathResult::Success, "The path to the current executable exceeds the expected length");
+    const size_t nLen = strnlen(szPath, _MAX_PATH);
 
     // Find path above exe name and deepest folder.
     bool firstIteration = true;
@@ -271,25 +277,27 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], [[ma
                 // Return exe path
                 if (szExeRootName)
                 {
-                    Unicode::Convert(szExeRootName, n+1, szPath);
+                    azstrncpy(szExeRootName, nRootSize, szPath + n + 1, nLen - n - 1);
                 }
 
                 // Return exe name
                 if (szExeFileName)
                 {
-                    Unicode::Convert(szExeFileName, nExeSize, szPath + n);
+                    azstrncpy(szExeFileName, nExeSize, szPath + n, nLen - n);
                 }
                 firstIteration = false;
             }
             // Check if the engineroot exists
-            wcscat_s(szPath, L"\\engine.json");
+            azstrcat(szPath, "\\engine.json");
             WIN32_FILE_ATTRIBUTE_DATA data;
-            BOOL res = GetFileAttributesExW(szPath, GetFileExInfoStandard, &data);
+            AZStd::wstring szPathW;
+            AZStd::to_wstring(szPathW, szPath);
+            BOOL res = GetFileAttributesExW(szPathW.c_str(), GetFileExInfoStandard, &data);
             if (res != 0 && data.dwFileAttributes != INVALID_FILE_ATTRIBUTES)
             {
                 // Found file
                 szPath[n] = 0;
-                SetCurrentDirectoryW(szPath);
+                SetCurrentDirectoryW(szPathW.c_str());
                 break;
             }
         }
@@ -423,7 +431,9 @@ uint32 CryGetFileAttributes(const char* lpFileName)
 #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
 #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #else
-    res = GetFileAttributesEx(lpFileName, GetFileExInfoStandard, &data);
+    AZStd::wstring lpFileNameW;
+    AZStd::to_wstring(lpFileNameW, lpFileName);
+    res = GetFileAttributesExW(lpFileNameW.c_str(), GetFileExInfoStandard, &data);
 #endif
     return res ? data.dwFileAttributes : -1;
 }
@@ -438,7 +448,9 @@ bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes)
 #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
 #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #else
-    return SetFileAttributes(lpFileName, dwFileAttributes) != 0;
+    AZStd::wstring lpFileNameW;
+    AZStd::to_wstring(lpFileNameW, lpFileName);
+    return SetFileAttributes(lpFileNameW.c_str(), dwFileAttributes) != 0;
 #endif
 }
 
diff --git a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp
index ff86577258..661487a299 100644
--- a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp
+++ b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp
@@ -6,13 +6,13 @@
  *
  */
 
+#if defined(WIN32) || defined(WIN64)
 
 #include "CrySystem_precompiled.h"
 
-#if defined(WIN32) || defined(WIN64)
-
 #include "ConsoleHelpGen.h"
 #include "System.h"
+#include 
 
 
 
@@ -132,7 +132,7 @@ void CConsoleHelpGen::LogVersion(FILE* f) const
     char s[1024];
 
     {
-        GetModuleFileName(NULL, s, sizeof(s));
+        AZ::Utils::GetExecutablePath(s, 1024);
 
         char fdir[_MAX_PATH];
         char fdrive[_MAX_PATH];
diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp
index c5d932429c..289d4070ff 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/DebugCallStack.cpp
@@ -18,6 +18,7 @@
 
 #include 
 #include 
+#include 
 
 #define VS_VERSION_INFO                 1
 #define IDD_CRITICAL_ERROR              101
@@ -400,7 +401,11 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
             timeStamp = tempBuffer;
 
             AZStd::string backupFileName = backupPath + timeStamp + " error.log";
-            CopyFile(fileName.c_str(), backupFileName.c_str(), true);
+            AZStd::wstring fileNameW;
+            AZStd::to_wstring(fileNameW, fileName.c_str());
+            AZStd::wstring backupFileNameW;
+            AZStd::to_wstring(backupFileNameW, backupFileName.c_str());
+            CopyFileW(fileNameW.c_str(), backupFileNameW.c_str(), true);
         }
     }
 
@@ -594,7 +599,11 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
                 }
 
                 AZStd::string backupFileName = backupPath + timeStamp + " error.dmp";
-                CopyFile(fileName.c_str(), backupFileName.c_str(), true);
+                AZStd::wstring fileNameW;
+                AZStd::to_wstring(fileNameW, fileName.c_str());
+                AZStd::wstring backupFileNameW;
+                AZStd::to_wstring(backupFileNameW, backupFileName.c_str());
+                CopyFileW(fileNameW.c_str(), backupFileNameW.c_str(), true);
             }
 
             CryEngineExceptionFilterMiniDump(pex, fileName.c_str(), mdumpValue);
@@ -635,11 +644,11 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         {
             if (SaveCurrentLevel())
             {
-                MessageBox(NULL, "Level has been successfully saved!\r\nPress Ok to terminate Editor.", "Save", MB_OK);
+                MessageBoxW(NULL, L"Level has been successfully saved!\r\nPress Ok to terminate Editor.", L"Save", MB_OK);
             }
             else
             {
-                MessageBox(NULL, "Error saving level.\r\nPress Ok to terminate Editor.", "Save", MB_OK | MB_ICONWARNING);
+                MessageBoxW(NULL, L"Error saving level.\r\nPress Ok to terminate Editor.", L"Save", MB_OK | MB_ICONWARNING);
             }
         }
     }
@@ -855,7 +864,7 @@ void DebugCallStack::GetProcNameForAddr(void* addr, AZStd::string& procName, voi
 AZStd::string DebugCallStack::GetCurrentFilename()
 {
     char fullpath[MAX_PATH_LENGTH + 1];
-    GetModuleFileName(NULL, fullpath, MAX_PATH_LENGTH);
+    AZ::Utils::GetExecutablePath(fullpath, MAX_PATH_LENGTH);
     return fullpath;
 }
 
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp
index ff43f6e56f..bee43b237b 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp
@@ -187,7 +187,7 @@ AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option")
     azstrcat(str, length, "\n");
 
 #if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_APPEND_MODULENAME
-    GetModuleFileNameA(NULL, s, sizeof(s));
+    AZ::Utils::GetExecutablePath(s, sizeof(s));
     
     // Log EXE filename only if possible (not full EXE path which could contain sensitive info)
     AZStd::string exeName;
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
index e3ccb22f88..42bdb3afef 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
@@ -25,6 +25,7 @@
 
 #include 
 #include 
+#include 
 
 #define MAX_CELL_COUNT 32
 
@@ -2329,12 +2330,11 @@ bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, AZStd::strin
     }
 }
 
-template
-void InternalFormatStringMessage(StringClass& outString, const StringClass& sString, const CharType** sParams, int nParams)
+void InternalFormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams)
 {
-    static const CharType token = (CharType) '%';
-    static const CharType tokens1[2] = { token, (CharType) '\0' };
-    static const CharType tokens2[3] = { token, token, (CharType) '\0' };
+    static const char token = '%';
+    static const char tokens1[2] = { token, '\0' };
+    static const char tokens2[3] = { token, token, '\0' };
 
     int maxArgUsed = 0;
     int lastPos = 0;
@@ -2342,8 +2342,8 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
     const int sourceLen = sString.length();
     while (true)
     {
-        int foundPos = sString.find(token, curPos);
-        if (foundPos != string::npos)
+        auto foundPos = sString.find(token, curPos);
+        if (foundPos != AZStd::string::npos)
         {
             if (foundPos + 1 < sourceLen)
             {
@@ -2360,8 +2360,8 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
                     }
                     else
                     {
-                        StringClass tmp (sString);
-                        tmp.replace(tokens1, tokens2);
+                        AZStd::string tmp(sString);
+                        AZ::StringFunc::Replace(tmp, tokens1, tokens2);
                         if constexpr (sizeof(*tmp.c_str()) == sizeof(char))
                         {
                             CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Parameter for argument %d is missing. [%s]", nArg + 1, (const char*)tmp.c_str());
@@ -2391,11 +2391,10 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
     }
 }
 
-template
-void InternalFormatStringMessage(StringClass& outString, const StringClass& sString, const CharType* param1, const CharType* param2 = 0, const CharType* param3 = 0, const CharType* param4 = 0)
+void InternalFormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0)
 {
     static const int MAX_PARAMS = 4;
-    const CharType* params[MAX_PARAMS] = { param1, param2, param3, param4 };
+    const char* params[MAX_PARAMS] = { param1, param2, param3, param4 };
     int nParams = 0;
     while (nParams < MAX_PARAMS && params[nParams])
     {
@@ -2677,7 +2676,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
         localtime_s(&thetime, &t);
         t = gEnv->pTimer->DateToSecondsUTC(thetime);
     }
-    outTimeString.resize(0);
+    outTimeString.clear();
     LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT;
     DWORD flags = bShowSeconds == false ? TIME_NOSECONDS : 0;
     SYSTEMTIME systemTime;
@@ -2689,7 +2688,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
         AZStd::fixed_wstring<256> tmpString;
         tmpString.resize(len);
         ::GetTimeFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len);
-        Unicode::Convert(outTimeString, tmpString);
+        AZStd::to_string(outTimeString, tmpString.data());
     }
 }
 
@@ -2719,7 +2718,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
             tmpString.resize(len);
             ::GetDateFormatW(lcID, 0, &systemTime, L"ddd", (wchar_t*) tmpString.c_str(), len);
             AZStd::string utf8;
-            Unicode::Convert(utf8, tmpString);
+            AZStd::to_string(utf8, tmpString.data());
             outDateString.append(utf8);
             outDateString.append(" ");
         }
@@ -2732,7 +2731,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
         tmpString.resize(len);
         ::GetDateFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len);
         AZStd::string utf8;
-        Unicode::Convert(utf8, tmpString);
+        AZStd::to_string(utf8, tmpString.data());
         outDateString.append(utf8);
     }
 }
diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp
index c23ed6e264..6ee6af6c22 100644
--- a/Code/Legacy/CrySystem/Log.cpp
+++ b/Code/Legacy/CrySystem/Log.cpp
@@ -18,7 +18,6 @@
 #include 
 #include "System.h"
 #include "CryPath.h"                    // PathUtil::ReplaceExtension()
-#include "UnicodeFunctions.h"
 
 #include 
 #include 
@@ -1052,13 +1051,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
 #if !defined(_RELEASE)
     if (queueState == MessageQueueState::NotQueued)
     {
-        // Note: OutputDebugString(A) only accepts current ANSI code-page, and the W variant will call the A variant internally.
-        // Here we replace non-ASCII characters with '?', which is the same as OutputDebugStringW will do for non-ANSI.
-        // Thus, we discard slightly more characters (ie, those inside the current ANSI code-page, but outside ASCII).
-        // In exchange, we save double-converting that would have happened otherwise (UTF-8 -> UTF-16 -> ANSI).
-        LogStringType asciiString;
-        Unicode::ConvertSafe(asciiString, tempString);
-        OutputDebugString(asciiString.c_str());
+        AZ::Debug::Platform::OutputToDebugger(nullptr, tempString.c_str());
     }
 
     if (!bIsMainThread)
@@ -1224,8 +1217,8 @@ void CLog::CreateBackupFile() const
     AZStd::string sFileWithoutExt = PathUtil::GetFileName(m_szFilename);
 
     {
-        assert(::strstr(sFileWithoutExt, ":") == 0);
-        assert(::strstr(sFileWithoutExt, "\\") == 0);
+        assert(::strstr(sFileWithoutExt.c_str(), ":") == 0);
+        assert(::strstr(sFileWithoutExt.c_str(), "\\") == 0);
     }
 
     PathUtil::RemoveExtension(sFileWithoutExt);
@@ -1255,11 +1248,9 @@ void CLog::CreateBackupFile() const
 
                     if (sName.find("BackupNameAttachment=") == AZStd::string::npos)
                     {
-#ifdef WIN32
-                        OutputDebugString("Log::CreateBackupFile ERROR '");
-                        OutputDebugString(sName.c_str());
-                        OutputDebugString("' not recognized \n");
-#endif
+                        AZ::Debug::Platform::OutputToDebugger("CrySystem Log", "Log::CreateBackupFile ERROR '");
+                        AZ::Debug::Platform::OutputToDebugger(nullptr, sName.c_str());
+                        AZ::Debug::Platform::OutputToDebugger(nullptr, "' not recognized \n");
                         assert(0);      // broken log file? - first line should include this name - written by LogVersion()
                         return;
                     }
diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp
index 9c2e1b1129..8c42c4a027 100644
--- a/Code/Legacy/CrySystem/System.cpp
+++ b/Code/Legacy/CrySystem/System.cpp
@@ -1148,7 +1148,7 @@ void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int
     if (sModuleFilter && *sModuleFilter != 0)
     {
         const char* sModule = ValidatorModuleToString(module);
-        if (strlen(sModule) > 1 || CryStringUtils::stristr(sModule, sModuleFilter) == 0)
+        if (strlen(sModule) > 1 || AZ::StringFunc::Find(sModule, sModuleFilter) == AZStd::string::npos)
         {
             // Filter out warnings from other modules.
             return;
@@ -1215,13 +1215,13 @@ void CSystem::GetLocalizedPath(const char* sLanguage, AZStd::string& sLocalizedP
     }
     else
     {
-    if (sLocalizationFolder.compareNoCase("Languages") != 0)
-    {
-        sLocalizedPath = sLocalizationFolder + "/" + sLanguage + "_xml.pak";
-    }
-    else
-    {
-        sLocalizedPath = AZStd::string("Localized/") + sLanguage + "_xml.pak";
+        if (AZ::StringFunc::Equal(sLocalizationFolder, "Languages", false))
+        {
+            sLocalizedPath = sLocalizationFolder + "/" + sLanguage + "_xml.pak";
+        }
+        else
+        {
+            sLocalizedPath = AZStd::string("Localized/") + sLanguage + "_xml.pak";
         }
     }
 }
@@ -1233,7 +1233,7 @@ void CSystem::GetLocalizedAudioPath(const char* sLanguage, AZStd::string& sLocal
     AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
     sLocalizationFolder.pop_back();
 
-    if (sLocalizationFolder.compareNoCase("Languages") != 0)
+    if (AZ::StringFunc::Equal(sLocalizationFolder, "Languages", false))
     {
         sLocalizedPath = sLocalizationFolder + "/" + sLanguage + ".pak";
     }
diff --git a/Code/Legacy/CrySystem/SystemCFG.cpp b/Code/Legacy/CrySystem/SystemCFG.cpp
index 062713c015..4d193c72a5 100644
--- a/Code/Legacy/CrySystem/SystemCFG.cpp
+++ b/Code/Legacy/CrySystem/SystemCFG.cpp
@@ -114,20 +114,22 @@ void CSystem::QueryVersionInfo()
 
     char ver[1024 * 8];
 
-    GetModuleFileName(NULL, moduleName, _MAX_PATH);  //retrieves the PATH for the current module
+    AZ::Utils::GetExecutablePath(moduleName, _MAX_PATH);  //retrieves the PATH for the current module
 
 #ifdef AZ_MONOLITHIC_BUILD
-    GetModuleFileName(NULL, moduleName, _MAX_PATH);  //retrieves the PATH for the current module
+    AZ::Utils::GetExecutablePath(moduleName, _MAX_PATH);  //retrieves the PATH for the current module
 #else // AZ_MONOLITHIC_BUILD
     azstrcpy(moduleName, AZ_ARRAY_SIZE(moduleName), "CrySystem.dll"); // we want to version from the system dll
 #endif // AZ_MONOLITHIC_BUILD
 
-    int verSize = GetFileVersionInfoSize(moduleName, &dwHandle);
+    AZStd::wstring moduleNameW;
+    AZStd::to_wstring(moduleNameW, moduleName);
+    int verSize = GetFileVersionInfoSizeW(moduleNameW.c_str(), &dwHandle);
     if (verSize > 0)
     {
-        GetFileVersionInfo(moduleName, dwHandle, 1024 * 8, ver);
+        GetFileVersionInfoW(moduleNameW.c_str(), dwHandle, 1024 * 8, ver);
         VS_FIXEDFILEINFO* vinfo;
-        VerQueryValue(ver, "\\", (void**)&vinfo, &len);
+        VerQueryValueW(ver, L"\\", (void**)&vinfo, &len);
 
         const uint32 verIndices[4] = {0, 1, 2, 3};
         m_fileVersion.v[verIndices[0]] = m_productVersion.v[verIndices[0]] = vinfo->dwFileVersionLS & 0xFFFF;
@@ -143,14 +145,14 @@ void CSystem::QueryVersionInfo()
         }* lpTranslate;
 
         UINT count = 0;
-        char path[256];
+        wchar_t path[256];
         char* version = NULL;
 
-        VerQueryValue(ver, "\\VarFileInfo\\Translation", (LPVOID*)&lpTranslate, &count);
+        VerQueryValueW(ver, L"\\VarFileInfo\\Translation", (LPVOID*)&lpTranslate, &count);
         if (lpTranslate != NULL)
         {
-            azsnprintf(path, sizeof(path), "\\StringFileInfo\\%04x%04x\\InternalName", lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
-            VerQueryValue(ver, path, (LPVOID*)&version, &count);
+            azsnwprintf(path, sizeof(path), L"\\StringFileInfo\\%04x%04x\\InternalName", lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
+            VerQueryValueW(ver, path, (LPVOID*)&version, &count);
             if (version)
             {
                 m_buildVersion.Set(version);
@@ -211,7 +213,7 @@ void CSystem::LogVersion()
     CryLogAlways("Running 64 bit Mac version");
 #endif
 #if AZ_LEGACY_CRYSYSTEM_TRAIT_SYSTEMCFG_MODULENAME
-    GetModuleFileName(NULL, s, sizeof(s));
+    AZ::Utils::GetExecutablePath(s, sizeof(s));
 
     // Log EXE filename only if possible (not full EXE path which could contain sensitive info)
     AZStd::string exeName;
@@ -448,25 +450,24 @@ bool CSystemConfiguration::ParseSystemConfig()
         }
 
         AZStd::string strLine = s;
+        AZ::StringFunc::TrimWhiteSpace(strLine, true, true);
 
         // detect groups e.g. "[General]"   should set strGroup="General"
         {
-            AZStd::string strTrimmedLine(RemoveWhiteSpaces(strLine));
-            size_t size = strTrimmedLine.size();
+            size_t size = strLine.size();
 
             if (size >= 3)
             {
-                if (strTrimmedLine[0] == '[' && strTrimmedLine[size - 1] == ']')       // currently no comments are allowed to be behind groups
+                if (strLine[0] == '[' && strLine[size - 1] == ']')  // currently no comments are allowed to be behind groups
                 {
-                    strGroup = &strTrimmedLine[1];
-                    strGroup.resize(size - 2);                                  // remove [ and ]
+                    strGroup = &strLine[1];
+                    strGroup.resize(size - 2);                      // remove [ and ]
                     continue;                                       // next line
                 }
             }
         }
 
         //trim all whitespace characters at the beginning and the end of the current line and store its size
-        AZ::StringFunc::TrimWhiteSpace(strLine, true, true);
         size_t strLineSize = strLine.size();
 
         //skip comments, comments start with ";" or "--" but may have preceding whitespace characters
@@ -491,8 +492,9 @@ bool CSystemConfiguration::ParseSystemConfig()
         AZStd::string::size_type posEq(strLine.find("=", 0));
         if (AZStd::string::npos != posEq)
         {
-            AZStd::string stemp(strLine, 0, posEq);
-            AZStd::string strKey(RemoveWhiteSpaces(stemp));
+            AZStd::string stemp;
+            AZStd::string strKey(strLine, 0, posEq);
+            AZ::StringFunc::TrimWhiteSpace(strKey, true, true);
 
             {
                 // extract value
@@ -507,8 +509,8 @@ bool CSystemConfiguration::ParseSystemConfig()
                 }
                 else
                 {
-                    AZStd::string strTmp(strLine, posEq + 1, strLine.size() - (posEq + 1));
-                    strValue = RemoveWhiteSpaces(strTmp);
+                    strValue = AZStd::string(strLine, posEq + 1, strLine.size() - (posEq + 1));
+                    AZ::StringFunc::TrimWhiteSpace(strValue, true, true);
                 }
 
                 {
diff --git a/Code/Legacy/CrySystem/SystemCFG.h b/Code/Legacy/CrySystem/SystemCFG.h
index cfaefd2e45..7ec6f1231b 100644
--- a/Code/Legacy/CrySystem/SystemCFG.h
+++ b/Code/Legacy/CrySystem/SystemCFG.h
@@ -25,12 +25,6 @@ public:
     CSystemConfiguration(const AZStd::string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing = true);
     ~CSystemConfiguration();
 
-    AZStd::string RemoveWhiteSpaces(AZStd::string& s)
-    {
-        s.Trim();
-        return s;
-    }
-
     bool IsError() const { return m_bError; }
 
 private: // ----------------------------------------
diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp
index ae177a9974..0c1411e649 100644
--- a/Code/Legacy/CrySystem/SystemInit.cpp
+++ b/Code/Legacy/CrySystem/SystemInit.cpp
@@ -451,7 +451,7 @@ AZStd::unique_ptr CSystem::LoadDLL(const char* dllName)
     //////////////////////////////////////////////////////////////////////////
     // After loading DLL initialize it by calling ModuleInitISystem
     //////////////////////////////////////////////////////////////////////////
-    string moduleName = PathUtil::GetFileName(dllName);
+    AZStd::string moduleName = PathUtil::GetFileName(dllName);
 
     typedef void*(*PtrFunc_ModuleInitISystem)(ISystem* pSystem, const char* moduleName);
     PtrFunc_ModuleInitISystem pfnModuleInitISystem = handle->GetFunction(DLL_MODULE_INIT_ISYSTEM);
@@ -523,7 +523,7 @@ void CSystem::ShutdownModuleLibraries()
 /////////////////////////////////////////////////////////////////////////////////
 
 #if defined(WIN32) || defined(WIN64)
-wstring GetErrorStringUnsupportedGPU(const char* gpuName, unsigned int gpuVendorId, unsigned int gpuDeviceId)
+AZStd::wstring GetErrorStringUnsupportedGPU(const char* gpuName, unsigned int gpuVendorId, unsigned int gpuDeviceId)
 {
     const size_t fullLangID = (size_t) GetKeyboardLayout(0);
     const size_t primLangID = fullLangID & 0x3FF;
@@ -877,19 +877,19 @@ void CSystem::InitLocalization()
         languageID = ILocalizationManager::EPlatformIndependentLanguageID::ePILID_English_US;
     }
 
-    string language = m_pLocalizationManager->LangNameFromPILID(languageID);
+    AZStd::string language = m_pLocalizationManager->LangNameFromPILID(languageID);
     m_pLocalizationManager->SetLanguage(language.c_str());
     if (m_pLocalizationManager->GetLocalizationFormat() == 1)
     {
-        string translationsListXML = LOCALIZATION_TRANSLATIONS_LIST_FILE_NAME;
-        m_pLocalizationManager->InitLocalizationData(translationsListXML);
+        AZStd::string translationsListXML = LOCALIZATION_TRANSLATIONS_LIST_FILE_NAME;
+        m_pLocalizationManager->InitLocalizationData(translationsListXML.c_str());
 
         m_pLocalizationManager->LoadAllLocalizationData();
     }
     else
     {
         // if the language value cannot be found, let's default to the english pak
-        OpenLanguagePak(language);
+        OpenLanguagePak(language.c_str());
     }
 
     if (auto console = AZ::Interface::Get(); console != nullptr)
@@ -907,7 +907,7 @@ void CSystem::InitLocalization()
             }
         }
     }
-    OpenLanguageAudioPak(language);
+    OpenLanguageAudioPak(language.c_str());
 }
 
 void CSystem::OpenBasicPaks()
@@ -971,10 +971,10 @@ void CSystem::OpenLanguagePak(const char* sLanguage)
     // Initialize languages.
 
     // Omit the trailing slash!
-    string sLocalizationFolder = PathUtil::GetLocalizationFolder();
+    AZStd::string sLocalizationFolder = PathUtil::GetLocalizationFolder();
 
     // load xml pak with full filenames to perform wildcard searches.
-    string sLocalizedPath;
+    AZStd::string sLocalizedPath;
     GetLocalizedPath(sLanguage, sLocalizedPath);
     if (!m_env.pCryPak->OpenPacks({ sLocalizationFolder.c_str(), sLocalizationFolder.size() }, { sLocalizedPath.c_str(), sLocalizedPath.size() }, 0))
     {
@@ -1001,15 +1001,15 @@ void CSystem::OpenLanguageAudioPak([[maybe_unused]] const char* sLanguage)
     int nPakFlags = 0;
 
     // Omit the trailing slash!
-    string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
+    AZStd::string sLocalizationFolder(AZStd::string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
 
-    if (sLocalizationFolder.compareNoCase("Languages") == 0)
+    if (!AZ::StringFunc::Equal(sLocalizationFolder, "Languages", false))
     {
         sLocalizationFolder = "@assets@";
     }
 
     // load localized pak with crc32 filenames on consoles to save memory.
-    string sLocalizedPath = "loc.pak";
+    AZStd::string sLocalizedPath = "loc.pak";
 
     if (!m_env.pCryPak->OpenPacks(sLocalizationFolder.c_str(), sLocalizedPath.c_str(), nPakFlags))
     {
@@ -1019,10 +1019,10 @@ void CSystem::OpenLanguageAudioPak([[maybe_unused]] const char* sLanguage)
 }
 
 
-string GetUniqueLogFileName(string logFileName)
+AZStd::string GetUniqueLogFileName(AZStd::string logFileName)
 {
-    string logFileNamePrefix = logFileName;
-    if ((logFileNamePrefix[0] != '@') && (AzFramework::StringFunc::Path::IsRelative(logFileNamePrefix)))
+    AZStd::string logFileNamePrefix = logFileName;
+    if ((logFileNamePrefix[0] != '@') && (AzFramework::StringFunc::Path::IsRelative(logFileNamePrefix.c_str())))
     {
         logFileNamePrefix = "@log@/";
         logFileNamePrefix += logFileName;
@@ -1038,9 +1038,9 @@ string GetUniqueLogFileName(string logFileName)
         return logFileNamePrefix;
     }
 
-    string logFileExtension;
+    AZStd::string logFileExtension;
     size_t extensionIndex = logFileName.find_last_of('.');
-    if (extensionIndex != string::npos)
+    if (extensionIndex != AZStd::string::npos)
     {
         logFileExtension = logFileName.substr(extensionIndex, logFileName.length() - extensionIndex);
         logFileNamePrefix = logFileName.substr(0, extensionIndex);
@@ -1214,7 +1214,7 @@ bool CSystem::Init(const SSystemInitParams& startupParams)
 
         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
 AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option")
-        GetVersionExA(&osvi);
+        GetVersionExW(&osvi);
 AZ_POP_DISABLE_WARNING
 
         bool bIsWindowsXPorLater = osvi.dwMajorVersion > 5 || (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion >= 1);
@@ -1309,7 +1309,7 @@ AZ_POP_DISABLE_WARNING
             }
             else if (startupParams.sLogFileName)    //otherwise see if the startup params has a log file name, if so use it
             {
-                const string sUniqueLogFileName = GetUniqueLogFileName(startupParams.sLogFileName);
+                const AZStd::string sUniqueLogFileName = GetUniqueLogFileName(startupParams.sLogFileName);
                 m_env.pLog->SetFileName(sUniqueLogFileName.c_str(), startupParams.autoBackupLogs);
             }
             else//use the default log name
@@ -1657,20 +1657,20 @@ static void LoadConfigurationCmd(IConsoleCmdArgs* pParams)
         return;
     }
 
-    GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1));
+    GetISystem()->LoadConfiguration((AZStd::string("Config/") + pParams->GetArg(1)).c_str());
 }
 
 
 // --------------------------------------------------------------------------------------------------------------------------
 
-static string ConcatPath(const char* szPart1, const char* szPart2)
+static AZStd::string ConcatPath(const char* szPart1, const char* szPart2)
 {
     if (szPart1[0] == 0)
     {
         return szPart2;
     }
 
-    string ret;
+    AZStd::string ret;
 
     ret.reserve(strlen(szPart1) + 1 + strlen(szPart2));
 
@@ -2134,12 +2134,12 @@ void CSystem::CreateAudioVars()
 }
 
 /////////////////////////////////////////////////////////////////////
-void CSystem::AddCVarGroupDirectory(const string& sPath)
+void CSystem::AddCVarGroupDirectory(const AZStd::string& sPath)
 {
     CryLog("creating CVarGroups from directory '%s' ...", sPath.c_str());
     INDENT_LOG_DURING_SCOPE();
 
-    AZ::IO::ArchiveFileIterator handle = gEnv->pCryPak->FindFirst(ConcatPath(sPath, "*.cfg").c_str());
+    AZ::IO::ArchiveFileIterator handle = gEnv->pCryPak->FindFirst(ConcatPath(sPath.c_str(), "*.cfg").c_str());
 
     if (!handle)
     {
@@ -2152,16 +2152,9 @@ void CSystem::AddCVarGroupDirectory(const string& sPath)
         {
             if (handle.m_filename != "." && handle.m_filename != "..")
             {
-                AddCVarGroupDirectory(ConcatPath(sPath, handle.m_filename.data()));
+                AddCVarGroupDirectory(ConcatPath(sPath.c_str(), handle.m_filename.data()));
             }
         }
-        else
-        {
-            string sFilePath = ConcatPath(sPath, handle.m_filename.data());
-
-            string sCVarName = sFilePath;
-            PathUtil::RemoveExtension(sCVarName);
-        }
     } while (handle = gEnv->pCryPak->FindNext(handle));
 
     gEnv->pCryPak->FindClose(handle);
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index a4be0e5054..9fd01f1905 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -15,7 +15,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include  // for AZ_MAX_PATH_LEN
 #include 
@@ -127,7 +126,7 @@ const char* CSystem::GetUserName()
     DWORD dwSize = iNameBufferSize;
     wchar_t nameW[iNameBufferSize];
     ::GetUserNameW(nameW, &dwSize);
-    azstrcpy(szNameBuffer, CryStringUtils::WStrToUTF8(nameW));
+    AZStd::to_string(szNameBuffer, iNameBufferSize, nameW, dwSize);
     return szNameBuffer;
 #else
 #if defined(LINUX)
@@ -171,12 +170,12 @@ int CSystem::GetApplicationInstance()
     // this code below essentially "locks" an instance of the USER folder to a specific running application
     if (m_iApplicationInstance == -1)
     {
-        string suffix;
+        AZStd::wstring suffix;
         for (int instance = 0;; ++instance)
         {
-            suffix.Format("(%d)", instance);
+            suffix = AZStd::wstring::format(L"LumberyardApplication(%d)", instance);
 
-            CreateMutex(NULL, TRUE, "LumberyardApplication" + suffix);
+            CreateMutexW(NULL, TRUE, suffix.c_str());
             // search for duplicates
             if (GetLastError() != ERROR_ALREADY_EXISTS)
             {
@@ -195,13 +194,13 @@ int CSystem::GetApplicationInstance()
 int CSystem::GetApplicationLogInstance([[maybe_unused]] const char* logFilePath)
 {
 #if AZ_TRAIT_OS_USE_WINDOWS_MUTEX
-    string suffix;
+    AZStd::wstring suffix;
     int instance = 0;
     for (;; ++instance)
     {
-        suffix.Format("(%d)", instance);
+        suffix = AZStd::wstring::format(L"%s(%d)", logFilePath, instance);
 
-        CreateMutex(NULL, TRUE, logFilePath + suffix);
+        CreateMutexW(NULL, TRUE, suffix.c_str());
         if (GetLastError() != ERROR_ALREADY_EXISTS)
         {
             break;
@@ -218,7 +217,7 @@ struct CryDbgModule
 {
     HANDLE heap;
     WIN_HMODULE handle;
-    string name;
+    AZStd::string name;
     DWORD dwSize;
 };
 
@@ -343,12 +342,15 @@ void CSystem::FatalError(const char* format, ...)
     assert(szBuffer[0] >= ' ');
     //  strcpy(szBuffer,szBuffer+1);    // remove verbosity tag since it is not supported by ::MessageBox
 
-    OutputDebugString(szBuffer);
+    AZ::Debug::Platform::OutputToDebugger("CrySystem", szBuffer);
+
 #ifdef WIN32
     OnFatalError(szBuffer);
     if (!g_cvars.sys_no_crash_dialog)
     {
-        ::MessageBox(NULL, szBuffer, "Open 3D Engine Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
+        AZStd::wstring szBufferW;
+        AZStd::to_wstring(szBufferW, szBuffer);
+        ::MessageBoxW(NULL, szBufferW.c_str(), L"Open 3D Engine Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
     }
 
     // Dump callstack.
@@ -461,20 +463,20 @@ bool CSystem::ReLaunchMediaCenter()
     }
 
     // Get the path to Media Center
-    char szExpandedPath[AZ_MAX_PATH_LEN];
-    if (!ExpandEnvironmentStrings("%SystemRoot%\\ehome\\ehshell.exe", szExpandedPath, AZ_MAX_PATH_LEN))
+    wchar_t szExpandedPath[AZ_MAX_PATH_LEN];
+    if (!ExpandEnvironmentStringsW(L"%SystemRoot%\\ehome\\ehshell.exe", szExpandedPath, AZ_MAX_PATH_LEN))
     {
         return false;
     }
 
     // Skip if ehshell.exe doesn't exist
-    if (GetFileAttributes(szExpandedPath) == 0xFFFFFFFF)
+    if (GetFileAttributesW(szExpandedPath) == 0xFFFFFFFF)
     {
         return false;
     }
 
     // Launch ehshell.exe
-    INT_PTR result = (INT_PTR)ShellExecute(NULL, TEXT("open"), szExpandedPath, NULL, NULL, SW_SHOWNORMAL);
+    INT_PTR result = (INT_PTR)ShellExecuteW(NULL, TEXT("open"), szExpandedPath, NULL, NULL, SW_SHOWNORMAL);
     return (result > 32);
 }
 #else
@@ -491,7 +493,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
     bool bSucceeded  = false;
     // check Vista and later OS first
 
-    HMODULE shell32 = LoadLibraryA("Shell32.dll");
+    HMODULE shell32 = LoadLibraryW(L"Shell32.dll");
     if (shell32)
     {
         typedef long (__stdcall * T_SHGetKnownFolderPath)(REFKNOWNFOLDERID rfid, unsigned long dwFlags, void* hToken, wchar_t** ppszPath);
@@ -505,7 +507,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
             if (bSucceeded)
             {
                 // Convert from UNICODE to UTF-8
-                azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
+                AZStd::to_string(szMyDocumentsPath, maxPathSize, wMyDocumentsPath);
                 CoTaskMemFree(wMyDocumentsPath);
             }
         }
@@ -519,7 +521,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
         bSucceeded = SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, wMyDocumentsPath));
         if (bSucceeded)
         {
-            azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
+            AZStd::to_string(szMyDocumentsPath, maxPathSize, wMyDocumentsPath);
         }
     }
 
@@ -547,7 +549,7 @@ void CSystem::DetectGameFolderAccessRights()
     BOOL bAccessStatus = FALSE;
 
     // Get a pointer to the existing DACL.
-    dwRes = GetNamedSecurityInfo(".", SE_FILE_OBJECT,
+    dwRes = GetNamedSecurityInfoW(L".", SE_FILE_OBJECT,
             DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION,
             NULL, NULL, &pDACL, NULL, &pSD);
 
diff --git a/Code/Legacy/CrySystem/WindowsErrorReporting.cpp b/Code/Legacy/CrySystem/WindowsErrorReporting.cpp
index a02f55b69e..d467923c74 100644
--- a/Code/Legacy/CrySystem/WindowsErrorReporting.cpp
+++ b/Code/Legacy/CrySystem/WindowsErrorReporting.cpp
@@ -66,7 +66,9 @@ LONG WINAPI CryEngineExceptionFilterMiniDump(struct _EXCEPTION_POINTERS* pExcept
         return EXCEPTION_CONTINUE_SEARCH;
     }
 
-    HANDLE hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+    AZStd::wstring szDumpPathW;
+    AZStd::to_wstring(szDumpPathW, szDumpPath);
+    HANDLE hFile = ::CreateFileW(szDumpPathW.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
     if (hFile == INVALID_HANDLE_VALUE)
     {
         CryLogAlways("Failed to record DMP file: could not open file '%s' for writing - error code: %d", szDumpPath, GetLastError());
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index a69d86e8b7..f5e946be43 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -15,9 +15,6 @@
 #include "XConsoleVariable.h"
 #include "System.h"
 #include "ConsoleBatchFile.h"
-#include "StringUtils.h"
-#include "UnicodeFunctions.h"
-#include "UnicodeIterator.h"
 
 #include 
 #include 
@@ -88,11 +85,13 @@ inline int GetCharPrio(char x)
     }
 }
 // case sensitive
-inline bool less_CVar(const char* left, const char* right)
+inline bool less_CVar(const AZStd::string& left, const AZStd::string& right)
 {
+    AZStd::string_view leftView(left);
+    AZStd::string_view rightView(right);
     for (;; )
     {
-        uint32 l = GetCharPrio(*left), r = GetCharPrio(*right);
+        uint32 l = GetCharPrio(leftView.front()), r = GetCharPrio(rightView.front());
 
         if (l < r)
         {
@@ -103,13 +102,13 @@ inline bool less_CVar(const char* left, const char* right)
             return false;
         }
 
-        if (*left == 0 || *right == 0)
+        if (leftView.front() == 0 || rightView.front() == 0)
         {
             break;
         }
 
-        ++left;
-        ++right;
+        leftView.remove_prefix(1);
+        rightView.remove_prefix(1);
     }
 
     return false;
@@ -149,7 +148,7 @@ void Bind(IConsoleCmdArgs* cmdArgs)
 {
     if (cmdArgs->GetArgCount() >= 3)
     {
-        string arg;
+        AZStd::string arg;
         for (int i = 2; i < cmdArgs->GetArgCount(); ++i)
         {
             arg += cmdArgs->GetArg(i);
@@ -414,9 +413,7 @@ void CXConsole::Init(ISystem* pSystem)
 void CXConsole::LogChangeMessage(const char* name, const bool isConst, const bool isCheat, const bool isReadOnly, const bool isDeprecated,
     const char* oldValue, const char* newValue, [[maybe_unused]] const bool isProcessingGroup, const bool allowChange)
 {
-    string logMessage;
-
-    logMessage.Format
+    AZStd::string logMessage = AZStd::string::format
         ("[CVARS]: [%s] variable [%s] from [%s] to [%s]%s; Marked as%s%s%s%s",
         (allowChange) ? "CHANGED" : "IGNORED CHANGE",
         name,
@@ -452,7 +449,7 @@ void CXConsole::RegisterVar(ICVar* pCVar, ConsoleVarFunc pChangeFunc)
     bool isReadOnly = ((pCVar->GetFlags() & VF_READONLY) != 0);
     bool isDeprecated = ((pCVar->GetFlags() & VF_DEPRECATED) != 0);
 
-    ConfigVars::iterator it = m_configVars.find(CONST_TEMP_STRING(pCVar->GetName()));
+    ConfigVars::iterator it = m_configVars.find(pCVar->GetName());
     if (it != m_configVars.end())
     {
         SConfigVar& var = it->second;
@@ -906,7 +903,7 @@ void CXConsole::DumpKeyBinds(IKeyBindDumpSink* pCallback)
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 const char* CXConsole::FindKeyBind(const char* sCmd) const
 {
-    ConsoleBindsMap::const_iterator it = m_mapBinds.find(CONST_TEMP_STRING(sCmd));
+    ConsoleBindsMap::const_iterator it = m_mapBinds.find(sCmd);
 
     if (it != m_mapBinds.end())
     {
@@ -1263,9 +1260,7 @@ bool CXConsole::ProcessInput(const AzFramework::InputChannel& inputChannel)
         if (m_nCursorPos)
         {
             const char* pCursor = m_sInputBuffer.c_str() + m_nCursorPos;
-            Unicode::CIterator pUnicode(pCursor);
-            --pUnicode; // Note: This moves back one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
-            pCursor = pUnicode.GetPosition();
+            pCursor -= Utf8::Internal::sequence_length(pCursor); // Note: This moves back one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
             m_nCursorPos = pCursor - m_sInputBuffer.c_str();
         }
         return true;
@@ -1275,9 +1270,7 @@ bool CXConsole::ProcessInput(const AzFramework::InputChannel& inputChannel)
         if (m_nCursorPos < (int)(m_sInputBuffer.length()))
         {
             const char* pCursor = m_sInputBuffer.c_str() + m_nCursorPos;
-            Unicode::CIterator pUnicode(pCursor);
-            ++pUnicode; // Note: This moves forward one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
-            pCursor = pUnicode.GetPosition();
+            pCursor += Utf8::Internal::sequence_length(pCursor); // Note: This moves forward one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
             m_nCursorPos = pCursor - m_sInputBuffer.c_str();
         }
         return true;
@@ -1446,7 +1439,7 @@ bool CXConsole::GetLineNo(const int indwLineNo, char* outszBuffer, const int ind
     {
         buf++;                          // to jump over verbosity level character
     }
-    cry_strcpy(outszBuffer, indwBufferSize, buf);
+    azstrcpy(outszBuffer, indwBufferSize, buf);
 
     return true;
 }
@@ -1558,27 +1551,27 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags)
 
     if (dwFlags & VF_READONLY)
     {
-        cry_strcat(sFlags, "READONLY, ");
+        azstrcat(sFlags, "READONLY, ");
     }
     if (dwFlags & VF_DEPRECATED)
     {
-        cry_strcat(sFlags, "DEPRECATED, ");
+        azstrcat(sFlags, "DEPRECATED, ");
     }
     if (dwFlags & VF_DUMPTODISK)
     {
-        cry_strcat(sFlags, "DUMPTODISK, ");
+        azstrcat(sFlags, "DUMPTODISK, ");
     }
     if (dwFlags & VF_REQUIRE_LEVEL_RELOAD)
     {
-        cry_strcat(sFlags, "REQUIRE_LEVEL_RELOAD, ");
+        azstrcat(sFlags, "REQUIRE_LEVEL_RELOAD, ");
     }
     if (dwFlags & VF_REQUIRE_APP_RESTART)
     {
-        cry_strcat(sFlags, "REQUIRE_APP_RESTART, ");
+        azstrcat(sFlags, "REQUIRE_APP_RESTART, ");
     }
     if (dwFlags & VF_RESTRICTEDMODE)
     {
-        cry_strcat(sFlags, "RESTRICTEDMODE, ");
+        azstrcat(sFlags, "RESTRICTEDMODE, ");
     }
 
     if (sFlags[0] != 0)
@@ -1794,7 +1787,7 @@ void CXConsole::DisplayHelp(const char* help, const char* name)
         char* start, * pos;
         for (pos = strstr((char*)help, "\n"), start = (char*)help; pos; start = ++pos)
         {
-            string s = start;
+            AZStd::string s = start;
             s.resize(pos - start);
             ConsoleLogInputResponse("    $3%s", s.c_str());
             pos = strstr(pos, "\n");
@@ -1816,11 +1809,12 @@ void CXConsole::ExecuteString(const char* command, const bool bSilentMode, const
 
     // Store the string commands into a list and defer the execution for later.
     // The commands will be processed in CXConsole::Update()
-    string str(command);
-    str.TrimLeft();
+    AZStd::string str(command);
+    AZ::StringFunc::TrimWhiteSpace(str, true, false);
 
     // Unroll the exec command
-    bool unroll = (0 == str.Left(strlen("exec")).compareNoCase("exec"));
+    
+    bool unroll = (0 == AZ::StringFunc::Find(str, "exec", 0, false, false));
 
     if (unroll)
     {
@@ -1858,10 +1852,10 @@ void CXConsole::ResetCVarsToDefaults()
 
 }
 
-void CXConsole::SplitCommands(const char* line, std::list& split)
+void CXConsole::SplitCommands(const char* line, std::list& split)
 {
     const char* start = line;
-    string working;
+    AZStd::string working;
 
     while (true)
     {
@@ -1881,7 +1875,7 @@ void CXConsole::SplitCommands(const char* line, std::list& split)
         case '\0':
         {
             working.assign(start, line - 1);
-            working.Trim();
+            AZ::StringFunc::TrimWhiteSpace(working, true, true);
 
             if (!working.empty())
             {
@@ -1931,15 +1925,15 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
     ConsoleCommandsMapItor itrCmd;
     ConsoleVariablesMapItor itrVar;
 
-    std::list lineCommands;
+    std::list lineCommands;
     SplitCommands(command, lineCommands);
 
-    string sTemp;
-    string sCommand, sLineCommand;
+    AZStd::string sTemp;
+    AZStd::string sCommand, sLineCommand;
 
     while (!lineCommands.empty())
     {
-        string::size_type nPos;
+        AZStd::string::size_type nPos;
 
         {
             sTemp = lineCommands.front();
@@ -1951,17 +1945,17 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
             {
                 if (GetStatus())
                 {
-                    AddLine(sTemp);
+                    AddLine(sTemp.c_str());
                 }
             }
 
             nPos = sTemp.find_first_of('=');
 
-            if (nPos != string::npos)
+            if (nPos != AZStd::string::npos)
             {
                 sCommand = sTemp.substr(0, nPos);
             }
-            else if ((nPos = sTemp.find_first_of(' ')) != string::npos)
+            else if ((nPos = sTemp.find_first_of(' ')) != AZStd::string::npos)
             {
                 sCommand = sTemp.substr(0, nPos);
             }
@@ -1970,7 +1964,7 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
                 sCommand = sTemp;
             }
 
-            sCommand.Trim();
+            AZ::StringFunc::TrimWhiteSpace(sCommand, true, true);
 
             //////////////////////////////////////////
             // Search for CVars
@@ -2005,7 +1999,7 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
 
         //////////////////////////////////////////
         //Check  if is a variable
-        itrVar = m_mapVariables.find(sCommand);
+        itrVar = m_mapVariables.find(sCommand.c_str());
         if (itrVar != m_mapVariables.end())
         {
             ICVar* pCVar = itrVar->second;
@@ -2017,10 +2011,10 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
                     m_blockCounter++;
                 }
 
-                if (nPos != string::npos)
+                if (nPos != AZStd::string::npos)
                 {
                     sTemp = sTemp.substr(nPos + 1);     // remove the command from sTemp
-                    sTemp.Trim(" \t\r\n\"\'");
+                    AZ::StringFunc::StripEnds(sTemp, " \t\r\n\"\'");
 
                     if (sTemp == "?")
                     {
@@ -2094,12 +2088,12 @@ void CXConsole::ExecuteDeferredCommands()
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDevMode)
+void CXConsole::ExecuteCommand(CConsoleCommand& cmd, AZStd::string& str, bool bIgnoreDevMode)
 {
     CryLog ("[CONSOLE] Executing console command '%s'", str.c_str());
     INDENT_LOG_DURING_SCOPE();
 
-    std::vector args;
+    std::vector args;
     size_t t;
 
     {
@@ -2118,7 +2112,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
                 {
                     ;
                 }
-                args.push_back(string(start + 1, commandLine - 1));
+                args.push_back(AZStd::string(start + 1, commandLine - 1));
                 start = commandLine;
                 break;
             }
@@ -2129,7 +2123,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
             {
                 if ((*commandLine == ' ') || !*commandLine)
                 {
-                    args.push_back(string(start, commandLine));
+                    args.push_back(AZStd::string(start, commandLine));
                     start = commandLine + 1;
                 }
             }
@@ -2139,7 +2133,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
 
         if (args.size() >= 2 && args[1] == "?")
         {
-            DisplayHelp(cmd.m_sHelp, cmd.m_sName.c_str());
+            DisplayHelp(cmd.m_sHelp.c_str(), cmd.m_sName.c_str());
             return;
         }
 
@@ -2166,13 +2160,13 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
         return;
     }
 
-    string buf;
+    AZStd::string buf;
     {
         // only do this for commands with script implementation
         for (;; )
         {
             t = str.find_first_of("\\", t);
-            if (t == string::npos)
+            if (t == AZStd::string::npos)
             {
                 break;
             }
@@ -2183,7 +2177,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
         for (t = 1;; )
         {
             t = str.find_first_of("\"", t);
-            if (t == string::npos)
+            if (t == AZStd::string::npos)
             {
                 break;
             }
@@ -2194,9 +2188,9 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
         buf = cmd.m_sCommand;
 
         size_t pp = buf.find("%%");
-        if (pp != string::npos)
+        if (pp != AZStd::string::npos)
         {
-            string list = "";
+            AZStd::string list = "";
             for (unsigned int i = 1; i < args.size(); i++)
             {
                 list += "\"" + args[i] + "\"";
@@ -2207,9 +2201,9 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
             }
             buf.replace(pp, 2, list);
         }
-        else if ((pp = buf.find("%line")) != string::npos)
+        else if ((pp = buf.find("%line")) != AZStd::string::npos)
         {
-            string tmp = "\"" + str.substr(str.find(" ") + 1) + "\"";
+            AZStd::string tmp = "\"" + str.substr(str.find(" ") + 1) + "\"";
             if (args.size() > 1)
             {
                 buf.replace(pp, 5, tmp);
@@ -2226,7 +2220,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
                 char pat[10];
                 azsprintf(pat, "%%%d", i);
                 size_t pos = buf.find(pat);
-                if (pos == string::npos)
+                if (pos == AZStd::string::npos)
                 {
                     if (i != args.size())
                     {
@@ -2241,7 +2235,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
                         ConsoleWarning("Not enough arguments for: %s", cmd.m_sName.c_str());
                         return;
                     }
-                    string arg = "\"" + args[i] + "\"";
+                    AZStd::string arg = "\"" + args[i] + "\"";
                     buf.replace(pos, strlen(pat), arg);
                 }
             }
@@ -2340,15 +2334,15 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
     }
     //try to search in command list
     bool bArgumentAutoComplete = false;
-    std::vector matches;
+    std::vector matches;
 
-    if (m_sPrevTab.find(' ') != string::npos)
+    if (m_sPrevTab.find(' ') != AZStd::string::npos)
     {
         bool bProcessAutoCompl = true;
 
         // Find command.
-        string sVar = m_sPrevTab.substr(0, m_sPrevTab.find(' '));
-        ICVar* pCVar = GetCVar(sVar);
+        AZStd::string sVar = m_sPrevTab.substr(0, m_sPrevTab.find(' '));
+        ICVar* pCVar = GetCVar(sVar.c_str());
         if (pCVar)
         {
             if (!(pCVar->GetFlags() & VF_RESTRICTEDMODE) && con_restricted)            // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
@@ -2376,7 +2370,7 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
                 int nMatches = pArgumentAutoComplete->GetCount();
                 for (int i = 0; i < nMatches; i++)
                 {
-                    string cmd = string(sVar) + " " + pArgumentAutoComplete->GetValue(i);
+                    AZStd::string cmd = AZStd::string(sVar) + " " + pArgumentAutoComplete->GetValue(i);
                     if (_strnicmp(m_sPrevTab.c_str(), cmd.c_str(), m_sPrevTab.length()) == 0)
                     {
                         {
@@ -2436,10 +2430,10 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
     {
         ConsoleLogInput(" ");       // empty line before auto completion
 
-        for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
+        for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
         {
             // List matching variables
-            const char* sVar = *i;
+            const char* sVar = i->c_str();
             ICVar* pVar = GetCVar(sVar);
 
             if (pVar)
@@ -2453,7 +2447,7 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
         }
     }
 
-    for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
+    for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
     {
         if (m_nTabCount <= nMatch)
         {
@@ -2485,8 +2479,8 @@ void CXConsole::DisplayVarValue(ICVar* pVar)
 
     const char* sFlagsString = GetFlagsString(pVar->GetFlags());
 
-    string sValue = (pVar->GetFlags() & VF_INVISIBLE) ? "" : pVar->GetString();
-    string sVar = pVar->GetName();
+    AZStd::string sValue = (pVar->GetFlags() & VF_INVISIBLE) ? "" : pVar->GetString();
+    AZStd::string sVar = pVar->GetName();
 
     char szRealState[40] = "";
 
@@ -2623,12 +2617,8 @@ void CXConsole::AddLine(const char* inputStr)
 
 void CXConsole::PostLine(const char* lineOfText, size_t len)
 {
-    string line;
-
-    {
-        line = string(lineOfText, len);
-        m_dqConsoleBuffer.push_back(line);
-    }
+    AZStd::string line = AZStd::string(lineOfText, len);
+    m_dqConsoleBuffer.push_back(line);
 
     int nBufferSize = con_line_buffer_size;
 
@@ -2701,7 +2691,7 @@ void CXConsole::RemoveOutputPrintSink(IOutputPrintSink* inpSink)
 //////////////////////////////////////////////////////////////////////////
 void CXConsole::AddLinePlus(const char* inputStr)
 {
-    string str, tmpStr;
+    AZStd::string str, tmpStr;
 
     {
         if (!m_dqConsoleBuffer.size())
@@ -2717,13 +2707,13 @@ void CXConsole::AddLinePlus(const char* inputStr)
             str.resize(str.size() - 1);
         }
 
-        string::size_type nPos;
-        while ((nPos = str.find('\n')) != string::npos)
+        AZStd::string::size_type nPos;
+        while ((nPos = str.find('\n')) != AZStd::string::npos)
         {
             str.replace(nPos, 1, 1, ' ');
         }
 
-        while ((nPos = str.find('\r')) != string::npos)
+        while ((nPos = str.find('\r')) != AZStd::string::npos)
         {
             str.replace(nPos, 1, 1, ' ');
         }
@@ -2783,7 +2773,7 @@ void CXConsole::AddInputUTF8(const AZStd::string& textUTF8)
 //////////////////////////////////////////////////////////////////////////
 void CXConsole::ExecuteInputBuffer()
 {
-    string sTemp = m_sInputBuffer;
+    AZStd::string sTemp = m_sInputBuffer;
     if (m_sInputBuffer.empty())
     {
         return;
@@ -2814,9 +2804,7 @@ void CXConsole::RemoveInputChar(bool bBackSpace)
             const char* const pBase = m_sInputBuffer.c_str();
             const char* pCursor = pBase + m_nCursorPos;
             const char* const pEnd = pCursor;
-            Unicode::CIterator pUnicode(pCursor);
-            pUnicode--; // Remove one UCS code-point, doesn't account for combining diacritics
-            pCursor = pUnicode.GetPosition();
+            pCursor -= Utf8::Internal::sequence_length(pCursor); // Remove one UCS code-point, doesn't account for combining diacritics
             size_t length = pEnd - pCursor;
             m_sInputBuffer.erase(pCursor - pBase, length);
             m_nCursorPos -= length;
@@ -2829,9 +2817,7 @@ void CXConsole::RemoveInputChar(bool bBackSpace)
             const char* const pBase = m_sInputBuffer.c_str();
             const char* pCursor = pBase + m_nCursorPos;
             const char* const pBegin = pCursor;
-            Unicode::CIterator pUnicode(pCursor);
-            pUnicode--; // Remove one UCS code-point, doesn't account for combining diacritics
-            pCursor = pUnicode.GetPosition();
+            pCursor -= Utf8::Internal::sequence_length(pCursor); // Remove one UCS code-point, doesn't account for combining diacritics
             size_t length = pCursor - pBegin;
             m_sInputBuffer.erase(pBegin - pBase, length);
         }
@@ -2905,28 +2891,29 @@ void CXConsole::Paste()
 #if defined(AZ_PLATFORM_WINDOWS)
     if (OpenClipboard(NULL) != 0)
     {
-        wstring data;
+        AZStd::string data;
         const HANDLE wideData = GetClipboardData(CF_UNICODETEXT);
         if (wideData)
         {
             const LPCWSTR pWideData = (LPCWSTR)GlobalLock(wideData);
             if (pWideData)
             {
-                // Note: This conversion is just to make sure we discard malicious or malformed data
-                Unicode::ConvertSafe(data, pWideData);
+                AZStd::to_string(data, pWideData);
                 GlobalUnlock(wideData);
             }
         }
         CloseClipboard();
 
-        for (Unicode::CIterator it(data.begin(), data.end()); it != data.end(); ++it)
+        Utf8::Unchecked::octet_iterator end(data.end());
+        for (Utf8::Unchecked::octet_iterator it(data.begin()); it != end; ++it)
         {
             const uint32 cp = *it;
             if (cp != '\r')
             {
                 // Convert UCS code-point into UTF-8 string
-                char utf8_buf[5];
-                Unicode::Convert(utf8_buf, cp);
+                char utf8_buf[5] = {0};
+                size_t size = 5;
+                it.to_utf8_sequence(cp, utf8_buf, size);
                 AddInputUTF8(utf8_buf);
             }
         }
@@ -3030,7 +3017,7 @@ void CXConsole::AddCVarsToHash(ConsoleVariablesVector::const_iterator begin, Con
     {
         // add name & variable to string. We add both since adding only the value could cause
         // many collisions with variables all having value 0 or all 1.
-        string hashStr = it->first;
+        AZStd::string hashStr = it->first;
 
         runningNameCrc32.Add(hashStr.c_str(), hashStr.length());
         hashStr += it->second->GetDataProbeString();
@@ -3281,7 +3268,7 @@ void CXConsole::FindVar(const char* substr)
 
     for (size_t i = 0; i < cmdCount; i++)
     {
-        if (CryStringUtils::stristr(cmds[i], substr))
+        if (AZ::StringFunc::Find(cmds[i], substr) != AZStd::string::npos)
         {
             ICVar* pCvar = gEnv->pConsole->GetCVar(cmds[i]);
             if (pCvar)
@@ -3399,7 +3386,7 @@ const char* CXConsole::AutoCompletePrev(const char* substr)
 }
 
 //////////////////////////////////////////////////////////////////////////
-inline size_t sizeOf (const string& str)
+inline size_t sizeOf (const AZStd::string& str)
 {
     return str.capacity() + 1;
 }
diff --git a/Code/Legacy/CrySystem/XConsole.h b/Code/Legacy/CrySystem/XConsole.h
index f09c8e5ad7..b141a88e52 100644
--- a/Code/Legacy/CrySystem/XConsole.h
+++ b/Code/Legacy/CrySystem/XConsole.h
@@ -95,26 +95,12 @@ private:
 
 struct string_nocase_lt
 {
-    bool operator()(const char* s1, const char* s2) const
+    bool operator()(const AZStd::string& s1, const AZStd::string& s2) const
     {
-        return azstricmp(s1, s2) < 0;
+        return azstricmp(s1.c_str(), s2.c_str()) < 0;
     }
 };
 
-/* - very dangerous to use with STL containers
-struct string_nocase_lt
-{
-    bool operator()( const char *s1,const char *s2 ) const
-    {
-        return _stricmp(s1,s2) < 0;
-    }
-    bool operator()( const string &s1,const string &s2 ) const
-    {
-        return _stricmp(s1.c_str(),s2.c_str()) < 0;
-    }
-};
-*/
-
 //forward declarations
 class ITexture;
 struct IRenderer;
diff --git a/Code/Legacy/CrySystem/XConsoleVariable.cpp b/Code/Legacy/CrySystem/XConsoleVariable.cpp
index 370931088f..ab6ed0b078 100644
--- a/Code/Legacy/CrySystem/XConsoleVariable.cpp
+++ b/Code/Legacy/CrySystem/XConsoleVariable.cpp
@@ -286,7 +286,7 @@ void CXConsoleVariableCVarGroup::OnLoadConfigurationEntry_End()
 {
     if (!m_sDefaultValue.empty())
     {
-        gEnv->pConsole->LoadConfigVar(GetName(), m_sDefaultValue);
+        gEnv->pConsole->LoadConfigVar(GetName(), m_sDefaultValue.c_str());
         m_sDefaultValue.clear();
     }
 }
@@ -299,9 +299,9 @@ CXConsoleVariableCVarGroup::CXConsoleVariableCVarGroup(CXConsole* pConsole, cons
 }
 
 
-string CXConsoleVariableCVarGroup::GetDetailedInfo() const
+AZStd::string CXConsoleVariableCVarGroup::GetDetailedInfo() const
 {
-    string sRet = GetName();
+    AZStd::string sRet = GetName();
 
     sRet += " [";
 
@@ -326,11 +326,11 @@ string CXConsoleVariableCVarGroup::GetDetailedInfo() const
     sRet += "/default] [current]:\n";
 
 
-    std::map::const_iterator it, end = m_CVarGroupDefault.m_KeyValuePair.end();
+    std::map::const_iterator it, end = m_CVarGroupDefault.m_KeyValuePair.end();
 
     for (it = m_CVarGroupDefault.m_KeyValuePair.begin(); it != end; ++it)
     {
-        const string& rKey = it->first;
+        const AZStd::string& rKey = it->first;
 
         sRet += " ... ";
         sRet += rKey;
@@ -344,7 +344,7 @@ string CXConsoleVariableCVarGroup::GetDetailedInfo() const
             sRet += "/";
         }
         sRet += GetValueSpec(rKey);
-        ICVar* pCVar = gEnv->pConsole->GetCVar(rKey);
+        ICVar* pCVar = gEnv->pConsole->GetCVar(rKey.c_str());
         if (pCVar)
         {
             sRet += " [";
@@ -369,7 +369,7 @@ const char* CXConsoleVariableCVarGroup::GetHelp()
     }
 
     // create help on demand
-    string sRet = "Console variable group to apply settings to multiple variables\n\n";
+    AZStd::string sRet = "Console variable group to apply settings to multiple variables\n\n";
 
     sRet += GetDetailedInfo();
 
@@ -545,12 +545,12 @@ bool CXConsoleVariableCVarGroup::TestCVars(const SCVarGroup* pGroup, const ICVar
 bool CXConsoleVariableCVarGroup::TestCVars(const SCVarGroup& rGroup, const ICVar::EConsoleLogMode mode, const SCVarGroup* pExclude) const
 {
     bool bRet = true;
-    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
+    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
 
     for (it = rGroup.m_KeyValuePair.begin(); it != end; ++it)
     {
-        const string& rKey = it->first;
-        const string& rValue = it->second;
+        const AZStd::string& rKey = it->first;
+        const AZStd::string& rValue = it->second;
 
         if (pExclude)
         {
@@ -674,7 +674,7 @@ bool CXConsoleVariableCVarGroup::TestCVars(const SCVarGroup& rGroup, const ICVar
 
 
 
-string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* pSpec) const
+AZStd::string CXConsoleVariableCVarGroup::GetValueSpec(const AZStd::string& sKey, const int* pSpec) const
 {
     if (pSpec)
     {
@@ -685,7 +685,7 @@ string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* p
             const SCVarGroup* pGrp = itGrp->second;
 
             // check in spec
-            std::map::const_iterator it = pGrp->m_KeyValuePair.find(sKey);
+            std::map::const_iterator it = pGrp->m_KeyValuePair.find(sKey);
 
             if (it != pGrp->m_KeyValuePair.end())
             {
@@ -695,7 +695,7 @@ string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* p
     }
 
     // check in default
-    std::map::const_iterator it = m_CVarGroupDefault.m_KeyValuePair.find(sKey);
+    std::map::const_iterator it = m_CVarGroupDefault.m_KeyValuePair.find(sKey);
 
     if (it != m_CVarGroupDefault.m_KeyValuePair.end())
     {
@@ -708,14 +708,14 @@ string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* p
 
 void CXConsoleVariableCVarGroup::ApplyCVars(const SCVarGroup& rGroup, const SCVarGroup* pExclude)
 {
-    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
+    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
 
     bool wasProcessingGroup = m_pConsole->GetIsProcessingGroup();
     m_pConsole->SetProcessingGroup(true);
 
     for (it = rGroup.m_KeyValuePair.begin(); it != end; ++it)
     {
-        const string& rKey = it->first;
+        const AZStd::string& rKey = it->first;
 
         if (pExclude)
         {
@@ -728,7 +728,7 @@ void CXConsoleVariableCVarGroup::ApplyCVars(const SCVarGroup& rGroup, const SCVa
         // Useful for debugging cvar groups
         //CryLogAlways("[CVARS]: [APPLY] ([%s]) [%s] = [%s]", GetName(), rKey.c_str(), it->second.c_str());
 
-        m_pConsole->LoadConfigVar(rKey, it->second);
+        m_pConsole->LoadConfigVar(rKey.c_str(), it->second.c_str());
     }
 
     m_pConsole->SetProcessingGroup(wasProcessingGroup);
diff --git a/Code/Legacy/CrySystem/XConsoleVariable.h b/Code/Legacy/CrySystem/XConsoleVariable.h
index 0dd05cdb07..e4f9c14355 100644
--- a/Code/Legacy/CrySystem/XConsoleVariable.h
+++ b/Code/Legacy/CrySystem/XConsoleVariable.h
@@ -16,6 +16,7 @@
 #include "SFunctor.h"
 
 class CXConsole;
+typedef AZStd::fixed_string<512> stack_string;
 
 inline int64 TextToInt64(const char* s, int64 nCurrent, bool bBitfield)
 {
@@ -184,13 +185,13 @@ public:
 
     // interface ICVar --------------------------------------------------------------------------------------
 
-    virtual int GetIVal() const { return atoi(m_sValue); }
-    virtual int64 GetI64Val() const { return _atoi64(m_sValue); }
-    virtual float GetFVal() const { return (float)atof(m_sValue); }
-    virtual const char* GetString() const { return m_sValue; }
+    virtual int GetIVal() const { return atoi(m_sValue.c_str()); }
+    virtual int64 GetI64Val() const { return _atoi64(m_sValue.c_str()); }
+    virtual float GetFVal() const { return (float)atof(m_sValue.c_str()); }
+    virtual const char* GetString() const { return m_sValue.c_str(); }
     virtual void ResetImpl()
     {
-        Set(m_sDefault);
+        Set(m_sDefault.c_str());
     }
     virtual void Set(const char* s)
     {
@@ -219,8 +220,7 @@ public:
 
     virtual void Set(float f)
     {
-        stack_string s;
-        s.Format("%g", f);
+        stack_string s = stack_string::format("%g", f);
 
         if ((m_sValue == s.c_str()) && (m_nFlags & VF_ALWAYSONCHANGE) == 0)
         {
@@ -233,8 +233,7 @@ public:
 
     virtual void Set(int i)
     {
-        stack_string s;
-        s.Format("%d", i);
+        stack_string s = stack_string::format("%d", i);
 
         if ((m_sValue == s.c_str()) && (m_nFlags & VF_ALWAYSONCHANGE) == 0)
         {
@@ -248,8 +247,8 @@ public:
 
     virtual void GetMemoryUsage(class ICrySizer* pSizer) const { pSizer->AddObject(this, sizeof(*this)); }
 private: // --------------------------------------------------------------------------------------------
-    string m_sValue;                                            
-    string m_sDefault;                                                                              //!<
+    AZStd::string m_sValue;                                            
+    AZStd::string m_sDefault;                                                                              //!<
 };
 
 
@@ -296,8 +295,7 @@ public:
             return;
         }
 
-        stack_string s;
-        s.Format("%d", i);
+        stack_string s = stack_string::format("%d", i);
 
         if (m_pConsole->OnBeforeVarChange(this, s.c_str()))
         {
@@ -364,8 +362,7 @@ public:
             return;
         }
 
-        stack_string s;
-        s.Format("%lld", i);
+        stack_string s = stack_string::format("%lld", i);
 
         if (m_pConsole->OnBeforeVarChange(this, s.c_str()))
         {
@@ -442,8 +439,7 @@ public:
             return;
         }
 
-        stack_string s;
-        s.Format("%g", f);
+        stack_string s = stack_string::format("%g", f);
 
         if (m_pConsole->OnBeforeVarChange(this, s.c_str()))
         {
@@ -718,7 +714,7 @@ public:
     {
         return m_sValue.c_str();
     }
-    virtual void ResetImpl() { Set(m_sDefault); }
+    virtual void ResetImpl() { Set(m_sDefault.c_str()); }
     virtual void Set(const char* s)
     {
         if ((m_sValue == s) && (m_nFlags & VF_ALWAYSONCHANGE) == 0)
@@ -740,14 +736,12 @@ public:
     }
     virtual void Set(float f)
     {
-        stack_string s;
-        s.Format("%g", f);
+        stack_string s = stack_string::format("%g", f);
         Set(s.c_str());
     }
     virtual void Set(int i)
     {
-        stack_string s;
-        s.Format("%d", i);
+        stack_string s = stack_string::format("%d", i);
         Set(s.c_str());
     }
     virtual int GetType() { return CVAR_STRING; }
@@ -755,8 +749,8 @@ public:
     virtual void GetMemoryUsage(class ICrySizer* pSizer) const { pSizer->AddObject(this, sizeof(*this)); }
 private: // --------------------------------------------------------------------------------------------
 
-    string m_sValue;
-    string m_sDefault;
+    AZStd::string m_sValue;
+    AZStd::string m_sDefault;
     const char*& m_userPtr;                                         //!<
 };
 
@@ -778,7 +772,7 @@ public:
 
     // Returns:
     //   part of the help string - useful to log out detailed description without additional help text
-    string GetDetailedInfo() const;
+    AZStd::string GetDetailedInfo() const;
 
     // interface ICVar -----------------------------------------------------------------------------------
 
@@ -809,7 +803,7 @@ private: // --------------------------------------------------------------------
 
     struct SCVarGroup
     {
-        std::map                         m_KeyValuePair;                 // e.g. m_KeyValuePair["r_fullscreen"]="0"
+        std::map                      m_KeyValuePair;                 // e.g. m_KeyValuePair["r_fullscreen"]="0"
         void GetMemoryUsage(class ICrySizer* pSizer) const
         {
             pSizer->AddObject(m_KeyValuePair);
@@ -818,15 +812,15 @@ private: // --------------------------------------------------------------------
 
     SCVarGroup                                                      m_CVarGroupDefault;
     typedef std::map      TCVarGroupStateMap;
-    TCVarGroupStateMap                                      m_CVarGroupStates;
-    string                                                              m_sDefaultValue;                // used by OnLoadConfigurationEntry_End()
+    TCVarGroupStateMap                                              m_CVarGroupStates;
+    AZStd::string                                                   m_sDefaultValue;                // used by OnLoadConfigurationEntry_End()
 
     void ApplyCVars(const SCVarGroup& rGroup, const SCVarGroup* pExclude = 0);
 
     // Arguments:
     //   sKey - must exist, at least in default
     //   pSpec - can be 0
-    string GetValueSpec(const string& sKey, const int* pSpec = 0) const;
+    AZStd::string GetValueSpec(const AZStd::string& sKey, const int* pSpec = 0) const;
 
     // should only be used by TestCVars()
     // Returns:

From f665f572f3790324e9d498902c00887f09a53438 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 18:53:50 -0700
Subject: [PATCH 051/251] Gems/Atom builds

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/BaseLibrary.cpp                   |   3 +-
 Code/Editor/Core/QtEditorApplication.cpp      |   7 +-
 Code/Editor/IEditorImpl.cpp                   |   2 +-
 Code/Editor/Include/IFileUtil.h               |   1 -
 Code/Editor/QtUtil.h                          |  24 ----
 Code/Editor/Util/FileUtil.h                   |   1 -
 Code/Editor/Util/PathUtil.cpp                 |  37 +++---
 Code/Editor/Util/PathUtil.h                   |  16 +--
 .../AzCore/AzCore/std/string/conversions.h    |  35 +++++-
 Code/Legacy/CryCommon/IStatObj.h              |  12 +-
 Code/Legacy/CryCommon/IXml.h                  |   8 +-
 .../Support/platform/win/CrashSupport_win.cpp |   5 +-
 Code/Tools/GridHub/GridHub/gridhub.cpp        |   8 +-
 Code/Tools/GridHub/GridHub/main.cpp           | 106 +++++++++---------
 .../Code/Source/LuxCore/LuxCoreRenderer.cpp   |   2 +-
 .../Windows/LaunchLuxCoreUI_Windows.cpp       |  12 +-
 .../Windows/RHI/PhysicalDevice_Windows.cpp    |   2 +-
 .../Windows/RHI/WindowsVersionQuery.cpp       |   4 +-
 Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp  |   8 +-
 Gems/CrashReporting/Code/CMakeLists.txt       |   1 +
 .../Code/Tests/AnimGraphCopyPasteTests.cpp    |   2 +-
 Gems/Maestro/Code/Source/Cinematics/Movie.cpp |   4 +-
 Gems/Maestro/Code/Source/Cinematics/Movie.h   |   2 +-
 .../SaveData_SystemComponent_Windows.cpp      |   3 +-
 24 files changed, 159 insertions(+), 146 deletions(-)

diff --git a/Code/Editor/BaseLibrary.cpp b/Code/Editor/BaseLibrary.cpp
index ee1c85756d..3c3ccfe13d 100644
--- a/Code/Editor/BaseLibrary.cpp
+++ b/Code/Editor/BaseLibrary.cpp
@@ -258,9 +258,8 @@ bool CBaseLibrary::SaveLibrary(const char* name, bool saveEmptyLibrary)
     }
     if (!bRes)
     {
-        string strMessage;
         QByteArray filenameUtf8 = fileName.toUtf8();
-        strMessage.Format("The file %s is read-only and the save of the library couldn't be performed. Try to remove the \"read-only\" flag or check-out the file and then try again.", filenameUtf8.data());
+        AZStd::string strMessage = AZStd::string::format("The file %s is read-only and the save of the library couldn't be performed. Try to remove the \"read-only\" flag or check-out the file and then try again.", filenameUtf8.data());
         CryMessageBox(strMessage.c_str(), "Saving Error", MB_OK | MB_ICONWARNING);
     }
     return bRes;
diff --git a/Code/Editor/Core/QtEditorApplication.cpp b/Code/Editor/Core/QtEditorApplication.cpp
index 46e789cd7c..9ec3b57e29 100644
--- a/Code/Editor/Core/QtEditorApplication.cpp
+++ b/Code/Editor/Core/QtEditorApplication.cpp
@@ -206,11 +206,8 @@ namespace
 
     static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
     {
-#if defined(WIN32) || defined(WIN64)
-        OutputDebugStringW(L"Qt: ");
-        OutputDebugStringW(reinterpret_cast(message.utf16()));
-        OutputDebugStringW(L"\n");
-#endif
+        AZ::Debug::Platform::OutputToDebugger("Qt", message.utf8());
+        AZ::Debug::Platform::OutputToDebugger(nullptr, "\n");
     }
 }
 
diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp
index c09c0a8e62..2e755bd36a 100644
--- a/Code/Editor/IEditorImpl.cpp
+++ b/Code/Editor/IEditorImpl.cpp
@@ -1109,7 +1109,7 @@ void CEditorImpl::DetectVersion()
 
     char ver[1024 * 8];
 
-    GetModuleFileName(NULL, exe, _MAX_PATH);
+    AZ::Utils::GetExecutablePath(exe, _MAX_PATH);
 
     int verSize = GetFileVersionInfoSize(exe, &dwHandle);
     if (verSize > 0)
diff --git a/Code/Editor/Include/IFileUtil.h b/Code/Editor/Include/IFileUtil.h
index f402786e67..8cb86b812e 100644
--- a/Code/Editor/Include/IFileUtil.h
+++ b/Code/Editor/Include/IFileUtil.h
@@ -8,7 +8,6 @@
 
 #pragma once
 
-#include "StringUtils.h"
 #include "../Include/SandboxAPI.h"
 
 class QWidget;
diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h
index bb1f8ba427..a9aaadc491 100644
--- a/Code/Editor/QtUtil.h
+++ b/Code/Editor/QtUtil.h
@@ -10,8 +10,6 @@
 #pragma once
 
 #include 
-#include 
-#include "UnicodeFunctions.h"
 
 #include 
 #include 
@@ -36,28 +34,6 @@ public:
 
 namespace QtUtil
 {
-    // From QString to CryString
-    inline CryStringT ToString(const QString& str)
-    {
-        return Unicode::Convert >(str);
-    }
-
-    // From CryString to QString
-    inline QString ToQString(const CryStringT& str)
-    {
-        return Unicode::Convert(str);
-    }
-
-    // From const char * to QString
-    inline QString ToQString(const char* str, size_t len = -1)
-    {
-        if (len == -1)
-        {
-            len = strlen(str);
-        }
-        return Unicode::Convert(str, str + len);
-    }
-
     // Replacement for CString::trimRight()
     inline QString trimRight(const QString& str)
     {
diff --git a/Code/Editor/Util/FileUtil.h b/Code/Editor/Util/FileUtil.h
index 000215e98d..06cceaaafc 100644
--- a/Code/Editor/Util/FileUtil.h
+++ b/Code/Editor/Util/FileUtil.h
@@ -10,7 +10,6 @@
 #pragma once
 
 #include "CryThread.h"
-#include "StringUtils.h"
 #include "../Include/SandboxAPI.h"
 #include 
 #include 
diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp
index 4bb5c20ece..e91d85e4d2 100644
--- a/Code/Editor/Util/PathUtil.cpp
+++ b/Code/Editor/Util/PathUtil.cpp
@@ -15,24 +15,20 @@
 #include  // for ebus events
 #include 
 #include 
+#include 
 
 #include 
 
-namespace
-{
-    string g_currentModName; // folder name only!
-}
-
 namespace Path
 {
     //////////////////////////////////////////////////////////////////////////
     void SplitPath(const QString& rstrFullPathFilename, QString& rstrDriveLetter, QString& rstrDirectory, QString& rstrFilename, QString& rstrExtension)
     {
-        string          strFullPathString(rstrFullPathFilename.toUtf8().data());
-        string          strDriveLetter;
-        string          strDirectory;
-        string          strFilename;
-        string          strExtension;
+        AZStd::string   strFullPathString(rstrFullPathFilename.toUtf8().data());
+        AZStd::string   strDriveLetter;
+        AZStd::string   strDirectory;
+        AZStd::string   strFilename;
+        AZStd::string   strExtension;
 
         char*           szPath((char*)strFullPathString.c_str());
         char*           pchLastPosition(szPath);
@@ -81,16 +77,16 @@ namespace Path
             strFilename.assign(pchLastPosition, pchCurrentPosition);
         }
 
-        rstrDriveLetter = strDriveLetter;
-        rstrDirectory = strDirectory;
-        rstrFilename = strFilename;
-        rstrExtension = strExtension;
+        rstrDriveLetter = strDriveLetter.c_str();
+        rstrDirectory = strDirectory.c_str();
+        rstrFilename = strFilename.c_str();
+        rstrExtension = strExtension.c_str();
     }
     //////////////////////////////////////////////////////////////////////////
     void GetDirectoryQueue(const QString& rstrSourceDirectory, QStringList& rcstrDirectoryTree)
     {
-        string                      strCurrentDirectoryName;
-        string                      strSourceDirectory(rstrSourceDirectory.toUtf8().data());
+        AZStd::string           strCurrentDirectoryName;
+        AZStd::string           strSourceDirectory(rstrSourceDirectory.toUtf8().data());
         const char*             szSourceDirectory(strSourceDirectory.c_str());
         const char*             pchCurrentPosition(szSourceDirectory);
         const char*             pchLastPosition(szSourceDirectory);
@@ -207,7 +203,9 @@ namespace Path
 
     bool IsFolder(const char* pPath)
     {
-        DWORD attrs = GetFileAttributes(pPath);
+        AZStd::wstring pPathW;
+        AZStd::to_wstring(pPathW, pPath);
+        DWORD attrs = GetFileAttributes(pPathW.c_str());
 
         if (attrs == FILE_ATTRIBUTE_DIRECTORY)
         {
@@ -255,16 +253,17 @@ namespace Path
     /// Get the data folder
     AZStd::string GetEditingGameDataFolder()
     {
+        static AZStd::string s_currentModName;
         // query the editor root.  The bus exists in case we want tools to be able to override this.
 
 
-        if (g_currentModName.empty())
+        if (s_currentModName.empty())
         {
             return GetGameAssetsFolder();
         }
         AZStd::string str(GetGameAssetsFolder());
         str += "Mods\\";
-        str += g_currentModName;
+        str += s_currentModName;
         return str;
     }
 
diff --git a/Code/Editor/Util/PathUtil.h b/Code/Editor/Util/PathUtil.h
index 98f484ec94..30887e698b 100644
--- a/Code/Editor/Util/PathUtil.h
+++ b/Code/Editor/Util/PathUtil.h
@@ -93,7 +93,7 @@ namespace Path
 #endif
         file = path_buffer;
     }
-    inline void Split(const string& filepath, string& path, string& file)
+    inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& file)
     {
         char path_buffer[_MAX_PATH];
         char drive[_MAX_DRIVE];
@@ -101,7 +101,7 @@ namespace Path
         char fname[_MAX_FNAME];
         char ext[_MAX_EXT];
 #ifdef AZ_COMPILER_MSVC
-        _splitpath_s(filepath, drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), 0, 0, 0, 0);
+        _splitpath_s(filepath.c_str(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), 0, 0, 0, 0);
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, 0, 0);
         path = path_buffer;
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), 0, 0, fname, ext);
@@ -137,7 +137,7 @@ namespace Path
         filename = fname;
         fext = ext;
     }
-    inline void Split(const string& filepath, string& path, string& filename, string& fext)
+    inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& filename, AZStd::string& fext)
     {
         char path_buffer[_MAX_PATH];
         char drive[_MAX_DRIVE];
@@ -145,7 +145,7 @@ namespace Path
         char fname[_MAX_FNAME];
         char ext[_MAX_EXT];
 #ifdef AZ_COMPILER_MSVC
-        _splitpath_s(filepath, drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), fname, AZ_ARRAY_SIZE(fname), ext, AZ_ARRAY_SIZE(ext));
+        _splitpath_s(filepath.c_str(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), fname, AZ_ARRAY_SIZE(fname), ext, AZ_ARRAY_SIZE(ext));
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, 0, 0);
 #else
         _splitpath(filepath, drive, dir, fname, ext);
@@ -271,7 +271,7 @@ namespace Path
     }
 
     template
-    inline void AddBackslash(AZstd::fixed_string* path)
+    inline void AddBackslash(AZStd::fixed_string* path)
     {
         if (path->empty())
         {
@@ -284,7 +284,7 @@ namespace Path
     }
 
     template
-    inline void AddSlash(AZstd::fixed_string* path)
+    inline void AddSlash(AZStd::fixed_string* path)
     {
         if (path->empty())
         {
@@ -357,7 +357,7 @@ namespace Path
     {
         return CaselessPaths(GetRelativePath(path, true));
     }
-    inline string FullPathToGamePath(const char* path)
+    inline AZStd::string FullPathToGamePath(const char* path)
     {
         return CaselessPaths(GetRelativePath(path, true)).toUtf8().data();
     }
@@ -394,7 +394,7 @@ namespace Path
     inline QString GetAudioLocalizationFolder(bool returnAbsolutePath)
     {
         // Omit the trailing slash!
-        QString sLocalizationFolder(QString(PathUtil::GetLocalizationFolder()).left(static_cast(PathUtil::GetLocalizationFolder().size()) - 1));
+        QString sLocalizationFolder(QString(PathUtil::GetLocalizationFolder().c_str()).left(static_cast(PathUtil::GetLocalizationFolder().size()) - 1));
 
         if (!sLocalizationFolder.isEmpty())
         {
diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index cb90881933..fcfe82ba5f 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -80,9 +80,7 @@ namespace AZStd
                 }
                 else
                 {
-                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
-                    using StringType = AZStd::basic_string;
-                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
+                    static_assert(false, "only wchar_t types of size 2 or 4 can be converted to utf8");
                 }
             }
 
@@ -123,6 +121,22 @@ namespace AZStd
                     static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
                 }
             }
+
+            static inline void to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf8to16(first, last, dest, destSize);
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf8to32(first, last, dest, destSize);
+                }
+                else
+                {
+                    static_assert(false, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
+                }
+            }
         };
     }
     // 21.5: numeric conversions
@@ -348,7 +362,7 @@ namespace AZStd
     {
         if (srcLen == 0)
         {
-            srcLen = wcslen(str) + 1;
+            srcLen = wcslen(str);
         }
 
         if (srcLen > 0)
@@ -497,6 +511,19 @@ namespace AZStd
         return to_wstring(dest, src.c_str(), src.length());
     }
 
+    inline void to_wstring(wchar_t* dest, size_t destSize, const char* str, size_t srcLen = 0)
+    {
+        if (srcLen == 0)
+        {
+            srcLen = strlen(str) + 1;
+        }
+
+        if (srcLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen + 1); // copy null terminator
+        }
+    }
+
     // Convert a range of chars to lower case
 #if defined(AZSTD_USE_OLD_RW_STL)
     template
diff --git a/Code/Legacy/CryCommon/IStatObj.h b/Code/Legacy/CryCommon/IStatObj.h
index ff3bbc41e3..4921ab3a25 100644
--- a/Code/Legacy/CryCommon/IStatObj.h
+++ b/Code/Legacy/CryCommon/IStatObj.h
@@ -201,7 +201,7 @@ struct IStreamable
     virtual void StartStreaming(bool bFinishNow, IReadStream_AutoPtr* ppStream) = 0;
     virtual int GetStreamableContentMemoryUsage(bool bJustForDebug = false) = 0;
     virtual void ReleaseStreamableContent() = 0;
-    virtual void GetStreamableName(string& sName) = 0;
+    virtual void GetStreamableName(AZStd::string& sName) = 0;
     virtual uint32 GetLastDrawMainFrameId() = 0;
     virtual bool IsUnloadable() const = 0;
 
@@ -239,8 +239,8 @@ struct IStatObj
         SSubObject() { bShadowProxy = 0; }
 
         EStaticSubObjectType nType;
-        string name;
-        string properties;
+        AZStd::string name;
+        AZStd::string properties;
         int nParent;          // Index of the parent sub object, if there`s hierarchy between them.
         Matrix34 tm;          // Transformation matrix.
         Matrix34 localTM;     // Local transformation matrix, relative to parent.
@@ -510,10 +510,10 @@ struct IStatObj
     virtual bool IsUnloadable() const = 0;
     virtual void SetCanUnload(bool value) = 0;
 
-    virtual string& GetFileName() = 0;
-    virtual const string& GetFileName() const = 0;
+    virtual AZStd::string& GetFileName() = 0;
+    virtual const AZStd::string& GetFileName() const = 0;
 
-    virtual const string& GetCGFNodeName() const = 0;
+    virtual const AZStd::string& GetCGFNodeName() const = 0;
 
     // Summary:
     //     Returns the filename of the object
diff --git a/Code/Legacy/CryCommon/IXml.h b/Code/Legacy/CryCommon/IXml.h
index a380ce167b..80c2415f9c 100644
--- a/Code/Legacy/CryCommon/IXml.h
+++ b/Code/Legacy/CryCommon/IXml.h
@@ -101,7 +101,13 @@ public:
     XmlString(const char* str)
         : AZStd::string(str) {};
 
-    operator const char*() const {
+    size_t GetAllocatedMemory() const
+    {
+        return sizeof(XmlString) + capacity() * sizeof(AZStd::string::value_type);
+    }
+
+    operator const char*() const
+    {
         return c_str();
     }
 };
diff --git a/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp b/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp
index 3933b5ea91..6010ac8e17 100644
--- a/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp
+++ b/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp
@@ -10,13 +10,14 @@
 #include 
 
 #include 
+#include 
 #include 
 
 namespace CrashHandler
 {
-    void GetExecutablePathA(char* pathBuffer, int& bufferSize)
+    void GetExecutablePath(char* pathBuffer, int& bufferSize)
     {
-        GetModuleFileNameA(nullptr, pathBuffer, bufferSize);
+        AZ::Utils::GetExecutablePath(pathBuffer, bufferSize);
     }
 
     void GetExecutablePathW(wchar_t* pathBuffer, int& bufferSize)
diff --git a/Code/Tools/GridHub/GridHub/gridhub.cpp b/Code/Tools/GridHub/GridHub/gridhub.cpp
index 3dbecf681f..978589ab74 100644
--- a/Code/Tools/GridHub/GridHub/gridhub.cpp
+++ b/Code/Tools/GridHub/GridHub/gridhub.cpp
@@ -358,13 +358,11 @@ GridHubComponent::GridHubComponent()
     m_isLogToFile = false;
     
 #ifdef AZ_PLATFORM_WINDOWS
-    TCHAR name[MAX_COMPUTERNAME_LENGTH + 1];
+    wchar_t name[MAX_COMPUTERNAME_LENGTH + 1];
     DWORD dwCompNameLen = AZ_ARRAY_SIZE(name);
-    if ( GetComputerName(name, &dwCompNameLen) != 0 ) 
+    if (GetComputerName(name, &dwCompNameLen) != 0) 
     {
-        char c[MAX_COMPUTERNAME_LENGTH + 1];
-        wcstombs(c, name, AZ_ARRAY_SIZE(c));
-        m_hubName = c;
+        AZStd::to_string(m_hubName, name);
     }
     else
 #endif
diff --git a/Code/Tools/GridHub/GridHub/main.cpp b/Code/Tools/GridHub/GridHub/main.cpp
index f02906e0d4..670367bf06 100644
--- a/Code/Tools/GridHub/GridHub/main.cpp
+++ b/Code/Tools/GridHub/GridHub/main.cpp
@@ -16,7 +16,6 @@
 #include 
 #include 
 #include 
-#include 
 #endif
 
 #include "gridhub.hxx"
@@ -39,6 +38,7 @@ AZ_POP_DISABLE_WARNING
 #include 
 #include 
 #include 
+#include 
 
 #ifdef AZ_PLATFORM_WINDOWS
 #include 
@@ -53,9 +53,9 @@ AZ_POP_DISABLE_WARNING
 #endif
 
 #ifdef AZ_PLATFORM_WINDOWS
-#define GRIDHUB_TSR_SUFFIX _T("_copyapp_")
-#define GRIDHUB_TSR_NAME _T("GridHub_copyapp_.exe")
-#define GRIDHUB_IMAGE_NAME _T("GridHub.exe")
+#define GRIDHUB_TSR_SUFFIX L"_copyapp_"
+#define GRIDHUB_TSR_NAME L"GridHub_copyapp_.exe"
+#define GRIDHUB_IMAGE_NAME L"GridHub.exe"
 #else
 #define GRIDHUB_TSR_SUFFIX "_copyapp_"
 #define GRIDHUB_TSR_NAME "GridHub_copyapp_"
@@ -191,7 +191,7 @@ protected:
          specializations.Append("gridhub");
      }
 
-    QString         m_originalExeFileName;
+     QString        m_originalExeFileName;
      QDateTime      m_originalExeLastModified;
      bool           m_monitorForExeChanges;
      bool           m_needToRelaunch;
@@ -305,22 +305,22 @@ public:
     {
 #ifdef AZ_PLATFORM_WINDOWS
         HRESULT hres;
-        TCHAR startupFolder[MAX_PATH] = {0};
-        TCHAR fullLinkName[MAX_PATH] = {0};
+        wchar_t startupFolder[MAX_PATH] = {0};
+        wchar_t fullLinkName[MAX_PATH] = {0};
 
         LPITEMIDLIST pidlFolder = NULL;
         hres = SHGetFolderLocation(0,/*CSIDL_COMMON_STARTUP all users required admin access*/CSIDL_STARTUP,NULL,0,&pidlFolder);
         if (SUCCEEDED(hres))
         {
-            if( SHGetPathFromIDList(pidlFolder,startupFolder) )
+            if (SHGetPathFromIDList(pidlFolder, startupFolder))
             {
-                _tcscat_s(fullLinkName,startupFolder);
-                _tcscat_s(fullLinkName,"\\Amazon Grid Hub.lnk");
+                wcscat_s(fullLinkName, startupFolder);
+                wcscat_s(fullLinkName, L"\\Amazon Grid Hub.lnk");
             }
             CoTaskMemFree(pidlFolder);
         }
 
-        if( moduleFilename.isEmpty() || _tcslen(fullLinkName) == 0 )
+        if( moduleFilename.isEmpty() || wcslen(fullLinkName) == 0 )
             return;
 
         // for development, never autoadd to startup
@@ -342,8 +342,8 @@ public:
                 IPersistFile* ppf;
 
                 // Set the path to the shortcut target and add the description.
-                psl->SetPath(moduleFilename.toUtf8().data());
-                psl->SetDescription("Amazon Grid Hub");
+                psl->SetPath(moduleFilename.toStdWString().c_str());
+                psl->SetDescription(L"Amazon Grid Hub");
 
                 // Query IShellLink for the IPersistFile interface, used for saving the
                 // shortcut in persistent storage.
@@ -351,16 +351,8 @@ public:
 
                 if (SUCCEEDED(hres))
                 {
-                    WCHAR wsz[MAX_PATH];
-
-                    // Ensure that the string is Unicode.
-                    MultiByteToWideChar(CP_ACP, 0, fullLinkName, -1, wsz, MAX_PATH);
-
-                    // Add code here to check return value from MultiByteWideChar
-                    // for success.
-
                     // Save the link by calling IPersistFile::Save.
-                    hres = ppf->Save(wsz, TRUE);
+                    hres = ppf->Save(fullLinkName, TRUE);
                     ppf->Release();
                 }
                 psl->Release();
@@ -412,13 +404,17 @@ GridHubApplication::Create(const Descriptor& descriptor, const StartupParameters
     {
         bool isError = false;
 #ifdef AZ_PLATFORM_WINDOWS
-        TCHAR originalExeFileName[MAX_PATH];
-        if (GetModuleFileName(NULL, originalExeFileName, AZ_ARRAY_SIZE(originalExeFileName)))
+        char originalExeFileName[MAX_PATH];
+        if (AZ::Utils::GetExecutablePath(originalExeFileName, AZ_ARRAY_SIZE(originalExeFileName)).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
         {
-            PathRemoveFileSpec(originalExeFileName);
-            PathAppend(originalExeFileName, GRIDHUB_IMAGE_NAME);
+            wchar_t originalExeFileNameW[MAX_PATH];
+            AZStd::to_wstring(originalExeFileNameW, MAX_PATH, originalExeFileName, MAX_PATH);
+            PathRemoveFileSpec(originalExeFileNameW);
+            PathAppend(originalExeFileNameW, GRIDHUB_IMAGE_NAME);
 
-            m_originalExeFileName = originalExeFileName;
+            AZStd::string finalExeFileName;
+            AZStd::to_string(finalExeFileName, originalExeFileNameW);
+            m_originalExeFileName = finalExeFileName.c_str();
 
             m_originalExeLastModified = QFileInfo(m_originalExeFileName).lastModified();
         }
@@ -489,18 +485,20 @@ void GridHubApplication::RegisterCoreComponents()
 void CopyAndRun(bool failSilently)
 {
 #ifdef AZ_PLATFORM_WINDOWS
-    TCHAR myFileName[MAX_PATH] = { _T(0) };
-    if (GetModuleFileName(NULL, myFileName, MAX_PATH ))
+    char myFileName[MAX_PATH] = { 0 };
+    if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
     {
-        TCHAR sourceProcPath[MAX_PATH] = { _T(0) };
-        TCHAR targetProcPath[MAX_PATH] = { _T(0) };
-        TCHAR procDrive[MAX_PATH] = { _T(0) };
-        TCHAR procDir[MAX_PATH] = { _T(0) };
-        TCHAR procFname[MAX_PATH] = { _T(0) };
-        TCHAR procExt[MAX_PATH] = { _T(0) };
-        _tsplitpath_s(myFileName, procDrive, procDir, procFname, procExt);
-        _tmakepath_s(sourceProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
-        _tmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_TSR_NAME, NULL);
+        wchar_t myFileNameW[MAX_PATH] = { 0 };
+        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH);
+        wchar_t sourceProcPath[MAX_PATH] = { 0 };
+        wchar_t targetProcPath[MAX_PATH] = { 0 };
+        wchar_t procDrive[MAX_PATH] = { 0 };
+        wchar_t procDir[MAX_PATH] = { 0 };
+        wchar_t procFname[MAX_PATH] = { 0 };
+        wchar_t procExt[MAX_PATH] = { 0 };
+        _wsplitpath_s(myFileNameW, procDrive, procDir, procFname, procExt);
+        _wmakepath_s(sourceProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
+        _wmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_TSR_NAME, NULL);
         if (CopyFileEx(sourceProcPath, targetProcPath, NULL, NULL, NULL, 0))
         {
             STARTUPINFO si;
@@ -527,9 +525,9 @@ void CopyAndRun(bool failSilently)
         {
             if (!failSilently)
             {
-                TCHAR errorMsg[1024] = { _T(0) };
-                _stprintf_s(errorMsg, _T("Failed to copy GridHub. Make sure that %s%s is writable!"), procFname, procExt);
-                MessageBox(NULL, errorMsg, NULL, MB_ICONSTOP|MB_OK);
+                wchar_t errorMsg[1024] = { 0 };
+                swprintf_s(errorMsg, L"Failed to copy GridHub. Make sure that %s%s is writable!", procFname, procExt);
+                MessageBoxW(NULL, errorMsg, NULL, MB_ICONSTOP|MB_OK);
             }
         }
     }
@@ -565,16 +563,18 @@ void CopyAndRun(bool failSilently)
 void RelaunchImage()
 {
 #ifdef AZ_PLATFORM_WINDOWS
-    TCHAR myFileName[MAX_PATH] = { _T(0) };
-    if (GetModuleFileName(NULL, myFileName, MAX_PATH))
+    char myFileName[MAX_PATH] = { 0 };
+    if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
     {
-        TCHAR targetProcPath[MAX_PATH] = { _T(0) };
-        TCHAR procDrive[MAX_PATH] = { _T(0) };
-        TCHAR procDir[MAX_PATH] = { _T(0) };
-        TCHAR procFname[MAX_PATH] = { _T(0) };
-        TCHAR procExt[MAX_PATH] = { _T(0) };
-        _tsplitpath_s(myFileName, procDrive, procDir, procFname, procExt);
-        _tmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
+        wchar_t myFileNameW[MAX_PATH] = { 0 };
+        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH);
+        wchar_t targetProcPath[MAX_PATH] = { 0 };
+        wchar_t procDrive[MAX_PATH] = { 0 };
+        wchar_t procDir[MAX_PATH] = { 0 };
+        wchar_t procFname[MAX_PATH] = { 0 };
+        wchar_t procExt[MAX_PATH] = { 0 };
+        _wsplitpath_s(myFileNameW, procDrive, procDir, procFname, procExt);
+        _wmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
 
         STARTUPINFO si;
         PROCESS_INFORMATION pi;
@@ -635,8 +635,8 @@ int main(int argc, char *argv[])
     {
 
 #ifdef AZ_PLATFORM_WINDOWS
-        TCHAR exeFileName[MAX_PATH];
-        if( GetModuleFileName(NULL,exeFileName,AZ_ARRAY_SIZE(exeFileName)) )
+        char exeFileName[MAX_PATH];
+        if (AZ::Utils::GetExecutablePath(exeFileName, AZ_ARRAY_SIZE(exeFileName)).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
 #elif defined AZ_PLATFORM_LINUX
         //KDAB_TODO
         char exeFileName[MAXPATHLEN];
@@ -661,7 +661,7 @@ int main(int argc, char *argv[])
         {
 #ifdef AZ_PLATFORM_WINDOWS
             // Create a OS named mutex while the OS is running
-            HANDLE hInstanceMutex = CreateMutex(NULL,TRUE,"Global\\GridHub-Instance");
+            HANDLE hInstanceMutex = CreateMutex(NULL, TRUE, L"Global\\GridHub-Instance");
             AZ_Assert(hInstanceMutex!=NULL,"Failed to create OS mutex [GridHub-Instance]\n");
             if( hInstanceMutex != NULL && GetLastError() == ERROR_ALREADY_EXISTS)
             {
diff --git a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp
index 40fcbc7f31..c753079d5b 100644
--- a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp
+++ b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp
@@ -19,7 +19,7 @@
 
 namespace LuxCoreUI
 {
-    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, AZStd::string& commandLine);
+    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, const AZStd::string& commandLine);
 }
 
 namespace AZ
diff --git a/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp b/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp
index 3c8f304cb6..7f15949201 100644
--- a/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp
+++ b/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp
@@ -7,11 +7,12 @@
  */
 
 #include 
+#include 
 #include 
 
 namespace LuxCoreUI
 {
-    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, AZStd::string& commandLine)
+    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, const AZStd::string& commandLine)
     {
         STARTUPINFO si;
         PROCESS_INFORMATION pi;
@@ -20,9 +21,14 @@ namespace LuxCoreUI
         si.cb = sizeof(si);
         ZeroMemory(&pi, sizeof(pi));
 
+        AZStd::wstring luxCoreExeFullPathW;
+        AZStd::to_wstring(luxCoreExeFullPathW, luxCoreExeFullPath.c_str());
+        AZStd::wstring commandLineW;
+        AZStd::to_wstring(commandLineW, commandLine.c_str());
+
         // start the program up
-        CreateProcess(luxCoreExeFullPath.data(),   // the path
-            commandLine.data(),        // Command line
+        CreateProcessW(luxCoreExeFullPathW.c_str(),   // the path
+            commandLineW.data(),        // Command line
             NULL,           // Process handle not inheritable
             NULL,           // Thread handle not inheritable
             FALSE,          // Set handle inheritance to FALSE
diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp
index 6e5206fc00..2c56a860e8 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp
@@ -78,7 +78,7 @@ namespace AZ
             }
 
             constexpr uint32_t SubKeyLength = 256;
-            char subKeyName[SubKeyLength];
+            wchar_t subKeyName[SubKeyLength];
 
             uint32_t driverVersion = 0;
 
diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp
index 0301d48454..91f0a712dd 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp
@@ -18,7 +18,7 @@ namespace AZ
             bool GetWindowsVersionFromSystemDLL(WindowsVersion* windowsVersion)
             {
                 // We get the file version of one of the system DLLs to get the OS version.
-                constexpr const char* dllName = "Kernel32.dll";
+                constexpr const wchar_t* dllName = L"Kernel32.dll";
                 VS_FIXEDFILEINFO* fileInfo = nullptr;
                 DWORD handle;
                 DWORD infoSize = GetFileVersionInfoSize(dllName, &handle);
@@ -28,7 +28,7 @@ namespace AZ
                     if (GetFileVersionInfo(dllName, handle, infoSize, versionData.data()) != 0)
                     {
                         UINT len;
-                        const char* subBlock = "\\";
+                        const wchar_t* subBlock = L"\\";
                         if (VerQueryValue(versionData.data(), subBlock, reinterpret_cast(&fileInfo), &len) != 0)
                         {
                             windowsVersion->m_majorVersion = HIWORD(fileInfo->dwProductVersionMS);
diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp
index db15930c01..f61aa3f67f 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp
@@ -13,9 +13,13 @@ namespace AZ
     namespace DX12
     {
         FenceEvent::FenceEvent(const char* name)
-            : m_EventHandle(CreateEvent(nullptr, false, false, name))
+            : m_EventHandle(nullptr)
             , m_name(name)
-        {}
+        {
+            AZStd::wstring nameW;
+            AZStd::to_wstring(nameW, name);
+            m_EventHandle = CreateEvent(nullptr, false, false, nameW.c_str());
+        }
 
         FenceEvent::~FenceEvent()
         {
diff --git a/Gems/CrashReporting/Code/CMakeLists.txt b/Gems/CrashReporting/Code/CMakeLists.txt
index 37224ea1aa..b12b5d8944 100644
--- a/Gems/CrashReporting/Code/CMakeLists.txt
+++ b/Gems/CrashReporting/Code/CMakeLists.txt
@@ -28,6 +28,7 @@ ly_add_target(
     BUILD_DEPENDENCIES
         PRIVATE
             AZ::CrashHandler
+            AZ::AzCore
 )
 
 # Load the "Gem::CrashReporting" module in Clients and Servers
diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp
index eb16a1a57c..4feb8cd86a 100644
--- a/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp
+++ b/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp
@@ -159,7 +159,7 @@ namespace EMotionFX
                     (azrtti_typeid<>(conditionPrototype) != azrtti_typeid()))
                 {
                     AZ::TypeId type = azrtti_typeid<>(conditionPrototype);
-                    OutputDebugString(AZStd::string::format("Condition: Name=%s, Type=%s\n", conditionPrototype->GetPaletteName(), type.ToString().c_str()).c_str());
+                    AZ::Debug::Platform::OutputToDebugger(nullptr, AZStd::string::format("Condition: Name=%s, Type=%s\n", conditionPrototype->GetPaletteName(), type.ToString().c_str()).c_str());
                     result.emplace_back(azrtti_typeid<>(conditionPrototype));
                 }
             }
diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
index 2d5aa7b410..a6d9e47eb1 100644
--- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
@@ -1963,7 +1963,7 @@ void CLightAnimWrapper::InvalidateAllNodes()
 
 CLightAnimWrapper* CLightAnimWrapper::FindLightAnim(const char* name)
 {
-    LightAnimWrapperCache::const_iterator it = ms_lightAnimWrapperCache.find(CONST_TEMP_STRING(name));
+    LightAnimWrapperCache::const_iterator it = ms_lightAnimWrapperCache.find(name);
     return it != ms_lightAnimWrapperCache.end() ? (*it).second : 0;
 }
 
@@ -1976,7 +1976,7 @@ void CLightAnimWrapper::CacheLightAnim(const char* name, CLightAnimWrapper* p)
 //////////////////////////////////////////////////////////////////////////
 void CLightAnimWrapper::RemoveCachedLightAnim(const char* name)
 {
-    ms_lightAnimWrapperCache.erase(CONST_TEMP_STRING(name));
+    ms_lightAnimWrapperCache.erase(name);
 }
 
 #ifdef MOVIESYSTEM_SUPPORT_EDITING
diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.h b/Gems/Maestro/Code/Source/Cinematics/Movie.h
index cb97cfc40b..6ac857d652 100644
--- a/Gems/Maestro/Code/Source/Cinematics/Movie.h
+++ b/Gems/Maestro/Code/Source/Cinematics/Movie.h
@@ -48,7 +48,7 @@ public:
     static void InvalidateAllNodes();
 
 private:
-    typedef std::map LightAnimWrapperCache;
+    typedef std::map LightAnimWrapperCache;
     static StaticInstance ms_lightAnimWrapperCache;
     static AZStd::intrusive_ptr ms_pLightAnimSet;
 
diff --git a/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp b/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp
index 236b2f525c..2e473cfea7 100644
--- a/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp
+++ b/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp
@@ -10,6 +10,7 @@
 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -99,7 +100,7 @@ namespace SaveData
     AZStd::string GetExecutableName()
     {
         char moduleFileName[AZ_MAX_PATH_LEN];
-        GetModuleFileNameA(nullptr, moduleFileName, AZ_MAX_PATH_LEN);
+        AZ::Utils::GetExecutablePath(moduleFileName, AZ_MAX_PATH_LEN);
 
         const AZStd::string moduleFileNameString(moduleFileName);
         const size_t executableNameStart = moduleFileNameString.find_last_of('\\') + 1;

From 8eb92057115ea2fd87354fc230f885ffc3d28927 Mon Sep 17 00:00:00 2001
From: Dayo Lawal 
Date: Mon, 2 Aug 2021 00:34:43 -0500
Subject: [PATCH 052/251] AtomToolsMainWindow

Signed-off-by: Dayo Lawal 
---
 .../Window/AtomToolsMainWindow.h              |  48 +++++++
 .../Source/Window/AtomToolsMainWindow.cpp     | 135 ++++++++++++++++++
 .../Code/atomtoolsframework_files.cmake       |   2 +
 .../Source/Window/MaterialEditorWindow.cpp    |  97 +------------
 .../Code/Source/Window/MaterialEditorWindow.h |  24 ++--
 .../Window/ShaderManagementConsoleWindow.cpp  | 103 ++-----------
 .../Window/ShaderManagementConsoleWindow.h    |  26 ++--
 7 files changed, 217 insertions(+), 218 deletions(-)
 create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
 create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp

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..21afe114f5
--- /dev/null
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
@@ -0,0 +1,48 @@
+/*
+ * 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 
+
+namespace AtomToolsFramework
+{
+    class AtomToolsMainWindow
+        : public AzQtComponents::DockMainWindow
+    {
+    public:
+        AtomToolsMainWindow(QWidget* parent = 0);
+    protected:
+        AzQtComponents::FancyDocking* m_advancedDockManager = nullptr;
+        QWidget* m_centralWidget = nullptr;
+        QMenuBar* m_menuBar = nullptr;
+        AzQtComponents::TabWidget* m_tabWidget = nullptr;
+
+        virtual void SetupMenu();
+
+        virtual void SetupTabs();
+        virtual void AddTabForDocumentId(const AZ::Uuid& documentId);
+        virtual void RemoveTabForDocumentId(const AZ::Uuid& documentId);
+        virtual void UpdateTabForDocumentId(const AZ::Uuid& documentId);
+        virtual AZ::Uuid GetDocumentIdFromTab(const int tabIndex) const;
+        
+        virtual void OpenTabContextMenu();
+        virtual void SelectPreviousTab();
+        virtual void SelectNextTab();
+
+        QMenu* m_menuFile = {};
+    };
+}
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..15edd8c5b6
--- /dev/null
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp
@@ -0,0 +1,135 @@
+/*
+ * 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_menuBar = new QMenuBar(this);
+        m_menuBar->setObjectName("MenuBar");
+        setMenuBar(m_menuBar);
+
+        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);
+    }
+
+    void AtomToolsMainWindow::SetupMenu()
+    {
+        // 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");
+    }
+
+    void AtomToolsMainWindow::SetupTabs()
+    {
+        // 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)
+    {
+        // 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;
+            }
+        }
+    }
+
+    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)
+    {
+        // Whenever a document is opened, saved, or modified we need to update the tab label
+        if (!documentId.IsNull())
+        {
+            return;
+        }
+    }
+
+    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());
+        }
+    }
+}
diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake
index 86fc3f5f5e..5ef4426537 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake
@@ -24,6 +24,7 @@ set(FILES
     Include/AtomToolsFramework/Viewport/RenderViewportWidget.h
     Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h
     Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h
+	Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
     Source/Application/AtomToolsApplication.cpp
     Source/Communication/LocalServer.cpp
     Source/Communication/LocalSocket.cpp
@@ -40,4 +41,5 @@ set(FILES
     Source/Util/Util.cpp
     Source/Viewport/RenderViewportWidget.cpp
     Source/Viewport/ModularViewportCameraController.cpp
+	Source/Window/AtomToolsMainWindow.cpp
 )
diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
index abb0102de6..78670ac710 100644
--- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
+++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
@@ -56,7 +56,7 @@ AZ_POP_DISABLE_WARNING
 namespace MaterialEditor
 {
     MaterialEditorWindow::MaterialEditorWindow(QWidget* parent /* = 0 */)
-        : AzQtComponents::DockMainWindow(parent)
+        : AtomToolsFramework::AtomToolsMainWindow(parent)
     {
         resize(1280, 1024);
 
@@ -83,29 +83,12 @@ 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);
@@ -370,8 +353,7 @@ namespace MaterialEditor
 
     void MaterialEditorWindow::SetupMenu()
     {
-        // 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");
+        AtomToolsFramework::AtomToolsMainWindow::SetupMenu();
 
         m_actionNew = m_menuFile->addAction("&New...", [this]() {
             CreateMaterialDialog createDialog(this);
@@ -563,18 +545,7 @@ namespace MaterialEditor
 
     void MaterialEditorWindow::SetupTabs()
     {
-        // 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();
-        });
+        AtomToolsFramework::AtomToolsMainWindow::SetupTabs();
 
         // 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
@@ -600,20 +571,7 @@ namespace MaterialEditor
             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;
-            }
-        }
+        AtomToolsMainWindow::AddTabForDocumentId(documentId);
 
         // Create a new tab for the document ID and assign it's label to the file name of the document.
         AZStd::string absolutePath;
@@ -639,22 +597,6 @@ namespace MaterialEditor
         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
@@ -698,20 +640,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 +666,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..96f03e6eed 100644
--- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
+++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
@@ -11,6 +11,7 @@
 #if !defined(Q_MOC_RUN)
 #include 
 #include 
+#include 
 
 AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT
 #include 
@@ -44,7 +45,7 @@ namespace MaterialEditor
      * 3) MaterialPropertyInspector  - The user edits the properties of the selected Material.
      */
     class MaterialEditorWindow
-        : public AzQtComponents::DockMainWindow
+        : public AtomToolsFramework::AtomToolsMainWindow
         , private MaterialEditorWindowRequestBus::Handler
         , private MaterialDocumentNotificationBus::Handler
     {
@@ -52,6 +53,8 @@ namespace MaterialEditor
     public:
         AZ_CLASS_ALLOCATOR(MaterialEditorWindow, AZ::SystemAllocator, 0);
 
+        using Base = AtomToolsFramework::AtomToolsMainWindow;
+
         MaterialEditorWindow(QWidget* parent = 0);
         ~MaterialEditorWindow();
 
@@ -75,31 +78,22 @@ namespace MaterialEditor
         void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override;
         void OnDocumentSaved(const AZ::Uuid& documentId) override;
 
-        void SetupMenu();
+        void SetupMenu() override;
 
-        void SetupTabs();
-        void AddTabForDocumentId(const AZ::Uuid& documentId);
-        void RemoveTabForDocumentId(const AZ::Uuid& documentId);
-        void UpdateTabForDocumentId(const AZ::Uuid& documentId);
+        void SetupTabs() override;
+        void AddTabForDocumentId(const AZ::Uuid& documentId) override;
+        void UpdateTabForDocumentId(const AZ::Uuid& documentId) override;
         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 = {};
         QAction* m_actionOpenRecent = {};
diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
index 3900720bf6..90a2e238a9 100644
--- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
+++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
@@ -38,29 +38,16 @@ 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);
-
         QVBoxLayout* vl = new QVBoxLayout(m_centralWidget);
         vl->setMargin(0);
         vl->setContentsMargins(0, 0, 0, 0);
@@ -144,7 +131,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);
@@ -188,8 +175,7 @@ namespace ShaderManagementConsole
 
     void ShaderManagementConsoleWindow::SetupMenu()
     {
-        // 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");
+        AtomToolsFramework::AtomToolsMainWindow::SetupMenu();
 
         m_actionOpen = m_menuFile->addAction("&Open...", [this]() {
             const AZStd::vector assetTypes = {
@@ -264,9 +250,9 @@ 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");
 
@@ -304,18 +290,7 @@ namespace ShaderManagementConsole
 
     void ShaderManagementConsoleWindow::SetupTabs()
     {
-        // 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();
-        });
+        AtomToolsFramework::AtomToolsMainWindow::SetupTabs();
 
         // 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
@@ -339,20 +314,7 @@ namespace ShaderManagementConsole
             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;
-            }
-        }
+        AtomToolsMainWindow::AddTabForDocumentId(documentId);
 
         // Create a new tab for the document ID and assign it's label to the file name of the document.
         AZStd::string absolutePath;
@@ -382,22 +344,6 @@ namespace ShaderManagementConsole
         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
@@ -434,20 +380,6 @@ namespace ShaderManagementConsole
         }
     }
 
-    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 +404,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);
diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h
index 5ab94aa34e..cb371bc4d6 100644
--- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h
+++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h
@@ -14,6 +14,7 @@
 
 #include 
 #include 
+#include 
 
 AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT
 #include 
@@ -42,13 +43,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 +63,13 @@ namespace ShaderManagementConsole
         void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override;
         void OnDocumentSaved(const AZ::Uuid& documentId) override;
 
-        void SetupMenu();
+        void SetupMenu() override; 
 
-        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 SetupTabs() override;
+        void AddTabForDocumentId(const AZ::Uuid& documentId) override;
+        void UpdateTabForDocumentId(const AZ::Uuid& documentId) override;
 
-        void OpenTabContextMenu();
-        void SelectPreviousTab();
-        void SelectNextTab();
+        void OpenTabContextMenu() override;
 
         void SelectDocumentForTab(const int tabIndex);
         void CloseDocumentForTab(const int tabIndex);
@@ -80,10 +79,6 @@ namespace ShaderManagementConsole
 
         void CreateDocumentContent(const AZ::Uuid& documentId, QStandardItemModel* model);
 
-        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;
@@ -91,7 +86,6 @@ namespace ShaderManagementConsole
         AzQtComponents::StyledDockWidget* m_assetBrowserDockWidget = nullptr;
         AzQtComponents::StyledDockWidget* m_pythonTerminalDockWidget = nullptr;
 
-        QMenu* m_menuFile = {};
         QMenu* m_menuNew = {};
         QAction* m_actionOpen = {};
         QAction* m_actionOpenRecent = {};
@@ -106,7 +100,7 @@ namespace ShaderManagementConsole
         QMenu* m_menuEdit = {};
         QAction* m_actionUndo = {};
         QAction* m_actionRedo = {};
-        QAction* m_actionPreferences = {};
+        QAction* m_actionSettings = {};
 
         QMenu* m_menuView = {};
         QAction* m_actionAssetBrowser = {};

From a241eb8e1cb21c141d1996fc929e6ca0242e8018 Mon Sep 17 00:00:00 2001
From: igarri 
Date: Mon, 2 Aug 2021 11:18:24 +0100
Subject: [PATCH 053/251] Added Sensible default

Signed-off-by: igarri 
---
 .../AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h      | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h
index abc3bf315b..d80e2bd093 100644
--- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h
+++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h
@@ -51,7 +51,7 @@ namespace AzToolsFramework
             int BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0);
 
         private:
-            int m_numberOfItemsDisplayed = 0;
+            int m_numberOfItemsDisplayed = 50;
             int m_displayedItemsCounter = 0;
             QPointer m_filterModel;
             QMap m_indexMap;

From e651f255772b11d01f1210178e6f567981dba36c Mon Sep 17 00:00:00 2001
From: Benjamin Jillich 
Date: Mon, 2 Aug 2021 13:17:34 +0200
Subject: [PATCH 054/251] Ported the render plugin, render update callback and
 render widget

Signed-off-by: Benjamin Jillich 
---
 .../Rendering/Common/RotateManipulator.h       |  2 +-
 .../Rendering/Common/TranslateManipulator.h    |  2 +-
 .../Source/BlendTreeRotationMath2Node.cpp      |  1 -
 .../Source/RenderPlugin/RenderPlugin.cpp       |  2 +-
 .../RenderPlugin/RenderUpdateCallback.cpp      |  7 +++----
 .../Source/RenderPlugin/RenderWidget.cpp       | 18 ++++++++----------
 .../Source/RenderPlugin/RenderWidget.h         | 12 ++++--------
 7 files changed, 18 insertions(+), 26 deletions(-)

diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h
index c6d719ae7c..5443bad219 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 
diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.h
index 362f6c19be..7bc0bacfe0 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"
diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp
index d01a6e5f0d..1f15333561 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp
@@ -105,7 +105,6 @@ namespace EMotionFX
         }
 
         // 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)
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 ab219b2b92..e4663750ce 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
@@ -915,7 +915,7 @@ namespace EMStudio
             }
 
             // get the mesh based AABB
-            AZ::Aabb aabb;
+            AZ::Aabb aabb = AZ::Aabb::CreateNull();
             actorInstance->CalcMeshBasedAabb(0, &aabb);
 
             // get the node based AABB
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..fed309d2e5 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
@@ -170,9 +170,8 @@ namespace EMStudio
             settings.mNodeBasedColor          = renderOptions->GetNodeAABBColor();
             settings.mStaticBasedColor        = renderOptions->GetStaticAABBColor();
             settings.mMeshBasedColor          = renderOptions->GetMeshAABBColor();
-            settings.mCollisionMeshBasedColor = renderOptions->GetCollisionMeshAABBColor();
 
-            renderUtil->RenderAABBs(actorInstance, settings);
+            renderUtil->RenderAabbs(actorInstance, settings);
         }
 
         if (widget->GetRenderFlag(RenderViewWidget::RENDER_OBB))
@@ -260,8 +259,8 @@ namespace EMStudio
         // render the selection
         if (renderOptions->GetRenderSelectionBox() && EMotionFX::GetActorManager().GetNumActorInstances() != 1 && mPlugin->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/RenderWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.cpp
index c74f693765..fb0ce4fdbf 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
@@ -72,9 +72,8 @@ namespace EMStudio
     }
 
     // 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;
@@ -82,9 +81,8 @@ namespace EMStudio
 
     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);
+        mViewCloseupAABB        = mPlugin->GetSceneAabb(selectedInstancesOnly);
         mViewCloseupFlightTime  = flightTime;
     }
 
@@ -603,14 +601,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;
@@ -1169,8 +1168,7 @@ namespace EMStudio
             mViewCloseupWaiting--;
             if (mViewCloseupWaiting == 0)
             {
-                mCamera->ViewCloseup(mViewCloseupAABB, mViewCloseupFlightTime);
-                //mViewCloseupWaiting = 0;
+                mCamera->ViewCloseup(MCore::AABB(mViewCloseupAABB.GetMin(), mViewCloseupAABB.GetMax()), mViewCloseupFlightTime);
             }
         }
 
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..10722f744a 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 
@@ -117,7 +116,7 @@ namespace EMStudio
         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);
+        void ViewCloseup(const AZ::Aabb& aabb, float flightTime, uint32 viewCloseupWaiting = 5);
         void ViewCloseup(bool selectedInstancesOnly, float flightTime, uint32 viewCloseupWaiting = 5);
         void SwitchCamera(CameraMode mode);
 
@@ -161,7 +160,7 @@ namespace EMStudio
 
         // used for closeup camera flights
         uint32                                  mViewCloseupWaiting;
-        MCore::AABB                             mViewCloseupAABB;
+        AZ::Aabb                                mViewCloseupAABB;
         float                                   mViewCloseupFlightTime;
 
         // manipulator helper data
@@ -175,6 +174,3 @@ namespace EMStudio
         int32                                   mPixelsMovedSinceRightClick;
     };
 } // namespace EMStudio
-
-
-#endif

From b840b24de2c018f0a50f4e580bad54dde07d88c2 Mon Sep 17 00:00:00 2001
From: Benjamin Jillich 
Date: Mon, 2 Aug 2021 14:38:20 +0200
Subject: [PATCH 055/251] Ported the actor and a few other places

* Fixed a bug with updating the static aabb for actors. It called that before the mesh was loaded resulting in an invalid aabb.
* Ported a few more places to AZ::Aabb from MCore::AABB

Signed-off-by: Benjamin Jillich 
---
 .../Code/Source/AtomActorInstance.cpp         |  9 ++---
 .../CommandSystem/Source/ActorCommands.cpp    |  9 ++---
 .../ExporterLib/Exporter/NodeExport.cpp       | 12 +++---
 .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 38 +++++++++----------
 Gems/EMotionFX/Code/EMotionFX/Source/Actor.h  | 10 ++---
 5 files changed, 37 insertions(+), 41 deletions(-)

diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp
index 706ed27a4d..f9c0242b77 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)
diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp
index a21b618b91..52a4ec6a0b 100644
--- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp
@@ -1063,11 +1063,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);
diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp
index a9010fb524..c66c3ca8ef 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp
@@ -184,12 +184,12 @@ namespace ExporterLib
         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();
+        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();
 
         // endian conversion and write it
         ConvertUnsignedInt(&nodesChunk.mNumNodes, targetEndianType);
diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp
index 973d8eb460..c55509e817 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp
@@ -97,6 +97,7 @@ namespace EMotionFX
         mID                         = MCore::GetIDGenerator().GenerateID();
         mUnitType                   = GetEMotionFX().GetUnitType();
         mFileUnitType               = mUnitType;
+        m_staticAabb                = AZ::Aabb::CreateNull();
 
         mUsedForVisualization       = false;
         mDirtyFlag                  = false;
@@ -148,7 +149,7 @@ namespace EMotionFX
         result->mMotionExtractionNode   = mMotionExtractionNode;
         result->mUnitType               = mUnitType;
         result->mFileUnitType           = mFileUnitType;
-        result->mStaticAABB             = mStaticAABB;
+        result->m_staticAabb            = m_staticAabb;
         result->mRetargetRootNode       = mRetargetRootNode;
         result->mInvBindPoseTransforms  = mInvBindPoseTransforms;
         result->m_optimizeSkeleton      = m_optimizeSkeleton;
@@ -1405,10 +1406,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)
         {
@@ -1526,6 +1523,10 @@ namespace EMotionFX
                     mMorphSetups[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 +1535,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, mThreadIndex);
+        actorInstance->UpdateMeshDeformers(0.0f);
+        actorInstance->UpdateStaticBasedAabbDimensions();
+        actorInstance->GetStaticBasedAabb(&m_staticAabb);
+        actorInstance->Destroy();
     }
 
 
@@ -2206,14 +2204,14 @@ namespace EMotionFX
 #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;
     }
 
     //---------------------------------
@@ -2422,8 +2420,8 @@ namespace EMotionFX
         }
 
         // 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();
diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h
index 6c3ab6bf29..53cbe7e05a 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h
@@ -16,11 +16,11 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
 // include MCore related files
-#include 
 #include 
 #include 
 #include 
@@ -781,9 +781,9 @@ namespace EMotionFX
         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; }
@@ -985,7 +985,7 @@ namespace EMotionFX
         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. */
+        AZ::Aabb                                        m_staticAabb;               /**< 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. */
         bool                                            m_optimizeSkeleton;         /**< Indicates if we should perform/ */

From b9cfce8165fd368018a6ea73f25f42828f523899 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 09:26:06 -0700
Subject: [PATCH 056/251] Gems/AtomLyIntegration

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Platform/Windows/FFontXML_Windows.cpp     |  7 +++-
 .../AtomFont/Code/Source/FFont.cpp            | 42 ++++++++++++-------
 .../AtomFont/Code/Source/FontRenderer.cpp     |  7 ++--
 .../AtomFont/Code/Source/FontTexture.cpp      | 10 ++---
 .../AtomFont/Code/Source/GlyphCache.cpp       |  2 +-
 .../Source/AnimGraph/GameController.cpp       | 21 +++++-----
 6 files changed, 53 insertions(+), 36 deletions(-)

diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
index 4c923c43c4..dc7c6ccbb2 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
@@ -9,6 +9,7 @@
 #include 
 
 #include 
+#include 
 
 #include 
 
@@ -16,11 +17,13 @@ namespace AtomFontInternal
 {
     void XmlFontShader::FoundElementImpl()
     {
-        TCHAR sysFontPath[MAX_PATH];
-        if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPath)))
+        wchar_t sysFontPathW[MAX_PATH];
+        if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPathW)))
         {
             const AZ::IO::PathView fontName = AZ::IO::PathView(m_strFontPath.c_str()).Filename();
 
+            AZStd::string sysFontPath;
+            AZStd::to_string(sysFontPath, sysFontPathW);
             AZ::IO::Path newFontPath(sysFontPath);
             newFontPath /= fontName;
             m_font->Load(newFontPath.c_str(), m_FontTexSize.x, m_FontTexSize.y, m_slotSizes.x, m_slotSizes.y, CreateTTFFontFlag(m_FontSmoothMethod, m_FontSmoothAmount), m_SizeRatio);
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
index ddb2fa6292..fe6f733abc 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
@@ -13,6 +13,8 @@
 
 #if !defined(USE_NULLFONT_ALWAYS)
 
+#include 
+
 #include 
 #include 
 #include 
@@ -26,7 +28,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 
 #include 
@@ -409,6 +410,9 @@ Vec2 AZ::FFont::GetTextSizeUInternal(
     const size_t fxIdx = ctx.m_fxIdx < fxSize ? ctx.m_fxIdx : 0;
     const FontEffect& fx = m_effects[fxIdx];
 
+    AZStd::wstring strW;
+    AZStd::to_wstring(strW, str);
+
     for (size_t i = 0, numPasses = fx.m_passes.size(); i < numPasses; ++i)
     {
         const FontRenderingPass* pass = &fx.m_passes[numPasses - i - 1];
@@ -426,7 +430,7 @@ Vec2 AZ::FFont::GetTextSizeUInternal(
 
         // parse the string, ignoring control characters
         uint32_t nextCh = 0;
-        Unicode::CIterator pChar(str);
+        const wchar_t* pChar = strW.c_str();
         while (uint32_t ch = *pChar)
         {
             ++pChar;
@@ -556,6 +560,9 @@ uint32_t AZ::FFont::GetNumQuadsForText(const char* str, const bool asciiMultiLin
     const size_t fxIdx = ctx.m_fxIdx < fxSize ? ctx.m_fxIdx : 0;
     const FontEffect& fx = m_effects[fxIdx];
 
+    AZStd::wstring strW;
+    AZStd::to_wstring(strW, str);
+
     for (size_t j = 0, numPasses = fx.m_passes.size(); j < numPasses; ++j)
     {
         size_t i = numPasses - j - 1;
@@ -567,7 +574,7 @@ uint32_t AZ::FFont::GetNumQuadsForText(const char* str, const bool asciiMultiLin
         }
 
         uint32_t nextCh = 0;
-        Unicode::CIterator pChar(str);
+        const wchar_t* pChar = strW.c_str();
         while (uint32_t ch = *pChar)
         {
             ++pChar;
@@ -862,9 +869,12 @@ int AZ::FFont::CreateQuadsForText(const RHI::Viewport& viewport, float x, float
             }
         }
 
+        AZStd::wstring strW;
+        AZStd::to_wstring(strW, str);
+
         // parse the string, ignoring control characters
         uint32_t nextCh = 0;
-        Unicode::CIterator pChar(str);
+        const wchar_t* pChar = strW.c_str();
         while (uint32_t ch = *pChar)
         {
             ++pChar;
@@ -1188,7 +1198,7 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
     const bool multiLine = strSize.y > GetRestoredFontSize(ctx).y;
 
     int lastSpace = -1;
-    const char* pLastSpace = NULL;
+    const wchar_t* pLastSpace = NULL;
     float lastSpaceWidth = 0.0f;
 
     float curCharWidth = 0.0f;
@@ -1197,7 +1207,9 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
     float widthSum = 0.0f;
 
     int curChar = 0;
-    Unicode::CIterator pChar(result.c_str());
+    AZStd::wstring resultW;
+    AZStd::to_wstring(resultW, result.c_str());
+    const wchar_t* pChar = resultW.c_str();
     while (uint32_t ch = *pChar)
     {
         // Dollar sign escape codes.  The following scenarios can happen with dollar signs embedded in a string.
@@ -1224,7 +1236,7 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
         // get char width and sum it to the line width
         // Note: This is not unicode compatible, since char-width depends on surrounding context (ie, combining diacritics etc)
         char codepoint[5];
-        Unicode::Convert(codepoint, ch);
+        AZStd::to_string(codepoint, 5, (wchar_t*)&ch, 1);
         curCharWidth = GetTextSize(codepoint, true, ctx).x;
 
         // keep track of spaces
@@ -1233,15 +1245,15 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
         {
             lastSpace = curChar;
             lastSpaceWidth = curLineWidth + curCharWidth;
-            pLastSpace = pChar.GetPosition();
+            pLastSpace = pChar;
             assert(*pLastSpace == ' ');
         }
 
         bool prevCharWasNewline = false;
-        const bool notFirstChar = pChar.GetPosition() != result.c_str();
+        const bool notFirstChar = pChar != resultW.c_str();
         if (*pChar && notFirstChar)
         {
-            const char* pPrevCharStr = pChar.GetPosition() - 1;
+            const wchar_t* pPrevCharStr = pChar - 1;
             prevCharWasNewline = pPrevCharStr[0] == '\n';
         }
 
@@ -1268,12 +1280,12 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
             }
             else
             {
-                const char* buf = pChar.GetPosition();
-                size_t bytesProcessed = buf - result.c_str();
-                result.insert(bytesProcessed, '\n'); // Insert the newline, this invalidates the iterator
-                buf = result.c_str() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
+                const wchar_t* buf = pChar;
+                size_t bytesProcessed = buf - resultW.c_str();
+                resultW.insert(resultW.begin() + bytesProcessed, L'\n'); // Insert the newline, this invalidates the iterator
+                buf = resultW.c_str() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
                 assert(*buf == '\n');
-                pChar.SetPosition(buf); // pChar once again points inside the target string, at the current character
+                pChar = buf; // pChar once again points inside the target string, at the current character
                 assert(*pChar == ch);
                 ++pChar;
                 ++curChar;
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
index 101a506ddc..17ac896cf7 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
@@ -22,6 +22,8 @@
 
 #include 
 
+#include 
+
 // Sizes are defined in in 26.6 fixed float format (TT_F26Dot6), where
 // 1 unit is 1/64 of a pixel.
 constexpr int FractionalPixelUnits = 64;
@@ -94,7 +96,7 @@ AZ::FontRenderer::~FontRenderer()
 }
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontRenderer::LoadFromFile(const string& fileName)
+int AZ::FontRenderer::LoadFromFile(const AZStd::string& fileName)
 {
     int iError = FT_Init_FreeType(&m_library);
 
@@ -309,8 +311,7 @@ Vec2 AZ::FontRenderer::GetKerning(uint32_t leftGlyph, uint32_t rightGlyph)
 #if !defined(_RELEASE)
         if (0 != ftError)
         {
-            string warnMsg;
-            warnMsg.Format("FT_Get_Kerning returned %d", ftError);
+            AZStd::string warnMsg = AZStd::string::format("FT_Get_Kerning returned %d", ftError);
             CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, warnMsg.c_str());
         }
 #endif
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp
index 6008881ec3..1ee7f80eda 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp
@@ -14,8 +14,8 @@
 #if !defined(USE_NULLFONT_ALWAYS)
 
 #include 
-#include 
 #include 
+#include 
 
 //-------------------------------------------------------------------------------------------------
 AZ::FontTexture::FontTexture()
@@ -44,7 +44,7 @@ AZ::FontTexture::~FontTexture()
 }
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontTexture::CreateFromFile(const string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCellCount, int heightCellCount)
+int AZ::FontTexture::CreateFromFile(const AZStd::string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCellCount, int heightCellCount)
 {
     if (!m_glyphCache.LoadFontFromFile(fileName))
     {
@@ -255,10 +255,10 @@ int AZ::FontTexture::PreCacheString(const char* string, int* updated, float size
     uint16_t slotUsage = m_slotUsage++;
     int updateCount = 0;
 
-    uint32_t character;
-    for (Unicode::CIterator it(string); *it; ++it)
+    AZStd::wstring stringW;
+    AZStd::to_wstring(stringW, string);
+    for (wchar_t character : stringW)
     {
-        character = *it;
         TextureSlot* slot = GetCharSlot(character, clampedGlyphSize);
 
         if (!slot)
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp
index 12ebd99183..ee52d36af5 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp
@@ -124,7 +124,7 @@ int AZ::GlyphCache::Release()
 }
 
 //-------------------------------------------------------------------------------------------------
-int AZ::GlyphCache::LoadFontFromFile(const string& fileName)
+int AZ::GlyphCache::LoadFontFromFile(const AZStd::string & fileName)
 {
     return m_fontRenderer.LoadFromFile(fileName);
 }
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..c3b929ae7a 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
@@ -12,6 +12,7 @@
 #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER
 
 #include 
+#include 
 
 
 // joystick enum callback
@@ -20,7 +21,7 @@ BOOL CALLBACK GameController::EnumJoysticksCallback(const DIDEVICEINSTANCE* pdid
     GameController* manager = static_cast(pContext);
 
     // store the name
-    manager->mDeviceInfo.mName = pdidInstance->tszProductName;
+    AZStd::to_string(manager->mDeviceInfo.mName, 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.
@@ -71,7 +72,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_XAxis)
     {
-        manager->mDeviceElements[ ELEM_POS_X ].mName                = pdidoi->tszName;
+        AZStd::to_string(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;
@@ -81,7 +82,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_YAxis)
     {
-        manager->mDeviceElements[ ELEM_POS_Y ].mName                = pdidoi->tszName;
+        AZStd::to_string(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;
@@ -91,7 +92,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_ZAxis)
     {
-        manager->mDeviceElements[ ELEM_POS_Z ].mName                = pdidoi->tszName;
+        AZStd::to_string(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;
@@ -101,7 +102,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_RxAxis)
     {
-        manager->mDeviceElements[ ELEM_ROT_X ].mName                = pdidoi->tszName;
+        AZStd::to_string(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;
@@ -111,7 +112,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_RyAxis)
     {
-        manager->mDeviceElements[ ELEM_ROT_Y ].mName                = pdidoi->tszName;
+        AZStd::to_string(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;
@@ -121,7 +122,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_RzAxis)
     {
-        manager->mDeviceElements[ ELEM_ROT_Z ].mName                = pdidoi->tszName;
+        AZStd::to_string(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;
@@ -134,7 +135,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
     {
         if (manager->mDeviceInfo.mNumSliders == 0)
         {
-            manager->mDeviceElements[ ELEM_SLIDER_1 ].mName                 = pdidoi->tszName;
+            AZStd::to_string(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;
@@ -142,7 +143,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
         }
         else
         {
-            manager->mDeviceElements[ ELEM_SLIDER_2 ].mName                 = pdidoi->tszName;
+            AZStd::to_string(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;
@@ -156,7 +157,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
     if (pdidoi->guidType == GUID_POV)
     {
         const uint32 povIndex = manager->mDeviceInfo.mNumPOVs;
-        manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mName                 = pdidoi->tszName;
+        AZStd::to_string(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;

From db7536acda4583ff46d2e4f84618e086f2577565 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 11:44:34 -0700
Subject: [PATCH 057/251] Gems/Maestro

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Export/ExportManager.cpp          |  2 +-
 Code/Editor/TrackView/CommentNodeAnimator.cpp |  2 +-
 .../TrackView/TrackViewDopeSheetBase.cpp      |  6 ++---
 Code/Editor/TrackView/TrackViewNodes.cpp      |  2 +-
 Code/Legacy/CryCommon/ISurfaceType.h          | 14 +++++------
 Code/Legacy/CryCommon/Mocks/IRendererMock.h   |  2 +-
 Code/Legacy/CryCommon/Mocks/ISystemMock.h     |  2 +-
 Code/Legacy/CryCommon/WinBase.cpp             | 10 ++++----
 Code/Legacy/CryCommon/platform_impl.cpp       |  2 +-
 Code/Legacy/CrySystem/XConsole.cpp            |  2 +-
 .../Support/include/CrashSupport.h            | 24 ++++++++-----------
 .../Components/BlastSystemComponent.cpp       |  1 +
 .../Animation/UiAnimViewDopeSheetBase.cpp     |  6 ++---
 .../Source/Cinematics/AnimComponentNode.h     |  6 ++---
 .../Code/Source/Cinematics/AnimPostFXNode.cpp |  2 +-
 .../Code/Source/Cinematics/AnimSequence.cpp   | 17 ++-----------
 .../Code/Source/Cinematics/AnimSequence.h     |  2 +-
 .../Source/Cinematics/CompoundSplineTrack.cpp | 10 ++++----
 .../Source/Cinematics/CompoundSplineTrack.h   |  2 +-
 .../Code/Source/Cinematics/EventTrack.cpp     |  4 ++--
 .../Code/Source/Cinematics/MaterialNode.h     |  2 +-
 Gems/Maestro/Code/Source/Cinematics/Movie.cpp | 23 +++++++++---------
 .../Code/Source/Cinematics/SceneNode.cpp      |  4 ++--
 .../Source/Cinematics/ScreenFaderTrack.cpp    |  2 +-
 .../Source/Cinematics/TrackEventTrack.cpp     |  4 ++--
 25 files changed, 68 insertions(+), 85 deletions(-)

diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp
index 03aa0bed8b..5ba250c960 100644
--- a/Code/Editor/Export/ExportManager.cpp
+++ b/Code/Editor/Export/ExportManager.cpp
@@ -46,7 +46,7 @@ namespace
         SEfResTexture* pTex = pRes->GetTextureResource(nSlot);
         if (pTex)
         {
-            cry_strcat(outName, Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data());
+            azstrcat(outName, Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data());
         }
     }
 
diff --git a/Code/Editor/TrackView/CommentNodeAnimator.cpp b/Code/Editor/TrackView/CommentNodeAnimator.cpp
index 47f4c5d9ae..579bba00ef 100644
--- a/Code/Editor/TrackView/CommentNodeAnimator.cpp
+++ b/Code/Editor/TrackView/CommentNodeAnimator.cpp
@@ -92,7 +92,7 @@ void CCommentNodeAnimator::AnimateCommentTextTrack(CTrackViewTrack* pTrack, cons
         if (commentKey.m_duration > 0 && ac.time < keyHandle.GetTime() + commentKey.m_duration)
         {
             m_commentContext.m_strComment = commentKey.m_strComment;
-            cry_strcpy(m_commentContext.m_strFont,  commentKey.m_strFont.c_str());
+            azstrcpy(m_commentContext.m_strFont,  commentKey.m_strFont.c_str());
             m_commentContext.m_color = commentKey.m_color;
             m_commentContext.m_align = commentKey.m_align;
             m_commentContext.m_size = commentKey.m_size;
diff --git a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
index 34ca2f062f..f66bb19bf3 100644
--- a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
+++ b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
@@ -2808,10 +2808,10 @@ void CTrackViewDopeSheetBase::DrawKeys(CTrackViewTrack* pTrack, QPainter* painte
                 }
                 else
                 {
-                    cry_strcpy(keydesc, "{");
+                    azstrcpy(keydesc, "{");
                 }
-                cry_strcat(keydesc, pDescription);
-                cry_strcat(keydesc, "}");
+                azstrcat(keydesc, pDescription);
+                azstrcat(keydesc, "}");
                 // Draw key description text.
                 // Find next key.
                 const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom()));
diff --git a/Code/Editor/TrackView/TrackViewNodes.cpp b/Code/Editor/TrackView/TrackViewNodes.cpp
index d69c256049..90e5598876 100644
--- a/Code/Editor/TrackView/TrackViewNodes.cpp
+++ b/Code/Editor/TrackView/TrackViewNodes.cpp
@@ -2516,7 +2516,7 @@ int CTrackViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, cons
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        cry_strcpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)
diff --git a/Code/Legacy/CryCommon/ISurfaceType.h b/Code/Legacy/CryCommon/ISurfaceType.h
index db5ec4eed4..10bddbbe6c 100644
--- a/Code/Legacy/CryCommon/ISurfaceType.h
+++ b/Code/Legacy/CryCommon/ISurfaceType.h
@@ -85,7 +85,7 @@ struct ISurfaceType
     };
     struct SBreakable2DParams
     {
-        string particle_effect;
+        AZStd::string particle_effect;
         float blast_radius;
         float blast_radius_first;
         float vert_size_spread;
@@ -97,12 +97,12 @@ struct ISurfaceType
         float shard_density;
         int use_edge_alpha;
         float crack_decal_scale;
-        string crack_decal_mtl;
+        AZStd::string crack_decal_mtl;
         float max_fracture;
-        string full_fracture_fx;
-        string fracture_fx;
+        AZStd::string full_fracture_fx;
+        AZStd::string fracture_fx;
         int no_procedural_full_fracture;
-        string broken_mtl;
+        AZStd::string broken_mtl;
         float destroy_timeout;
         float destroy_timeout_spread;
 
@@ -125,8 +125,8 @@ struct ISurfaceType
     };
     struct SBreakageParticles
     {
-        string type;
-        string particle_effect;
+        AZStd::string type;
+        AZStd::string particle_effect;
         int count_per_unit;
         float count_scale;
         float scale;
diff --git a/Code/Legacy/CryCommon/Mocks/IRendererMock.h b/Code/Legacy/CryCommon/Mocks/IRendererMock.h
index ff3550a738..be9c1eec8b 100644
--- a/Code/Legacy/CryCommon/Mocks/IRendererMock.h
+++ b/Code/Legacy/CryCommon/Mocks/IRendererMock.h
@@ -283,7 +283,7 @@ public:
     MOCK_METHOD0(EF_GetShaderMissLogPath,
         const char*());
     MOCK_METHOD1(EF_GetShaderNames,
-        string * (int& nNumShaders));
+        AZStd::string * (int& nNumShaders));
     MOCK_METHOD1(EF_ReloadFile,
         bool(const char* szFileName));
     MOCK_METHOD1(EF_ReloadFile_Request,
diff --git a/Code/Legacy/CryCommon/Mocks/ISystemMock.h b/Code/Legacy/CryCommon/Mocks/ISystemMock.h
index d891365696..9e4b7c99ec 100644
--- a/Code/Legacy/CryCommon/Mocks/ISystemMock.h
+++ b/Code/Legacy/CryCommon/Mocks/ISystemMock.h
@@ -122,7 +122,7 @@ public:
         const SFileVersion&());
 
     MOCK_METHOD1(AddCVarGroupDirectory,
-        void(const string&));
+        void(const AZStd::string&));
     MOCK_METHOD0(SaveConfiguration,
         void());
     MOCK_METHOD3(LoadConfiguration,
diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp
index a60dbdf00b..fe9c539569 100644
--- a/Code/Legacy/CryCommon/WinBase.cpp
+++ b/Code/Legacy/CryCommon/WinBase.cpp
@@ -349,23 +349,23 @@ void _makepath(char* path, const char* drive, const char* dir, const char* filen
     }
     if (dir && dir[0])
     {
-        cry_strcat(tmp, dir);
+        azstrcat(tmp, dir);
         ch = tmp[strlen(tmp) - 1];
         if (ch != '/' && ch != '\\')
         {
-            cry_strcat(tmp, "\\");
+            azstrcat(tmp, "\\");
         }
     }
     if (filename && filename[0])
     {
-        cry_strcat(tmp, filename);
+        azstrcat(tmp, filename);
         if (ext && ext[0])
         {
             if (ext[0] != '.')
             {
-                cry_strcat(tmp, ".");
+                azstrcat(tmp, ".");
             }
-            cry_strcat(tmp, ext);
+            azstrcat(tmp, ext);
         }
     }
     azstrcpy(path, strlen(tmp) + 1, tmp);
diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp
index 6badd2fe1e..1523622538 100644
--- a/Code/Legacy/CryCommon/platform_impl.cpp
+++ b/Code/Legacy/CryCommon/platform_impl.cpp
@@ -499,7 +499,7 @@ inline void CryDebugStr([[maybe_unused]] const char* format, ...)
      va_start(ArgList, format);
      azvsnprintf(szBuffer,sizeof(szBuffer)-1, format, ArgList);
      va_end(ArgList);
-     cry_strcat(szBuffer,"\n");
+     azstrcat(szBuffer,"\n");
      OutputDebugString(szBuffer);
      #endif
      */
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index f5e946be43..2348e78a0e 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -1545,7 +1545,7 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags)
     static char sFlags[256];
 
     // hiding this makes it a bit more difficult for cheaters
-    //  if(dwFlags&VF_CHEAT)                  cry_strcat( sFlags,"CHEAT, ");
+    //  if(dwFlags&VF_CHEAT)                  azstrcat( sFlags,"CHEAT, ");
 
     azstrcpy(sFlags, "");
 
diff --git a/Code/Tools/CrashHandler/Support/include/CrashSupport.h b/Code/Tools/CrashHandler/Support/include/CrashSupport.h
index 9932d950d4..1393930913 100644
--- a/Code/Tools/CrashHandler/Support/include/CrashSupport.h
+++ b/Code/Tools/CrashHandler/Support/include/CrashSupport.h
@@ -11,6 +11,8 @@
 #pragma once
 
 #include 
+#include 
+#include 
 
 #include 
 #include 
@@ -23,30 +25,24 @@
 namespace CrashHandler
 {
     std::string GetTimeString();
-    void GetExecutablePathA(char* pathBuffer, int& bufferSize);
-    void GetExecutablePathW(wchar_t* pathBuffer, int& bufferSize);
     void GetTimeInfo(tm& curTime);
 
-    template 
-    inline void GetExecutablePath(T& returnPath)
+    inline void GetExecutablePath(std::string& returnPath)
     {
         char currentFileName[CRASH_HANDLER_MAX_PATH_LEN] = { 0 };
-        int bufferLen{ CRASH_HANDLER_MAX_PATH_LEN };
-        GetExecutablePathA(currentFileName, bufferLen);
+        AZ::Utils::GetExecutablePath(currentFileName, CRASH_HANDLER_MAX_PATH_LEN);
 
         returnPath = currentFileName;
         std::replace(returnPath.begin(), returnPath.end(), '\\', '/');
     }
 
-    template <>
-    inline void GetExecutablePath(std::wstring& returnPath)
+    inline void GetExecutablePath(std::wstring& returnPathW)
     {
-        wchar_t currentFileName[CRASH_HANDLER_MAX_PATH_LEN] = { 0 };
-        int bufferLen{ CRASH_HANDLER_MAX_PATH_LEN };
-        GetExecutablePathW(currentFileName, bufferLen);
-
-        returnPath = currentFileName;
-        std::replace(returnPath.begin(), returnPath.end(), '\\', '/');
+        std::string returnPath;
+        GetExecutablePath(returnPath);
+        wchar_t currentFileNameW[CRASH_HANDLER_MAX_PATH_LEN] = { 0 };
+        AZStd::to_wstring(currentFileNameW, CRASH_HANDLER_MAX_PATH_LEN, returnPath.c_str(), returnPath.size());
+        returnPathW = currentFileNameW;
     }
 
     template
diff --git a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp
index 933633b5e3..bee94ed116 100644
--- a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp
+++ b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp
@@ -32,6 +32,7 @@
 #include 
 #include 
 #endif
+#include 
 
 namespace Blast
 {
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
index f9ce0e522f..ae0880e98e 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
@@ -2362,10 +2362,10 @@ void CUiAnimViewDopeSheetBase::DrawKeys(CUiAnimViewTrack* pTrack, QPainter* pain
                 }
                 else
                 {
-                    cry_strcpy(keydesc, "{");
+                    azstrcpy(keydesc, "{");
                 }
-                cry_strcat(keydesc, pDescription);
-                cry_strcat(keydesc, "}");
+                azstrcat(keydesc, pDescription);
+                azstrcat(keydesc, "}");
                 // Draw key description text.
                 // Find next key.
                 const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom()));
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h b/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h
index 4df6021aa9..5ad3ab6f94 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h
@@ -144,7 +144,7 @@ private:
     {
     public:
         BehaviorPropertyInfo() {}
-        BehaviorPropertyInfo(const string& name)
+        BehaviorPropertyInfo(const AZStd::string& name)
         {
             *this = name;
         }
@@ -154,7 +154,7 @@ private:
             m_animNodeParamInfo.paramType = other.m_displayName;
             m_animNodeParamInfo.name = &m_displayName[0];
         }
-        BehaviorPropertyInfo& operator=(const string& str)
+        BehaviorPropertyInfo& operator=(const AZStd::string& str)
         {
             // TODO: clean this up - this weird memory sharing was copied from legacy Cry - could be better.
             m_displayName = str;
@@ -163,7 +163,7 @@ private:
             return *this;
         }
 
-        string     m_displayName;
+        AZStd::string m_displayName;
         SParamInfo m_animNodeParamInfo;
     };
     
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp
index 78d878c0eb..fd7f99c9b3 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp
@@ -39,7 +39,7 @@ public:
         virtual void GetDefault(bool& val) const = 0;
         virtual void GetDefault(Vec4& val) const = 0;
 
-        string m_name;
+        AZStd::string m_name;
 
     protected:
         virtual ~CControlParamBase(){}
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp
index e9f77f7947..23017e5779 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp
@@ -98,10 +98,10 @@ void CAnimSequence::SetName(const char* name)
         return;   // should never happen, null pointer guard
     }
 
-    string originalName = GetName();
+    AZStd::string originalName = GetName();
 
     m_name = name;
-    m_pMovieSystem->OnSequenceRenamed(originalName, m_name.c_str());
+    m_pMovieSystem->OnSequenceRenamed(originalName.c_str(), m_name.c_str());
 
     // the sequence named LIGHT_ANIMATION_SET_NAME is a singleton sequence to hold all light animations.
     if (m_name == LIGHT_ANIMATION_SET_NAME)
@@ -744,9 +744,6 @@ void CAnimSequence::Deactivate()
         static_cast(animNode)->OnReset();
     }
 
-    // Remove a possibly cached game hint associated with this anim sequence.
-    stack_string sTemp("anim_sequence_");
-    sTemp += m_name.c_str();
     // Audio: Release precached sound
 
     m_bActive = false;
@@ -776,16 +773,6 @@ void CAnimSequence::PrecacheStatic(const float startTime)
         return;
     }
 
-    // Try to cache this sequence's game hint if one exists.
-    stack_string sTemp("anim_sequence_");
-    sTemp += m_name.c_str();
-
-    //if (gEnv->pAudioSystem)
-    {
-        // Make sure to use the non-serializable game hint type as trackview sequences get properly reactivated after load
-        // Audio: Precache sound
-    }
-
     gEnv->pLog->Log("=== Precaching render data for cutscene: %s ===", GetName());
 
     m_precached = true;
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h
index 2c12f6e5ea..f69017c3a6 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h
@@ -174,7 +174,7 @@ private:
 
     uint32 m_id;
     AZStd::string m_name;
-    mutable string m_fullNameHolder;
+    mutable AZStd::string m_fullNameHolder;
     Range m_timeRange;
     TrackEvents m_events;
 
diff --git a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
index 4dd52a734a..62de2dfdf5 100644
--- a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
@@ -457,31 +457,31 @@ void CCompoundSplineTrack::GetKeyInfo(int key, const char*& description, float&
         {
             float dummy;
             m_subTracks[0]->GetKeyInfo(m, subDesc, dummy);
-            cry_strcat(str, subDesc);
+            azstrcat(str, subDesc);
             break;
         }
     }
     if (m == m_subTracks[0]->GetNumKeys())
     {
-        cry_strcat(str, m_subTrackNames[0].c_str());
+        azstrcat(str, m_subTrackNames[0].c_str());
     }
     // Tail cases
     for (int i = 1; i < GetSubTrackCount(); ++i)
     {
-        cry_strcat(str, ",");
+        azstrcat(str, ",");
         for (m = 0; m < m_subTracks[i]->GetNumKeys(); ++m)
         {
             if (m_subTracks[i]->GetKeyTime(m) == time)
             {
                 float dummy;
                 m_subTracks[i]->GetKeyInfo(m, subDesc, dummy);
-                cry_strcat(str, subDesc);
+                azstrcat(str, subDesc);
                 break;
             }
         }
         if (m == m_subTracks[i]->GetNumKeys())
         {
-            cry_strcat(str, m_subTrackNames[i].c_str());
+            azstrcat(str, m_subTrackNames[i].c_str());
         }
     }
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h
index f22b0fb144..b0a2733316 100644
--- a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h
+++ b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h
@@ -108,7 +108,7 @@ public:
 
     virtual int NextKeyByTime(int key) const;
 
-    void SetSubTrackName(const int i, const string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
+    void SetSubTrackName(const int i, const AZStd::string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
 
 #ifdef MOVIESYSTEM_SUPPORT_EDITING
     virtual ColorB GetCustomColor() const
diff --git a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
index 278833cfe2..36d468e36d 100644
--- a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
@@ -72,8 +72,8 @@ void CEventTrack::GetKeyInfo(int key, const char*& description, float& duration)
     azstrcpy(desc, m_keys[key].event.c_str());
     if (!m_keys[key].eventValue.empty())
     {
-        cry_strcat(desc, ", ");
-        cry_strcat(desc, m_keys[key].eventValue.c_str());
+        azstrcat(desc, ", ");
+        azstrcat(desc, m_keys[key].eventValue.c_str());
     }
 
     description = desc;
diff --git a/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h b/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h
index 51d1b8be15..003312c426 100644
--- a/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h
+++ b/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h
@@ -58,7 +58,7 @@ private:
     float m_fMaxKeyValue;
 
     std::vector< CAnimNode::SParamInfo > m_dynamicShaderParamInfos;
-    typedef AZStd::unordered_map< string, size_t, stl::hash_string_caseless, stl::equality_string_caseless > TDynamicShaderParamsMap;
+    typedef AZStd::unordered_map, stl::equality_string_caseless > TDynamicShaderParamsMap;
     TDynamicShaderParamsMap m_nameToDynamicShaderParam;
 };
 
diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
index a6d9e47eb1..b7fb82e0e7 100644
--- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
@@ -75,19 +75,19 @@ static SMovieSequenceAutoComplete s_movieSequenceAutoComplete;
 // Serialization for anim nodes & param types
 #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(AnimNodeType::name) == g_animNodeEnumToStringMap.end()); \
     g_animNodeEnumToStringMap[AnimNodeType::name] = STRINGIFY(name);                                                            \
-    g_animNodeStringToEnumMap[string(STRINGIFY(name))] = AnimNodeType::name;
+    g_animNodeStringToEnumMap[AZStd::string(STRINGIFY(name))] = AnimNodeType::name;
 
 #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(AnimParamType::name) == g_animParamEnumToStringMap.end()); \
     g_animParamEnumToStringMap[AnimParamType::name] = STRINGIFY(name);                                                              \
-    g_animParamStringToEnumMap[string(STRINGIFY(name))] = AnimParamType::name;
+    g_animParamStringToEnumMap[AZStd::string(STRINGIFY(name))] = AnimParamType::name;
 
 namespace
 {
-    AZStd::unordered_map g_animNodeEnumToStringMap;
-    StaticInstance >> g_animNodeStringToEnumMap;
+    AZStd::unordered_map g_animNodeEnumToStringMap;
+    StaticInstance >> g_animNodeStringToEnumMap;
 
-    AZStd::unordered_map g_animParamEnumToStringMap;
-    StaticInstance >> g_animParamStringToEnumMap;
+    AZStd::unordered_map g_animParamEnumToStringMap;
+    StaticInstance >> g_animParamStringToEnumMap;
 
     // If you get an assert in this function, it means two node types have the same enum value.
     void RegisterNodeTypes()
@@ -1479,8 +1479,7 @@ void CMovieSystem::GoToFrame(const char* seqName, float targetFrame)
 
     if (gEnv->IsEditor() && gEnv->IsEditorGameMode() == false)
     {
-        string editorCmd;
-        editorCmd.Format("mov_goToFrameEditor %s %f", seqName, targetFrame);
+        AZStd::string editorCmd = AZStd::string::format("mov_goToFrameEditor %s %f", seqName, targetFrame);
         gEnv->pConsole->ExecuteString(editorCmd.c_str());
         return;
     }
@@ -1679,7 +1678,7 @@ void CMovieSystem::SerializeNodeType(AnimNodeType& animNodeType, XmlNodeRef& xml
     {
         const char* pTypeString = "Invalid";
         assert(g_animNodeEnumToStringMap.find(animNodeType) != g_animNodeEnumToStringMap.end());
-        pTypeString = g_animNodeEnumToStringMap[animNodeType];
+        pTypeString = g_animNodeEnumToStringMap[animNodeType].c_str();
         xmlNode->setAttr(kType, pTypeString);
     }
 }
@@ -1780,7 +1779,7 @@ void CMovieSystem::SaveParamTypeToXml(const CAnimParamType& animParamType, XmlNo
         }
 
         assert(g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end());
-        pTypeString = g_animParamEnumToStringMap[animParamType.m_type];
+        pTypeString = g_animParamEnumToStringMap[animParamType.m_type].c_str();
     }
 
     xmlNode->setAttr(kParamType, pTypeString);
@@ -1815,7 +1814,7 @@ const char* CMovieSystem::GetParamTypeName(const CAnimParamType& animParamType)
     {
         if (g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end())
         {
-            return g_animParamEnumToStringMap[animParamType.m_type];
+            return g_animParamEnumToStringMap[animParamType.m_type].c_str();
         }
     }
 
@@ -1970,7 +1969,7 @@ CLightAnimWrapper* CLightAnimWrapper::FindLightAnim(const char* name)
 //////////////////////////////////////////////////////////////////////////
 void CLightAnimWrapper::CacheLightAnim(const char* name, CLightAnimWrapper* p)
 {
-    ms_lightAnimWrapperCache.insert(LightAnimWrapperCache::value_type(string(name), p));
+    ms_lightAnimWrapperCache.insert(LightAnimWrapperCache::value_type(AZStd::string(name), p));
 }
 
 //////////////////////////////////////////////////////////////////////////
diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
index 9e3fe212df..799747eb12 100644
--- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
@@ -917,7 +917,7 @@ void CAnimSceneNode::ApplyEventKey(IEventKey& key, [[maybe_unused]] SAnimContext
 {
     char funcName[1024];
     azstrcpy(funcName, "Event_");
-    cry_strcat(funcName, key.event.c_str());
+    azstrcat(funcName, key.event.c_str());
     gEnv->pMovieSystem->SendGlobalEvent(funcName);
 }
 
@@ -1003,7 +1003,7 @@ void CAnimSceneNode::ApplyGotoKey(CGotoTrack*   poGotoTrack, SAnimContext& ec)
         {
             if (stDiscreteFloadKey.m_fValue >= 0)
             {
-                string fullname = m_pSequence->GetName();
+                AZStd::string fullname = m_pSequence->GetName();
                 GetMovieSystem()->GoToFrame(fullname.c_str(), stDiscreteFloadKey.m_fValue);
             }
         }
diff --git a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
index af5b931dec..3541fe718e 100644
--- a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
@@ -32,7 +32,7 @@ void CScreenFaderTrack::GetKeyInfo(int key, const char*& description, float& dur
     CheckValid();
     description = 0;
     duration = m_keys[key].m_fadeTime;
-    cry_strcpy(desc, m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out");
+    azstrcpy(desc, m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out");
 
     description = desc;
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
index 3eca733a1d..25d709bcdc 100644
--- a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
@@ -146,8 +146,8 @@ void CTrackEventTrack::GetKeyInfo(int key, const char*& description, float& dura
     azstrcpy(desc, m_keys[key].event.c_str());
     if (!m_keys[key].eventValue.empty())
     {
-        cry_strcat(desc, ", ");
-        cry_strcat(desc, m_keys[key].eventValue.c_str());
+        azstrcat(desc, ", ");
+        azstrcat(desc, m_keys[key].eventValue.c_str());
     }
 
     description = desc;

From 93a3d3efa07abe909474ee81f981b9df98524c01 Mon Sep 17 00:00:00 2001
From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com>
Date: Mon, 2 Aug 2021 15:57:29 -0400
Subject: [PATCH 058/251] Bandwith overlay works without imgui

Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com>
---
 .../Include/Multiplayer/IMultiplayerDebug.h   |  28 +++++
 .../Debug/MultiplayerDebugByteReporter.cpp    |   4 +-
 .../MultiplayerDebugPerEntityReporter.cpp     | 106 ++++++++----------
 .../Debug/MultiplayerDebugPerEntityReporter.h |   3 +-
 .../Debug/MultiplayerDebugSystemComponent.cpp |  35 +++++-
 .../Debug/MultiplayerDebugSystemComponent.h   |  11 +-
 Gems/Multiplayer/Code/multiplayer_files.cmake |   1 +
 7 files changed, 123 insertions(+), 65 deletions(-)
 create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h

diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h
new file mode 100644
index 0000000000..384db66317
--- /dev/null
+++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.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
+
+namespace Multiplayer
+{
+    //! @class IMultiplayerDebug
+    //! @brief IMultiplayerDebug provides access to multiplayer debug overlays
+    class IMultiplayerDebug
+    {
+    public:
+        AZ_RTTI(IMultiplayerDebug, "{C5EB7F3A-E19F-4921-A604-C9BDC910123C}");
+
+        virtual ~IMultiplayerDebug() = default;
+
+        //!
+        virtual void ShowEntityBandwidthDebugOverlay() = 0;
+
+        //!
+        virtual void HideEntityBandwidthDebugOverlay() = 0;
+    };
+}
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp
index a29350e43a..38a1a27dcd 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp
@@ -8,12 +8,10 @@
 
 #include "MultiplayerDebugByteReporter.h"
 
-#include 
+#include  // for std::setfill
 #include 
 #include 
 
-#pragma optimize("", off)
-
 namespace Multiplayer
 {
     void MultiplayerDebugByteReporter::ReportBytes(size_t byteSize)
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp
index da32bbb666..b0bfe097e1 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp
@@ -17,11 +17,6 @@
 #include 
 #endif
 
-#pragma optimize("", off)
-
-AZ_CVAR(bool, net_DebugNetworkEntity_Bandwidth, true, nullptr, AZ::ConsoleFunctorFlags::Null,
-    "If true, prints debug text over entities that use a considerable amount of network traffic");
-
 AZ_CVAR(float, net_DebugNetworkEntity_ShowAboveKbps, 1.f, nullptr, AZ::ConsoleFunctorFlags::Null,
     "Prints bandwidth on network entities with higher kpbs than this value");
 
@@ -304,8 +299,8 @@ namespace Multiplayer
 
     void MultiplayerDebugPerEntityReporter::RecordRpcReceived(
         AZ::EntityId entityId, const char* entityName,
-        Multiplayer::NetComponentId netComponentId,
-        Multiplayer::RpcIndex rpcId,
+        NetComponentId netComponentId,
+        RpcIndex rpcId,
         uint32_t totalBytes)
     {
         if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry())
@@ -323,69 +318,66 @@ namespace Multiplayer
 
     void MultiplayerDebugPerEntityReporter::UpdateDebugOverlay()
     {
-        if (net_DebugNetworkEntity_Bandwidth)
+        m_networkEntitiesTraffic.clear();
+
+        for (AZStd::pair& entityPair : m_receivingEntityReports)
         {
-            m_networkEntitiesTraffic.clear();
+            m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName();
+            m_networkEntitiesTraffic[entityPair.first].m_down = entityPair.second.GetKbitsPerSecond();
+        }
 
-            for (AZStd::pair& entityPair : m_receivingEntityReports)
+        for (AZStd::pair& entityPair : m_sendingEntityReports)
+        {
+            m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName();
+            m_networkEntitiesTraffic[entityPair.first].m_up = entityPair.second.GetKbitsPerSecond();
+        }
+
+        //get debug display interface for the viewport
+        if (m_debugDisplay == nullptr)
+        {
+            AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus;
+            AzFramework::DebugDisplayRequestBus::Bind(debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId);
+            m_debugDisplay = AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus);
+        }
+
+        const AZ::u32 stateBefore = m_debugDisplay->GetState();
+
+        for (AZStd::pair& networkEntity : m_networkEntitiesTraffic)
+        {
+            if (networkEntity.second.m_down < net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up < net_DebugNetworkEntity_ShowAboveKbps)
             {
-                m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName();
-                m_networkEntitiesTraffic[entityPair.first].m_down = entityPair.second.GetKbitsPerSecond();
+                continue;
             }
 
-            for (AZStd::pair& entityPair : m_sendingEntityReports)
+            if (networkEntity.second.m_down > net_DebugNetworkEntity_WarnAboveKbps || networkEntity.second.m_up > net_DebugNetworkEntity_WarnAboveKbps)
             {
-                m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName();
-                m_networkEntitiesTraffic[entityPair.first].m_up = entityPair.second.GetKbitsPerSecond();
+                m_debugDisplay->SetColor(net_DebugNetworkEntity_WarningColor);
             }
-
-            //get debug display interface for the viewport
-            if (m_debugDisplay == nullptr)
+            else
             {
-                AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus;
-                AzFramework::DebugDisplayRequestBus::Bind(debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId);
-                m_debugDisplay = AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus);
+                m_debugDisplay->SetColor(net_DebugNetworkEntity_BelowWarningColor);
             }
 
-            const AZ::u32 stateBefore = m_debugDisplay->GetState();
-
-            for (AZStd::pair& networkEntity : m_networkEntitiesTraffic)
+            if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up > net_DebugNetworkEntity_ShowAboveKbps)
             {
-                if (networkEntity.second.m_down < net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up < net_DebugNetworkEntity_ShowAboveKbps)
-                {
-                    continue;
-                }
-
-                if (networkEntity.second.m_down > net_DebugNetworkEntity_WarnAboveKbps || networkEntity.second.m_up > net_DebugNetworkEntity_WarnAboveKbps)
-                {
-                    m_debugDisplay->SetColor(net_DebugNetworkEntity_WarningColor);
-                }
-                else
-                {
-                    m_debugDisplay->SetColor(net_DebugNetworkEntity_BelowWarningColor);
-                }
-
-                if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up > net_DebugNetworkEntity_ShowAboveKbps)
-                {
-                    azsprintf(m_statusBuffer, "[%s] %.0f down / %0.f up (kbps)", networkEntity.second.m_name,
-                        networkEntity.second.m_down, networkEntity.second.m_up);
-                }
-                else if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps)
-                {
-                    azsprintf(m_statusBuffer, "[%s] %.0f down (kbps)", networkEntity.second.m_name, networkEntity.second.m_down);
-                }
-                else
-                {
-                    azsprintf(m_statusBuffer, "[%s] %.0f up (kbps)", networkEntity.second.m_name, networkEntity.second.m_up);
-                }
-
-                AZ::Vector3 entityPosition = AZ::Vector3::CreateZero();
-                constexpr bool centerText = true;
-                AZ::TransformBus::EventResult(entityPosition, networkEntity.first, &AZ::TransformBus::Events::GetWorldTranslation);
-                m_debugDisplay->DrawTextLabel(entityPosition, 1.0f, m_statusBuffer, centerText, 0, 0);
+                azsprintf(m_statusBuffer, "[%s] %.0f down / %0.f up (kbps)", networkEntity.second.m_name,
+                    networkEntity.second.m_down, networkEntity.second.m_up);
+            }
+            else if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps)
+            {
+                azsprintf(m_statusBuffer, "[%s] %.0f down (kbps)", networkEntity.second.m_name, networkEntity.second.m_down);
+            }
+            else
+            {
+                azsprintf(m_statusBuffer, "[%s] %.0f up (kbps)", networkEntity.second.m_name, networkEntity.second.m_up);
             }
 
-            m_debugDisplay->SetState(stateBefore);
+            AZ::Vector3 entityPosition = AZ::Vector3::CreateZero();
+            constexpr bool centerText = true;
+            AZ::TransformBus::EventResult(entityPosition, networkEntity.first, &AZ::TransformBus::Events::GetWorldTranslation);
+            m_debugDisplay->DrawTextLabel(entityPosition, 1.0f, m_statusBuffer, centerText, 0, 0);
         }
+
+        m_debugDisplay->SetState(stateBefore);
     }
 }
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h
index d6ceaaf04c..8a33bc78ee 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h
@@ -11,7 +11,6 @@
 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -66,7 +65,7 @@ namespace Multiplayer
             float m_down = 0.f;
         };
 
-        AZStd::fixed_unordered_map m_networkEntitiesTraffic;
+        AZStd::unordered_map m_networkEntitiesTraffic;
 
         AzFramework::DebugDisplayRequests* m_debugDisplay = nullptr;
     };
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp
index 03d79025f7..f892ee9724 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp
@@ -13,6 +13,11 @@
 #include 
 #include 
 
+void OnDebugNetworkEntity_ShowBandwidth_Changed(const bool& showBandwidth);
+
+AZ_CVAR(bool, net_DebugNetworkEntity_ShowBandwidth, false, &OnDebugNetworkEntity_ShowBandwidth_Changed, AZ::ConsoleFunctorFlags::Null,
+    "If true, prints bandwidth values over entities that use a considerable amount of network traffic");
+
 namespace Multiplayer
 {
     void MultiplayerDebugSystemComponent::Reflect(AZ::ReflectContext* context)
@@ -53,11 +58,20 @@ namespace Multiplayer
 #endif
     }
 
-    void MultiplayerDebugSystemComponent::OnImGuiInitialize()
+    void MultiplayerDebugSystemComponent::ShowEntityBandwidthDebugOverlay()
     {
         m_reporter = AZStd::make_unique();
     }
 
+    void MultiplayerDebugSystemComponent::HideEntityBandwidthDebugOverlay()
+    {
+        m_reporter.reset();
+    }
+
+    void MultiplayerDebugSystemComponent::OnImGuiInitialize()
+    {
+    }
+
 #ifdef IMGUI_ENABLED
     void MultiplayerDebugSystemComponent::OnImGuiMainMenuUpdate()
     {
@@ -327,15 +341,32 @@ namespace Multiplayer
 
         if (m_displayPerEntityStats)
         {
-            //ImGui::SetNextWindowSize({500, 400});
+            // This overrides @net_DebugNetworkEntity_ShowBandwidth value
             if (ImGui::Begin("Multiplayer Per Entity Stats", &m_displayPerEntityStats, ImGuiWindowFlags_AlwaysAutoResize))
             {
                 if (m_reporter)
                 {
                     m_reporter->OnImGuiUpdate();
                 }
+                else
+                {
+                    ShowEntityBandwidthDebugOverlay();
+                }
             }
         }
     }
 #endif
 }
+
+void OnDebugNetworkEntity_ShowBandwidth_Changed(const bool& showBandwidth)
+{
+    if (showBandwidth)
+    {
+        AZ::Interface::Get()->ShowEntityBandwidthDebugOverlay();
+    }
+    else
+    {
+        AZ::Interface::Get()->HideEntityBandwidthDebugOverlay();
+    }
+}
+
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h
index a7f76e075a..87b238c79b 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h
@@ -9,7 +9,9 @@
 #pragma once
 
 #include 
+#include 
 #include 
+#include 
 
 #ifdef IMGUI_ENABLED
 #   include 
@@ -20,6 +22,7 @@ namespace Multiplayer
 {
     class MultiplayerDebugSystemComponent final
         : public AZ::Component
+        , public AZ::Interface::Registrar
 #ifdef IMGUI_ENABLED
         , public ImGui::ImGuiUpdateListenerBus::Handler
 #endif
@@ -30,7 +33,7 @@ namespace Multiplayer
         static void Reflect(AZ::ReflectContext* context);
         static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
         static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required);
-        static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatbile);
+        static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible);
 
         ~MultiplayerDebugSystemComponent() override = default;
 
@@ -40,6 +43,12 @@ namespace Multiplayer
         void Deactivate() override;
         //! @}
 
+        //! IMultiplayerDebugSystem overrides
+        //! @{
+        void ShowEntityBandwidthDebugOverlay() override;
+        void HideEntityBandwidthDebugOverlay() override;
+        //! @}
+
 #ifdef IMGUI_ENABLED
         //! ImGui::ImGuiUpdateListenerBus overrides
         //! @{
diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake
index 7392ea6856..0b2adb1530 100644
--- a/Gems/Multiplayer/Code/multiplayer_files.cmake
+++ b/Gems/Multiplayer/Code/multiplayer_files.cmake
@@ -8,6 +8,7 @@
 
 set(FILES
     Include/Multiplayer/IMultiplayer.h
+    Include/Multiplayer/IMultiplayerDebug.h
     Include/Multiplayer/IMultiplayerTools.h
     Include/Multiplayer/MultiplayerConstants.h
     Include/Multiplayer/MultiplayerStats.h

From 58ff2d8cab609637c16d2988451e0e494971444a Mon Sep 17 00:00:00 2001
From: Dayo Lawal 
Date: Mon, 2 Aug 2021 14:59:45 -0500
Subject: [PATCH 059/251] AtomToolsMainWindowRequestBus

Signed-off-by: Dayo Lawal 
---
 .../Window/AtomToolsMainWindow.h              | 22 +++++-
 .../AtomToolsMainWindowFactoryRequestBus.h    | 30 ++++++++
 .../Window/AtomToolsMainWindowRequestBus.h    | 63 +++++++++++++++
 .../Source/Window/AtomToolsMainWindow.cpp     | 77 ++++++++++++++++++-
 .../Code/atomtoolsframework_files.cmake       |  6 +-
 .../Source/Window/MaterialEditorWindow.cpp    | 70 +----------------
 .../Code/Source/Window/MaterialEditorWindow.h | 11 ---
 .../Window/ShaderManagementConsoleWindow.cpp  | 41 ++++------
 .../Window/ShaderManagementConsoleWindow.h    |  5 --
 9 files changed, 205 insertions(+), 120 deletions(-)
 create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h
 create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h

diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
index 21afe114f5..2cc6621cec 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
@@ -8,6 +8,7 @@
 
 #pragma once
 #include 
+#include 
 
 #include 
 #include 
@@ -22,14 +23,19 @@ namespace AtomToolsFramework
 {
     class AtomToolsMainWindow
         : public AzQtComponents::DockMainWindow
+        , protected AtomToolsFramework::AtomToolsMainWindowRequestBus::Handler
     {
     public:
         AtomToolsMainWindow(QWidget* parent = 0);
+        ~AtomToolsMainWindow();
+
     protected:
-        AzQtComponents::FancyDocking* m_advancedDockManager = nullptr;
-        QWidget* m_centralWidget = nullptr;
-        QMenuBar* m_menuBar = nullptr;
-        AzQtComponents::TabWidget* m_tabWidget = nullptr;
+        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 SetupMenu();
 
@@ -43,6 +49,14 @@ namespace AtomToolsFramework
         virtual void SelectPreviousTab();
         virtual void SelectNextTab();
 
+        AzQtComponents::FancyDocking* m_advancedDockManager = nullptr;
+        QWidget* m_centralWidget = nullptr;
+        QMenuBar* m_menuBar = nullptr;
+        AzQtComponents::TabWidget* m_tabWidget = nullptr;
+
+        AZStd::unordered_map m_dockWidgets;
+
         QMenu* m_menuFile = {};
+        //StatusBarWidget* m_statusBar = {};
     };
 }
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..aed0d877db
--- /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 the AtomToolsMainWindow
+        virtual void CreateAtomToolsMainWindow() = 0;
+
+        //! Destroys material editor window and releases all cached assets
+        virtual void DestroyAtomToolsMainWindow() = 0;
+    };
+    using AtomToolsMainWindowFactoryRequestBus = AZ::EBus;
+
+} // namespace AtomToolsFramework
diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h
new file mode 100644
index 0000000000..fd98b3b68b
--- /dev/null
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.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
+#pragma warning(disable : 4100)
+#include 
+#include 
+#include 
+
+class QWidget;
+
+namespace AtomToolsFramework
+{
+    //! AtomToolsMainWindowRequestBus provides
+    class AtomToolsMainWindowRequests : public AZ::EBusTraits
+    {
+    public:
+        static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single;
+        static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single;
+
+        //! Bring main window to foreground
+        virtual void ActivateWindow() = 0;
+
+        //! Add dockable widget in main window
+        //! @param name title of the dockable window
+        //! @param widget docked window content
+        //! @param area location of docked window corresponding to Qt::DockWidgetArea
+        //! @param orientation orientation of docked window corresponding to Qt::Orientation
+        virtual bool AddDockWidget(const AZStd::string& name, QWidget* widget, uint32_t area, uint32_t orientation) = 0;
+
+        //! Destroy dockable widget in main window
+        //! @param name title of the dockable window
+        virtual void RemoveDockWidget(const AZStd::string& name) = 0;
+
+        //! Show or hide dockable widget in main window
+        //! @param name title of the dockable window
+        virtual void SetDockWidgetVisible(const AZStd::string& name, bool visible) = 0;
+
+        //! Determine visibility of dockable widget in main window
+        //! @param name title of the dockable window
+        virtual bool IsDockWidgetVisible(const AZStd::string& name) const = 0;
+
+        //! 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.
+        //! (This indicates the size of the render target, not the desktop-scaled QT widget size).
+        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) {};
+
+        //! Releases the viewport's render target resolution lock, allowing it to match the viewport widget again.
+        virtual void UnlockViewportRenderTargetSize() {};
+    };
+    using AtomToolsMainWindowRequestBus = AZ::EBus;
+
+} // namespace AtomToolsFramework
diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp
index 15edd8c5b6..849169e2e3 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp
@@ -8,7 +8,6 @@
 
 #include 
 
-
 namespace AtomToolsFramework
 {
     AtomToolsMainWindow::AtomToolsMainWindow(QWidget* parent)
@@ -31,6 +30,80 @@ namespace AtomToolsFramework
         m_tabWidget->setObjectName("TabWidget");
         m_tabWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
         m_tabWidget->setContentsMargins(0, 0, 0, 0);
+
+        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::SetupMenu()
@@ -132,4 +205,4 @@ namespace AtomToolsFramework
             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 5ef4426537..0769aac86c 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake
@@ -24,7 +24,9 @@ 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/AtomToolsMainWindow.h
+    Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h
+    Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h
     Source/Application/AtomToolsApplication.cpp
     Source/Communication/LocalServer.cpp
     Source/Communication/LocalSocket.cpp
@@ -41,5 +43,5 @@ set(FILES
     Source/Util/Util.cpp
     Source/Viewport/RenderViewportWidget.cpp
     Source/Viewport/ModularViewportCameraController.cpp
-	Source/Window/AtomToolsMainWindow.cpp
+    Source/Window/AtomToolsMainWindow.cpp
 )
diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
index 78670ac710..96a94ebfcc 100644
--- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
+++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
@@ -131,7 +131,6 @@ namespace MaterialEditor
             m_advancedDockManager->restoreState(windowState);
         }
 
-        MaterialEditorWindowRequestBus::Handler::BusConnect();
         MaterialDocumentNotificationBus::Handler::BusConnect();
         OnDocumentOpened(AZ::Uuid::CreateNull());
     }
@@ -139,76 +138,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();
diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
index 96f03e6eed..a443f04ebe 100644
--- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
+++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
@@ -46,7 +46,6 @@ namespace MaterialEditor
      */
     class MaterialEditorWindow
         : public AtomToolsFramework::AtomToolsMainWindow
-        , private MaterialEditorWindowRequestBus::Handler
         , private MaterialDocumentNotificationBus::Handler
     {
         Q_OBJECT
@@ -59,14 +58,6 @@ namespace MaterialEditor
         ~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;
@@ -92,8 +83,6 @@ namespace MaterialEditor
         MaterialViewportWidget* m_materialViewport = nullptr;
         MaterialEditorToolBar* m_toolBar = nullptr;
 
-        AZStd::unordered_map  m_dockWidgets;
-
         QAction* m_actionNew = {};
         QAction* m_actionOpen = {};
         QAction* m_actionOpenRecent = {};
diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
index 90a2e238a9..05f88655ca 100644
--- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
+++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
@@ -58,24 +58,8 @@ namespace ShaderManagementConsole
         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());
@@ -256,17 +240,20 @@ namespace ShaderManagementConsole
 
         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();
diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h
index cb371bc4d6..8513366ec2 100644
--- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h
+++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h
@@ -79,12 +79,7 @@ namespace ShaderManagementConsole
 
         void CreateDocumentContent(const AZ::Uuid& documentId, QStandardItemModel* model);
 
-        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_menuNew = {};
         QAction* m_actionOpen = {};

From 29a2ad79a44d850e0046609c1c4ffd2a5012c0cc Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 14:04:18 -0700
Subject: [PATCH 060/251] Gems/Gestures

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h               | 2 +-
 Code/Legacy/CrySystem/XConsole.cpp                            | 4 ++--
 .../Code/Include/Gestures/GestureRecognizerClickOrTap.inl     | 1 +
 Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl | 1 +
 Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h   | 1 +
 Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl | 1 +
 .../Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl | 1 +
 .../Code/Include/Gestures/GestureRecognizerRotate.inl         | 1 +
 .../Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl | 1 +
 9 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h b/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h
index 44962ddb61..4702435b83 100644
--- a/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h
+++ b/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h
@@ -101,7 +101,7 @@ public: // member functions
 
     //! Save this canvas to the given path in XML
     //! \return true if no error
-    virtual bool SaveToXml(const string& assetIdPathname, const string& sourceAssetPathname) = 0;
+    virtual bool SaveToXml(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname) = 0;
 
     //! Initialize a set of entities that have been added to the canvas
     //! Used when instantiating a slice or for undo/redo, copy/paste
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index 2348e78a0e..0f67e4ffd9 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -2911,9 +2911,9 @@ void CXConsole::Paste()
             if (cp != '\r')
             {
                 // Convert UCS code-point into UTF-8 string
-                char utf8_buf[5] = {0};
+                AZStd::fixed_string<5> utf8_buf = {0};
                 size_t size = 5;
-                it.to_utf8_sequence(cp, utf8_buf, size);
+                it.to_utf8_sequence(cp, utf8_buf.data(), size);
                 AddInputUTF8(utf8_buf);
             }
         }
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl
index 84837972e8..57716c7d9f 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerClickOrTap::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl
index 368f236338..2c1af6fbc9 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerDrag::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h
index b8d538b426..87c53d815a 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h
@@ -9,6 +9,7 @@
 
 #include "IGestureRecognizer.h"
 
+#include 
 #include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl
index 48f23cce1f..b399639f6d 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerHold::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl
index e577be0e48..f6c0427b2c 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerPinch::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl
index eb3b20287e..9dff9a115a 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerRotate::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
index 9fdab7b1a2..8d59525e93 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerSwipe::Config::Reflect(AZ::ReflectContext* context)

From 63ed78d2679e9eaec353a2d3af0a40f0fb22a0c6 Mon Sep 17 00:00:00 2001
From: Dayo Lawal 
Date: Mon, 2 Aug 2021 17:27:26 -0500
Subject: [PATCH 061/251] status_bar

Signed-off-by: Dayo Lawal 
---
 .../Window/AtomToolsMainWindow.h              |  1 +
 .../Source/Window/AtomToolsMainWindow.cpp     |  4 +++
 .../Source/Window/MaterialEditorWindow.cpp    | 35 ++++++++++++-------
 .../Code/Source/Window/MaterialEditorWindow.h |  2 --
 .../Code/materialeditorwindow_files.cmake     |  6 ++--
 .../Window/ShaderManagementConsoleWindow.cpp  |  4 +++
 6 files changed, 34 insertions(+), 18 deletions(-)

diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
index 2cc6621cec..edb8ff4322 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
@@ -53,6 +53,7 @@ namespace AtomToolsFramework
         QWidget* m_centralWidget = nullptr;
         QMenuBar* m_menuBar = nullptr;
         AzQtComponents::TabWidget* m_tabWidget = nullptr;
+        QStatusBar* m_statusBar = nullptr;
 
         AZStd::unordered_map m_dockWidgets;
 
diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp
index 849169e2e3..ffc618c574 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp
@@ -31,6 +31,10 @@ namespace AtomToolsFramework
         m_tabWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
         m_tabWidget->setContentsMargins(0, 0, 0, 0);
 
+        m_statusBar = new QStatusBar(this);
+        m_statusBar->setObjectName("StatusBar");
+        statusBar()->addPermanentWidget(m_statusBar, 1);
+
         AtomToolsMainWindowRequestBus::Handler::BusConnect();
     }
 
diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
index 96a94ebfcc..733a01539e 100644
--- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
+++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp
@@ -101,10 +101,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();
 
@@ -245,7 +241,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));
         }
     }
 
@@ -254,7 +251,8 @@ 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)
@@ -280,7 +278,8 @@ namespace MaterialEditor
         UpdateTabForDocumentId(documentId);
 
         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()
@@ -321,7 +320,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);
 
@@ -334,7 +334,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);
 
@@ -347,7 +348,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));
             }
         });
 
@@ -356,7 +358,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));
             }
         });
 
@@ -401,7 +404,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);
 
@@ -412,7 +416,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);
 
@@ -505,6 +510,10 @@ namespace MaterialEditor
 
         AtomToolsMainWindow::AddTabForDocumentId(documentId);
 
+        // 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);
+
         // 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);
diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
index a443f04ebe..65c13a094d 100644
--- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
+++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h
@@ -113,7 +113,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/materialeditorwindow_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake
index f5891a5c2b..caef9916f6 100644
--- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake
+++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake
@@ -42,15 +42,15 @@ set(FILES
     Source/Window/PerformanceMonitor/PerformanceMonitorWidget.cpp
     Source/Window/PerformanceMonitor/PerformanceMonitorWidget.h
     Source/Window/PerformanceMonitor/PerformanceMonitorWidget.ui
+    Source/Window/StatusBar/StatusBarWidget.cpp
+    Source/Window/StatusBar/StatusBarWidget.h
+    Source/Window/StatusBar/StatusBarWidget.ui
     Source/Window/ToolBar/MaterialEditorToolBar.h
     Source/Window/ToolBar/MaterialEditorToolBar.cpp
     Source/Window/ToolBar/ModelPresetComboBox.h
     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/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
index 05f88655ca..e02ab83597 100644
--- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
+++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp
@@ -303,6 +303,10 @@ namespace ShaderManagementConsole
 
         AtomToolsMainWindow::AddTabForDocumentId(documentId);
 
+        // 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);
+
         // 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);

From d5c491a694b3990ab6a5ab15a72f237cb4bc10a0 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 16:04:46 -0700
Subject: [PATCH 062/251] Gems\MetaStream

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Gems/Metastream/Code/Source/MetastreamGem.cpp | 2 +-
 Gems/Metastream/Code/Tests/MetastreamTest.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Gems/Metastream/Code/Source/MetastreamGem.cpp b/Gems/Metastream/Code/Source/MetastreamGem.cpp
index d1792c439f..2bb213662c 100644
--- a/Gems/Metastream/Code/Source/MetastreamGem.cpp
+++ b/Gems/Metastream/Code/Source/MetastreamGem.cpp
@@ -323,7 +323,7 @@ namespace Metastream
         {
             // Initialise and start the HTTP server
             m_server = std::unique_ptr(new CivetHttpServer(m_cache.get()));
-            string serverOptions = m_serverOptionsCVar->GetString();
+            AZStd::string serverOptions = m_serverOptionsCVar->GetString();
             CryLogAlways("Initializing Metastream: Options=\"%s\"", serverOptions.c_str());
 
             bool result = m_server->Start(serverOptions.c_str());
diff --git a/Gems/Metastream/Code/Tests/MetastreamTest.cpp b/Gems/Metastream/Code/Tests/MetastreamTest.cpp
index 4f1d37391a..1b25fb5327 100644
--- a/Gems/Metastream/Code/Tests/MetastreamTest.cpp
+++ b/Gems/Metastream/Code/Tests/MetastreamTest.cpp
@@ -60,7 +60,7 @@ public:
 
     }
 
-    const string m_serverOptionsString = "document_root=Gems/Metastream/Files;listening_ports=8082";
+    const char* m_serverOptionsString = "document_root=Gems/Metastream/Files;listening_ports=8082";
 
 protected:
     void SetUp() override

From 0620f6dff3267d2a5efda4ee89babd064083c562 Mon Sep 17 00:00:00 2001
From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com>
Date: Mon, 2 Aug 2021 19:06:02 -0400
Subject: [PATCH 063/251] Minor refactoring

Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com>
---
 .../Source/Debug/MultiplayerDebugByteReporter.cpp  |  3 ---
 .../Source/Debug/MultiplayerDebugByteReporter.h    |  5 -----
 .../Debug/MultiplayerDebugSystemComponent.cpp      | 14 +++++++++-----
 .../Source/Debug/MultiplayerDebugSystemComponent.h |  2 ++
 4 files changed, 11 insertions(+), 13 deletions(-)

diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp
index 38a1a27dcd..361f9d943d 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp
@@ -169,7 +169,6 @@ namespace Multiplayer
             m_currentComponentReport = nullptr;
         }
 
-        m_gdeDirtyBytes.ReportAggregateBytes();
         MultiplayerDebugByteReporter::ReportAggregateBytes();
     }
 
@@ -183,7 +182,6 @@ namespace Multiplayer
         }
 
         SetEntityName(other.GetEntityName());
-        m_gdeDirtyBytes.Combine(other.m_gdeDirtyBytes);
     }
 
     void MultiplayerDebugEntityReporter::Reset()
@@ -191,7 +189,6 @@ namespace Multiplayer
         MultiplayerDebugByteReporter::Reset();
 
         m_componentReports.clear();
-        m_gdeDirtyBytes.Reset();
     }
 
     AZStd::map& MultiplayerDebugEntityReporter::GetComponentReports()
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h
index 934c6f3aac..279f7fb360 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h
@@ -58,8 +58,6 @@ namespace Multiplayer
 
         using Report = AZStd::pair;
         AZStd::vector GetFieldReports();
-        AZStd::size_t GetTotalDirtyBits() const { return m_componentDirtyBytes.GetTotalBytes(); }
-        float GetAvgDirtyBits() const { return m_componentDirtyBytes.GetAverageBytes(); }
 
         void Combine(const MultiplayerDebugComponentReporter& other);
 
@@ -87,13 +85,10 @@ namespace Multiplayer
         }
 
         AZStd::map& GetComponentReports();
-        AZStd::size_t GetTotalDirtyBits() const { return m_gdeDirtyBytes.GetTotalBytes(); }
-        float GetAvgDirtyBits() const { return m_gdeDirtyBytes.GetAverageBytes(); }
 
     private:
         MultiplayerDebugComponentReporter* m_currentComponentReport = nullptr;
         AZStd::map m_componentReports;
-        MultiplayerDebugByteReporter m_gdeDirtyBytes;
         AZStd::string m_entityName;
     };
 }
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp
index f892ee9724..0e015fc86d 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp
@@ -341,16 +341,20 @@ namespace Multiplayer
 
         if (m_displayPerEntityStats)
         {
-            // This overrides @net_DebugNetworkEntity_ShowBandwidth value
             if (ImGui::Begin("Multiplayer Per Entity Stats", &m_displayPerEntityStats, ImGuiWindowFlags_AlwaysAutoResize))
             {
-                if (m_reporter)
+                if (ImGui::Checkbox("Show Bandwidth over Entities", &m_displayPerEntityBandwidth))
                 {
-                    m_reporter->OnImGuiUpdate();
+                    // This overrides @net_DebugNetworkEntity_ShowBandwidth value
+                    if (m_reporter == nullptr)
+                    {
+                        ShowEntityBandwidthDebugOverlay();
+                    }
                 }
-                else
+
+                if (m_reporter)
                 {
-                    ShowEntityBandwidthDebugOverlay();
+                    m_reporter->OnImGuiUpdate();
                 }
             }
         }
diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h
index 87b238c79b..9be53cca02 100644
--- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h
+++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h
@@ -60,7 +60,9 @@ namespace Multiplayer
     private:
         bool m_displayNetworkingStats = false;
         bool m_displayMultiplayerStats = false;
+
         bool m_displayPerEntityStats = false;
+        bool m_displayPerEntityBandwidth = false;
 
         AZStd::unique_ptr m_reporter;
     };

From 061cb98f74971b54744e8f241eeab3b3a26393b2 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 16:07:23 -0700
Subject: [PATCH 064/251] auto-search/replace

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/BaseLibraryManager.cpp            |   2 +-
 Code/Editor/Commands/CommandManager.cpp       |   2 +-
 Code/Editor/Commands/CommandManager.h         |  22 ++--
 Code/Editor/ConfigGroup.h                     |   6 +-
 Code/Editor/Controls/SplineCtrlEx.h           |   2 +-
 Code/Editor/Include/Command.h                 | 110 +++++++++---------
 .../EditorAssetImporter/AssetImporterPlugin.h |   2 +-
 Code/Editor/Util/EditorUtils.h                |   1 +
 Code/Editor/Util/FileUtil.cpp                 |   2 +-
 Code/Editor/Util/IXmlHistoryManager.h         |   2 +-
 Code/Editor/Util/StringHelpers.cpp            |  42 +++----
 Code/Editor/Util/StringHelpers.h              |  42 +++----
 Code/Editor/Util/XmlHistoryManager.cpp        |   2 +-
 Code/Editor/Util/XmlHistoryManager.h          |   2 +-
 .../GridMate/GridMate/Carrier/Carrier.cpp     |   8 +-
 .../GridMate/GridMate/Carrier/Carrier.h       |   2 +-
 .../GridMate/Carrier/DefaultHandshake.cpp     |   2 +-
 .../GridMate/Carrier/DefaultHandshake.h       |   2 +-
 .../GridMate/GridMate/Carrier/Driver.h        |   4 +-
 .../GridMate/GridMate/Carrier/Handshake.h     |   2 +-
 .../GridMate/Carrier/SocketDriver.cpp         |  14 +--
 .../GridMate/GridMate/Carrier/SocketDriver.h  |  14 +--
 .../GridMate/Drillers/SessionDriller.cpp      |   2 +-
 .../GridMate/Drillers/SessionDriller.h        |   2 +-
 .../GridMate/GridMate/Session/LANSession.cpp  |  12 +-
 .../GridMate/Session/LANSessionServiceTypes.h |   6 +-
 .../GridMate/GridMate/Session/Session.cpp     |   8 +-
 .../GridMate/GridMate/Session/Session.h       |  12 +-
 Code/Framework/GridMate/Tests/Session.cpp     |  12 +-
 .../Framework/GridMate/Tests/TestProfiler.cpp |   2 +-
 .../Legacy/CryCommon/LocalizationManagerBus.h |   2 +-
 .../LyShine/Animation/IUiAnimation.h          |  11 +-
 Code/Legacy/CryCommon/LyShine/ISprite.h       |   7 +-
 33 files changed, 179 insertions(+), 184 deletions(-)

diff --git a/Code/Editor/BaseLibraryManager.cpp b/Code/Editor/BaseLibraryManager.cpp
index 8e555cae8c..2189156454 100644
--- a/Code/Editor/BaseLibraryManager.cpp
+++ b/Code/Editor/BaseLibraryManager.cpp
@@ -560,7 +560,7 @@ QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QS
         return srcName;
     }
 
-    std::sort(possibleDuplicates.begin(), possibleDuplicates.end(), [](const string& strOne, const string& strTwo)
+    std::sort(possibleDuplicates.begin(), possibleDuplicates.end(), [](const AZStd::string& strOne, const AZStd::string& strTwo)
         {
             // I can assume size sorting since if the length is different, either one of the two strings doesn't
             // closely match the string we are trying to duplicate, or it's a bigger number (X1 vs X10)
diff --git a/Code/Editor/Commands/CommandManager.cpp b/Code/Editor/Commands/CommandManager.cpp
index 90059ea195..708fccd16b 100644
--- a/Code/Editor/Commands/CommandManager.cpp
+++ b/Code/Editor/Commands/CommandManager.cpp
@@ -79,7 +79,7 @@ CEditorCommandManager::~CEditorCommandManager()
     m_uiCommands.clear();
 }
 
-string CEditorCommandManager::GetFullCommandName(const string& module, const string& name)
+string CEditorCommandManager::GetFullCommandName(const AZStd::string& module, const string& name)
 {
     string fullName = module;
     fullName += ".";
diff --git a/Code/Editor/Commands/CommandManager.h b/Code/Editor/Commands/CommandManager.h
index 2ec4a137bc..a76df830d0 100644
--- a/Code/Editor/Commands/CommandManager.h
+++ b/Code/Editor/Commands/CommandManager.h
@@ -48,20 +48,20 @@ public:
         const AZStd::function& functor,
         const CCommand0::SUIInfo& uiInfo);
     bool AttachUIInfo(const char* fullCmdName, const CCommand0::SUIInfo& uiInfo);
-    bool GetUIInfo(const string& module, const string& name, CCommand0::SUIInfo& uiInfo) const;
-    bool GetUIInfo(const string& fullCmdName, CCommand0::SUIInfo& uiInfo) const;
-    QString Execute(const string& cmdLine);
-    QString Execute(const string& module, const string& name, const CCommand::CArgs& args);
+    bool GetUIInfo(const AZStd::string& module, const AZStd::string& name, CCommand0::SUIInfo& uiInfo) const;
+    bool GetUIInfo(const AZStd::string& fullCmdName, CCommand0::SUIInfo& uiInfo) const;
+    QString Execute(const AZStd::string& cmdLine);
+    QString Execute(const AZStd::string& module, const AZStd::string& name, const CCommand::CArgs& args);
     void Execute(int commandId);
     void GetCommandList(std::vector& cmds) const;
     //! Used in the console dialog
-    string AutoComplete(const string& substr) const;
+    string AutoComplete(const AZStd::string& substr) const;
     bool IsRegistered(const char* module, const char* name) const;
     bool IsRegistered(const char* cmdLine) const;
     bool IsRegistered(int commandId) const;
-    void SetCommandAvailableInScripting(const string& module, const string& name);
-    bool IsCommandAvailableInScripting(const string& module, const string& name) const;
-    bool IsCommandAvailableInScripting(const string& fullCmdName) const;
+    void SetCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name);
+    bool IsCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name) const;
+    bool IsCommandAvailableInScripting(const AZStd::string& fullCmdName) const;
     //! Turning off the warning is needed for reloading the ribbon bar.
     void TurnDuplicateWarningOn() { m_bWarnDuplicate = true; }
     void TurnDuplicateWarningOff() { m_bWarnDuplicate = false; }
@@ -86,9 +86,9 @@ protected:
     bool m_bWarnDuplicate;
 
     static int GenNewCommandId();
-    static string GetFullCommandName(const string& module, const string& name);
-    static void GetArgsFromString(const string& argsTxt, CCommand::CArgs& argList);
-    void LogCommand(const string& fullCmdName, const CCommand::CArgs& args) const;
+    static string GetFullCommandName(const AZStd::string& module, const AZStd::string& name);
+    static void GetArgsFromString(const AZStd::string& argsTxt, CCommand::CArgs& argList);
+    void LogCommand(const AZStd::string& fullCmdName, const CCommand::CArgs& args) const;
     QString ExecuteAndLogReturn(CCommand* pCommand, const CCommand::CArgs& args);
 };
 
diff --git a/Code/Editor/ConfigGroup.h b/Code/Editor/ConfigGroup.h
index 35c0b8e47f..5d9b22b2b9 100644
--- a/Code/Editor/ConfigGroup.h
+++ b/Code/Editor/ConfigGroup.h
@@ -47,12 +47,12 @@ namespace Config
             return m_type;
         }
 
-        ILINE const string& GetName() const
+        ILINE const AZStd::string& GetName() const
         {
             return m_name;
         }
 
-        ILINE const string& GetDescription() const
+        ILINE const AZStd::string& GetDescription() const
         {
             return m_description;
         }
@@ -71,7 +71,7 @@ namespace Config
         static EType TranslateType(const bool&) { return eType_BOOL; }
         static EType TranslateType(const int&) { return eType_INT; }
         static EType TranslateType(const float&) { return eType_FLOAT; }
-        static EType TranslateType(const string&) { return eType_STRING; }
+        static EType TranslateType(const AZStd::string&) { return eType_STRING; }
 
     protected:
         EType m_type;
diff --git a/Code/Editor/Controls/SplineCtrlEx.h b/Code/Editor/Controls/SplineCtrlEx.h
index 8592febf88..de07c4214b 100644
--- a/Code/Editor/Controls/SplineCtrlEx.h
+++ b/Code/Editor/Controls/SplineCtrlEx.h
@@ -53,7 +53,7 @@ class QRubberBand;
 class ISplineSet
 {
 public:
-    virtual ISplineInterpolator* GetSplineFromID(const string& id) = 0;
+    virtual ISplineInterpolator* GetSplineFromID(const AZStd::string& id) = 0;
     virtual string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
     virtual int GetSplineCount() const = 0;
     virtual int GetKeyCountAtTime(float time, float threshold) const = 0;
diff --git a/Code/Editor/Include/Command.h b/Code/Editor/Include/Command.h
index 69853ddb4f..92a7736446 100644
--- a/Code/Editor/Include/Command.h
+++ b/Code/Editor/Include/Command.h
@@ -27,10 +27,10 @@ class CCommand
 {
 public:
     CCommand(
-        const string& module,
-        const string& name,
-        const string& description,
-        const string& example)
+        const AZStd::string& module,
+        const AZStd::string& name,
+        const AZStd::string& description,
+        const AZStd::string& example)
         : m_module(module)
         , m_name(name)
         , m_description(description)
@@ -79,7 +79,7 @@ public:
         }
         int GetArgCount() const
         { return m_args.size(); }
-        const string& GetArg(int i) const
+        const AZStd::string& GetArg(int i) const
         {
             assert(0 <= i && i < GetArgCount());
             return m_args[i];
@@ -89,10 +89,10 @@ public:
         unsigned char m_stringFlags;    // This is needed to quote string parameters when logging a command.
     };
 
-    const string& GetName() const { return m_name; }
-    const string& GetModule() const { return m_module; }
-    const string& GetDescription() const { return m_description; }
-    const string& GetExample() const { return m_example; }
+    const AZStd::string& GetName() const { return m_name; }
+    const AZStd::string& GetModule() const { return m_module; }
+    const AZStd::string& GetDescription() const { return m_description; }
+    const AZStd::string& GetExample() const { return m_example; }
 
     void SetAvailableInScripting() { m_bAlsoAvailableInScripting = true; };
     bool IsAvailableInScripting() const { return m_bAlsoAvailableInScripting; }
@@ -137,8 +137,8 @@ class CCommand0
     : public CCommand
 {
 public:
-    CCommand0(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand0(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor)
         : CCommand(module, name, description, example)
         , m_functor(functor) {}
@@ -179,8 +179,8 @@ class CCommand0wRet
     : public CCommand
 {
 public:
-    CCommand0wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand0wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -195,8 +195,8 @@ class CCommand1
     : public CCommand
 {
 public:
-    CCommand1(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand1(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -211,8 +211,8 @@ class CCommand1wRet
     : public CCommand
 {
 public:
-    CCommand1wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand1wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -227,8 +227,8 @@ class CCommand2
     : public CCommand
 {
 public:
-    CCommand2(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand2(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -243,8 +243,8 @@ class CCommand2wRet
     : public CCommand
 {
 public:
-    CCommand2wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand2wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -259,8 +259,8 @@ class CCommand3
     : public CCommand
 {
 public:
-    CCommand3(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand3(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -275,8 +275,8 @@ class CCommand3wRet
     : public CCommand
 {
 public:
-    CCommand3wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand3wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -291,8 +291,8 @@ class CCommand4
     : public CCommand
 {
 public:
-    CCommand4(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand4(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -307,8 +307,8 @@ class CCommand4wRet
     : public CCommand
 {
 public:
-    CCommand4wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand4wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -323,8 +323,8 @@ class CCommand5
     : public CCommand
 {
 public:
-    CCommand5(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand5(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -339,8 +339,8 @@ class CCommand6
     : public CCommand
 {
 public:
-    CCommand6(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand6(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -353,8 +353,8 @@ protected:
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand0wRet::CCommand0wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand0wRet::CCommand0wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -373,8 +373,8 @@ QString CCommand0wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand1::CCommand1(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand1::CCommand1(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -410,8 +410,8 @@ QString CCommand1::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand1wRet::CCommand1wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand1wRet::CCommand1wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -448,8 +448,8 @@ QString CCommand1wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand2::CCommand2(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand2::CCommand2(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -487,8 +487,8 @@ QString CCommand2::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand2wRet::CCommand2wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand2wRet::CCommand2wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -527,8 +527,8 @@ QString CCommand2wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand3::CCommand3(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand3::CCommand3(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -568,8 +568,8 @@ QString CCommand3::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand3wRet::CCommand3wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand3wRet::CCommand3wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -610,8 +610,8 @@ QString CCommand3wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand4::CCommand4(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand4::CCommand4(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -654,8 +654,8 @@ QString CCommand4::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand4wRet::CCommand4wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand4wRet::CCommand4wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -699,8 +699,8 @@ QString CCommand4wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand5::CCommand5(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand5::CCommand5(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -745,8 +745,8 @@ QString CCommand5::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand6::CCommand6(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand6::CCommand6(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
diff --git a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
index c5b6694af4..8bdfb48774 100644
--- a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
+++ b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
@@ -41,7 +41,7 @@ public:
         return m_editor;
     }
 
-    const string& GetToolName() const
+    const AZStd::string& GetToolName() const
     {
         return m_toolName;
     }
diff --git a/Code/Editor/Util/EditorUtils.h b/Code/Editor/Util/EditorUtils.h
index fb767c98b3..1eb73532ef 100644
--- a/Code/Editor/Util/EditorUtils.h
+++ b/Code/Editor/Util/EditorUtils.h
@@ -18,6 +18,7 @@
 #include 
 #include "Util/FileUtil.h"
 #include 
+#include 
 
 //! Typedef for quaternion.
 //typedef CryQuat Quat;
diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp
index 9e4f688f69..d57d690154 100644
--- a/Code/Editor/Util/FileUtil.cpp
+++ b/Code/Editor/Util/FileUtil.cpp
@@ -1330,7 +1330,7 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory
         const QString fileName = QFileInfo(filePath).fileName();
 
         bool ignored = false;
-        for (const string& ignoredFile : ignoredPatterns)
+        for (const AZStd::string& ignoredFile : ignoredPatterns)
         {
             if (StringHelpers::CompareIgnoreCase(fileName.toStdString().c_str(), ignoredFile.c_str()) == 0)
             {
diff --git a/Code/Editor/Util/IXmlHistoryManager.h b/Code/Editor/Util/IXmlHistoryManager.h
index 78d849df7d..e133d073bc 100644
--- a/Code/Editor/Util/IXmlHistoryManager.h
+++ b/Code/Editor/Util/IXmlHistoryManager.h
@@ -62,7 +62,7 @@ struct IXmlHistoryManager
     // History
     virtual void ClearHistory(bool flagAsSaved = false) = 0;
     virtual int GetVersionCount() const = 0;
-    virtual const string& GetVersionDesc(int number) const = 0;
+    virtual const AZStd::string& GetVersionDesc(int number) const = 0;
     virtual int GetCurrentVersionNumber() const = 0;
 
     // Views
diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp
index a6bf622ad0..bf607e475e 100644
--- a/Code/Editor/Util/StringHelpers.cpp
+++ b/Code/Editor/Util/StringHelpers.cpp
@@ -84,7 +84,7 @@ static inline int Vsnprintf_s(wchar_t* str, size_t sizeInBytes, [[maybe_unused]]
 }
 
 
-int StringHelpers::Compare(const string& str0, const string& str1)
+int StringHelpers::Compare(const AZStd::string& str0, const AZStd::string& str1)
 {
     const size_t minLength = Util::getMin(str0.length(), str1.length());
     const int result = std::memcmp(str0.c_str(), str1.c_str(), minLength);
@@ -119,7 +119,7 @@ int StringHelpers::Compare(const wstring& str0, const wstring& str1)
 }
 
 
-int StringHelpers::CompareIgnoreCase(const string& str0, const string& str1)
+int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
 {
     const size_t minLength = Util::getMin(str0.length(), str1.length());
     const int result = azmemicmp(str0.c_str(), str1.c_str(), minLength);
@@ -154,7 +154,7 @@ int StringHelpers::CompareIgnoreCase(const wstring& str0, const wstring& str1)
 }
 
 
-bool StringHelpers::Equals(const string& str0, const string& str1)
+bool StringHelpers::Equals(const AZStd::string& str0, const AZStd::string& str1)
 {
     if (str0.length() != str1.length())
     {
@@ -173,7 +173,7 @@ bool StringHelpers::Equals(const wstring& str0, const wstring& str1)
 }
 
 
-bool StringHelpers::EqualsIgnoreCase(const string& str0, const string& str1)
+bool StringHelpers::EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
 {
     if (str0.length() != str1.length())
     {
@@ -200,7 +200,7 @@ bool StringHelpers::EqualsIgnoreCase(const wstring& str0, const wstring& str1)
 }
 
 
-bool StringHelpers::StartsWith(const string& str, const string& pattern)
+bool StringHelpers::StartsWith(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -219,7 +219,7 @@ bool StringHelpers::StartsWith(const wstring& str, const wstring& pattern)
 }
 
 
-bool StringHelpers::StartsWithIgnoreCase(const string& str, const string& pattern)
+bool StringHelpers::StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -246,7 +246,7 @@ bool StringHelpers::StartsWithIgnoreCase(const wstring& str, const wstring& patt
 }
 
 
-bool StringHelpers::EndsWith(const string& str, const string& pattern)
+bool StringHelpers::EndsWith(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -265,7 +265,7 @@ bool StringHelpers::EndsWith(const wstring& str, const wstring& pattern)
 }
 
 
-bool StringHelpers::EndsWithIgnoreCase(const string& str, const string& pattern)
+bool StringHelpers::EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -292,7 +292,7 @@ bool StringHelpers::EndsWithIgnoreCase(const wstring& str, const wstring& patter
 }
 
 
-bool StringHelpers::Contains(const string& str, const string& pattern)
+bool StringHelpers::Contains(const AZStd::string& str, const AZStd::string& pattern)
 {
     const size_t patternLength = pattern.length();
     if (str.length() < patternLength)
@@ -329,7 +329,7 @@ bool StringHelpers::Contains(const wstring& str, const wstring& pattern)
 }
 
 
-bool StringHelpers::ContainsIgnoreCase(const string& str, const string& pattern)
+bool StringHelpers::ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
 {
     const size_t patternLength = pattern.length();
     if (str.length() < patternLength)
@@ -380,7 +380,7 @@ bool StringHelpers::ContainsIgnoreCase(const wstring& str, const wstring& patter
     return false;
 }
 
-string StringHelpers::TrimLeft(const string& s)
+string StringHelpers::TrimLeft(const AZStd::string& s)
 {
     const size_t first = s.find_first_not_of(" \r\t");
     return (first == s.npos) ? string() : s.substr(first);
@@ -393,7 +393,7 @@ wstring StringHelpers::TrimLeft(const wstring& s)
 }
 
 
-string StringHelpers::TrimRight(const string& s)
+string StringHelpers::TrimRight(const AZStd::string& s)
 {
     const size_t last = s.find_last_not_of(" \r\t");
     return (last == s.npos) ? s : s.substr(0, last + 1);
@@ -406,7 +406,7 @@ wstring StringHelpers::TrimRight(const wstring& s)
 }
 
 
-string StringHelpers::Trim(const string& s)
+string StringHelpers::Trim(const AZStd::string& s)
 {
     return TrimLeft(TrimRight(s));
 }
@@ -447,7 +447,7 @@ static inline TS RemoveDuplicateSpaces_Tpl(const TS& s)
     return res;
 }
 
-string StringHelpers::RemoveDuplicateSpaces(const string& s)
+string StringHelpers::RemoveDuplicateSpaces(const AZStd::string& s)
 {
     return RemoveDuplicateSpaces_Tpl(s);
 }
@@ -470,7 +470,7 @@ static inline TS MakeLowerCase_Tpl(const TS& s)
     return copy;
 }
 
-string StringHelpers::MakeLowerCase(const string& s)
+string StringHelpers::MakeLowerCase(const AZStd::string& s)
 {
     return MakeLowerCase_Tpl(s);
 }
@@ -493,7 +493,7 @@ static inline TS MakeUpperCase_Tpl(const TS& s)
     return copy;
 }
 
-string StringHelpers::MakeUpperCase(const string& s)
+string StringHelpers::MakeUpperCase(const AZStd::string& s)
 {
     return MakeUpperCase_Tpl(s);
 }
@@ -517,7 +517,7 @@ static inline TS Replace_Tpl(const TS& s, const typename TS::value_type oldChar,
     return copy;
 }
 
-string StringHelpers::Replace(const string& s, char oldChar, char newChar)
+string StringHelpers::Replace(const AZStd::string& s, char oldChar, char newChar)
 {
     return Replace_Tpl(s, oldChar, newChar);
 }
@@ -528,12 +528,12 @@ wstring StringHelpers::Replace(const wstring& s, wchar_t oldChar, wchar_t newCha
 }
 
 
-void StringHelpers::ConvertStringByRef(string& out, const string& in)
+void StringHelpers::ConvertStringByRef(string& out, const AZStd::string& in)
 {
     out = in;
 }
 
-void StringHelpers::ConvertStringByRef(wstring& out, const string& in)
+void StringHelpers::ConvertStringByRef(wstring& out, const AZStd::string& in)
 {
     Unicode::Convert(out, in);
 }
@@ -630,7 +630,7 @@ static inline void SplitByAnyOf_Tpl(const TS& str, const TS& separators, bool bR
 
 
 
-void StringHelpers::Split(const string& str, const string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
 }
@@ -641,7 +641,7 @@ void StringHelpers::Split(const wstring& str, const wstring& separator, bool bRe
 }
 
 
-void StringHelpers::SplitByAnyOf(const string& str, const string& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     SplitByAnyOf_Tpl(str, separators, bReturnEmptyPartsToo, outParts);
 }
diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h
index da4aa9c9cc..ec5515fbc9 100644
--- a/Code/Editor/Util/StringHelpers.h
+++ b/Code/Editor/Util/StringHelpers.h
@@ -15,83 +15,83 @@ namespace StringHelpers
 {
     // compares two strings to see if they are the same or different, case sensitive
     // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
-    int Compare(const string& str0, const string& str1);
+    int Compare(const AZStd::string& str0, const AZStd::string& str1);
     int Compare(const wstring& str0, const wstring& str1);
 
     // compares two strings to see if they are the same or different, case is ignored
     // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
-    int CompareIgnoreCase(const string& str0, const string& str1);
+    int CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
     int CompareIgnoreCase(const wstring& str0, const wstring& str1);
 
     // compares two strings to see if they are the same, case senstive
     // returns true if they are the same or false if they are different
-    bool Equals(const string& str0, const string& str1);
+    bool Equals(const AZStd::string& str0, const AZStd::string& str1);
     bool Equals(const wstring& str0, const wstring& str1);
 
     // compares two strings to see if they are the same, case is ignored
     // returns true if they are the same or false if they are different
-    bool EqualsIgnoreCase(const string& str0, const string& str1);
+    bool EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
     bool EqualsIgnoreCase(const wstring& str0, const wstring& str1);
 
     // checks to see if a string starts with a specified string, case sensitive
     // returns true if the string does start with a specified string or false if it does not
-    bool StartsWith(const string& str, const string& pattern);
+    bool StartsWith(const AZStd::string& str, const AZStd::string& pattern);
     bool StartsWith(const wstring& str, const wstring& pattern);
 
     // checks to see if a string starts with a specified string, case is ignored
     // returns true if the string does start with a specified string or false if it does not
-    bool StartsWithIgnoreCase(const string& str, const string& pattern);
+    bool StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
     bool StartsWithIgnoreCase(const wstring& str, const wstring& pattern);
 
     // checks to see if a string ends with a specified string, case sensitive
     // returns true if the string does end with a specified string or false if it does not
-    bool EndsWith(const string& str, const string& pattern);
+    bool EndsWith(const AZStd::string& str, const AZStd::string& pattern);
     bool EndsWith(const wstring& str, const wstring& pattern);
 
     // checks to see if a string ends with a specified string, case is ignored
     // returns true if the string does end with a specified string or false if it does not
-    bool EndsWithIgnoreCase(const string& str, const string& pattern);
+    bool EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
     bool EndsWithIgnoreCase(const wstring& str, const wstring& pattern);
 
     // checks to see if a string contains a specified string, case sensitive
     // returns true if the string does contain the specified string or false if it does not
-    bool Contains(const string& str, const string& pattern);
+    bool Contains(const AZStd::string& str, const AZStd::string& pattern);
     bool Contains(const wstring& str, const wstring& pattern);
 
     // checks to see if a string contains a specified string, case is ignored
     // returns true if the string does contain the specified string or false if it does not
-    bool ContainsIgnoreCase(const string& str, const string& pattern);
+    bool ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
     bool ContainsIgnoreCase(const wstring& str, const wstring& pattern);
 
-    string TrimLeft(const string& s);
+    string TrimLeft(const AZStd::string& s);
     wstring TrimLeft(const wstring& s);
 
-    string TrimRight(const string& s);
+    string TrimRight(const AZStd::string& s);
     wstring TrimRight(const wstring& s);
 
-    string Trim(const string& s);
+    string Trim(const AZStd::string& s);
     wstring Trim(const wstring& s);
 
-    string RemoveDuplicateSpaces(const string& s);
+    string RemoveDuplicateSpaces(const AZStd::string& s);
     wstring RemoveDuplicateSpaces(const wstring& s);
 
     // converts a string with upper case characters to be all lower case
     // returns the string in all lower case
-    string MakeLowerCase(const string& s);
+    string MakeLowerCase(const AZStd::string& s);
     wstring MakeLowerCase(const wstring& s);
 
     // converts a string with lower case characters to be all upper case
     // returns the string in all upper case
-    string MakeUpperCase(const string& s);
+    string MakeUpperCase(const AZStd::string& s);
     wstring MakeUpperCase(const wstring& s);
 
     // replace a specified character in a string with a specified replacement character
     // returns string with specified character replaced
-    string Replace(const string& s, char oldChar, char newChar);
+    string Replace(const AZStd::string& s, char oldChar, char newChar);
     wstring Replace(const wstring& s, wchar_t oldChar, wchar_t newChar);
 
-    void ConvertStringByRef(string& out, const string& in);
-    void ConvertStringByRef(wstring& out, const string& in);
+    void ConvertStringByRef(string& out, const AZStd::string& in);
+    void ConvertStringByRef(wstring& out, const AZStd::string& in);
     void ConvertStringByRef(string& out, const wstring& in);
     void ConvertStringByRef(wstring& out, const wstring& in);
 
@@ -103,10 +103,10 @@ namespace StringHelpers
         return out;
     }
     
-    void Split(const string& str, const string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
+    void Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
     void Split(const wstring& str, const wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
 
-    void SplitByAnyOf(const string& str, const string& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
+    void SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
     void SplitByAnyOf(const wstring& str, const wstring& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
 
     string FormatVA(const char* const format, va_list parg);
diff --git a/Code/Editor/Util/XmlHistoryManager.cpp b/Code/Editor/Util/XmlHistoryManager.cpp
index 3aea041d29..5a1bc237bb 100644
--- a/Code/Editor/Util/XmlHistoryManager.cpp
+++ b/Code/Editor/Util/XmlHistoryManager.cpp
@@ -419,7 +419,7 @@ void CXmlHistoryManager::ClearHistory(bool flagAsSaved)
 }
 
 /////////////////////////////////////////////////////////////////////////////
-const string& CXmlHistoryManager::GetVersionDesc(int number) const
+const AZStd::string& CXmlHistoryManager::GetVersionDesc(int number) const
 {
     THistoryInfoMap::const_iterator it = m_HistoryInfoMap.find(number);
     if (it != m_HistoryInfoMap.end())
diff --git a/Code/Editor/Util/XmlHistoryManager.h b/Code/Editor/Util/XmlHistoryManager.h
index d894bc7f00..12699536e5 100644
--- a/Code/Editor/Util/XmlHistoryManager.h
+++ b/Code/Editor/Util/XmlHistoryManager.h
@@ -103,7 +103,7 @@ public:
     // History
     void ClearHistory(bool flagAsSaved = false);
     int GetVersionCount() const { return m_LatestVersion; }
-    const string& GetVersionDesc(int number) const;
+    const AZStd::string& GetVersionDesc(int number) const;
     int GetCurrentVersionNumber() const { return m_CurrentVersion; }
 
     // Views
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
index 3c3c1183e4..23e967c3fa 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
@@ -417,7 +417,7 @@ namespace GridMate
     {
         GM_CLASS_ALLOCATOR(Connection); // make a pool and use it...
 
-        Connection(CarrierThread* threadOwner, const string& address);
+        Connection(CarrierThread* threadOwner, const AZStd::string& address);
         ~Connection();
 
         CarrierThread*              m_threadOwner;                                  ///< Pointer to the carrier thread that operates with this connection.
@@ -999,7 +999,7 @@ namespace GridMate
         /// Connect with host and port. This is ASync operation, the connection is active after OnConnectionEstablished is called.
         ConnectionID    Connect(const char* hostAddress, unsigned int port) override;
         /// Connect with internal address format. This is ASync operation, the connection is active after OnConnectionEstablished is called.
-        ConnectionID    Connect(const string& address) override;
+        ConnectionID    Connect(const AZStd::string& address) override;
         /// Request a disconnect procedure. This is ASync operation, the connection is closed after OnDisconnect is called.
         void            Disconnect(ConnectionID id) override;
 
@@ -1118,7 +1118,7 @@ using namespace GridMate;
 // Connection
 //////////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////////
-Connection::Connection(CarrierThread* threadOwner, const string& address)
+Connection::Connection(CarrierThread* threadOwner, const AZStd::string& address)
     : m_threadOwner(threadOwner)
     , m_threadConn(NULL)
     , m_fullAddress(address)
@@ -3740,7 +3740,7 @@ CarrierImpl::Connect(const char* hostAddress, unsigned int port)
 // [1/12/2011]
 //=========================================================================
 ConnectionID
-CarrierImpl::Connect(const string& address)
+CarrierImpl::Connect(const AZStd::string& address)
 {
     // check if we don't have it in the list.
     for(auto& i : m_connections)
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
index 5bfa621af1..2968582c0d 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
@@ -88,7 +88,7 @@ namespace GridMate
         /// Connect with host and port. This is ASync operation, the connection is active after OnConnectionEstablished is called.
         virtual ConnectionID    Connect(const char* hostAddress, unsigned int port) = 0;
         /// Connect with internal address format. This is ASync operation, the connection is active after OnConnectionEstablished is called.
-        virtual ConnectionID    Connect(const string& address) = 0;
+        virtual ConnectionID    Connect(const AZStd::string& address) = 0;
         /// Request a disconnect procedure. This is ASync operation, the connection is closed after OnDisconnect is called.
         virtual void            Disconnect(ConnectionID id) = 0;
 
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp
index bc657becbc..58436bb757 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp
@@ -98,7 +98,7 @@ DefaultHandshake::OnConfirmAck(ConnectionID id, ReadBuffer& rb)
 // [11/5/2010]
 //=========================================================================
 bool
-DefaultHandshake::OnNewConnection(const string& address)
+DefaultHandshake::OnNewConnection(const AZStd::string& address)
 {
     (void)address;
     return true; /// We don't have a ban list yet
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
index 0b9240dfa3..8f456e4649 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
@@ -47,7 +47,7 @@ namespace GridMate
         */
         virtual bool                OnConfirmAck(ConnectionID id, ReadBuffer& rb);
         /// Return true if you want to reject early reject a connection.
-        virtual bool                OnNewConnection(const string& address);
+        virtual bool                OnNewConnection(const AZStd::string& address);
         /// Called when we close a connection.
         virtual void                OnDisconnect(ConnectionID id);
         /// Return timeout in milliseconds of the handshake procedure.
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Driver.h b/Code/Framework/GridMate/GridMate/Carrier/Driver.h
index 84e43b5acf..2c806be5e0 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Driver.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Driver.h
@@ -140,7 +140,7 @@ namespace GridMate
         /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data.
         ///  Create address from ip and port. If ip == NULL we will assign a broadcast address.
         virtual string          IPPortToAddress(const char* ip, unsigned int port) const = 0;
-        virtual bool            AddressToIPPort(const string& address, string& ip, unsigned int& port) const = 0;
+        virtual bool            AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const = 0;
         /// @}
 
         /**
@@ -150,7 +150,7 @@ namespace GridMate
          * \note Driver address allocates internal resources, use it only when you intend to communicate. Otherwise operate with
          * the string address.
          */
-        virtual AZStd::intrusive_ptr CreateDriverAddress(const string& address) = 0;
+        virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address) = 0;
 
         /**
          * Returns true if the driver can accept new data (ex, has buffer space).
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
index 5d06f2f1b8..ffd332b65c 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
@@ -53,7 +53,7 @@ namespace GridMate
          */
         virtual bool                OnConfirmAck(ConnectionID id, ReadBuffer& rb) = 0;
         /// Return true if you want to reject early reject a connection.
-        virtual bool                OnNewConnection(const string& address) = 0;
+        virtual bool                OnNewConnection(const AZStd::string& address) = 0;
         /// Called when we close a connection.
         virtual void                OnDisconnect(ConnectionID id) = 0;
         /// Return timeout in milliseconds of the handshake procedure.
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
index b75de6f383..fc3062062c 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
@@ -498,7 +498,7 @@ namespace GridMate
         }
     }
 
-    SocketDriverAddress::SocketDriverAddress(Driver* driver, const string& ip, unsigned int port)
+    SocketDriverAddress::SocketDriverAddress(Driver* driver, const AZStd::string& ip, unsigned int port)
         : DriverAddress(driver)
     {
         AZ_Assert(!ip.empty(), "Invalid address string!");
@@ -1156,7 +1156,7 @@ namespace GridMate
     // [3/4/2013]
     //=========================================================================
     bool
-    SocketDriverCommon::AddressStringToIPPort(const string& address, string& ip, unsigned int& port)
+    SocketDriverCommon::AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port)
     {
         AZStd::size_t pos = address.find('|');
         AZ_Assert(pos != string::npos, "Invalid driver address!");
@@ -1176,7 +1176,7 @@ namespace GridMate
     // [7/11/2013]
     //=========================================================================
     Driver::BSDSocketFamilyType
-    SocketDriverCommon::AddressFamilyType(const string& ip)
+    SocketDriverCommon::AddressFamilyType(const AZStd::string& ip)
     {
         // TODO: We can/should use inet_ntop() to detect the family type
         AZStd::size_t pos = ip.find(".");
@@ -1198,13 +1198,13 @@ namespace GridMate
     //////////////////////////////////////////////////////////////////////////
     //////////////////////////////////////////////////////////////////////////
     //=========================================================================
-    // CreateDriverAddress(const string&)
+    // CreateDriverAddress(const AZStd::string&)
     // [1/12/2011]
     //=========================================================================
     AZStd::intrusive_ptr
-    SocketDriver::CreateDriverAddress(const string& address)
+    SocketDriver::CreateDriverAddress(const AZStd::string& address)
     {
-        string ip;
+        AZStd::string ip;
         unsigned int port;
         if (!AddressToIPPort(address, ip, port))
         {
@@ -1243,7 +1243,7 @@ namespace GridMate
     namespace Utils
     {
         // \note function moved here to use addinfo when IPV6 is not in use, consider moving those definitions to a header file
-        bool GetIpByHostName(int familyType, const char* hostName, string& ip)
+        bool GetIpByHostName(int familyType, const char* hostName, AZStd::string& ip)
         {
             static const size_t kMaxLen = 64; // max length of ipv6 ip is 45 chars, so all ips should be able to fit in this buf
             char ipBuf[kMaxLen];
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
index bda135f532..7555c92639 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
@@ -83,7 +83,7 @@ namespace GridMate
 
         SocketDriverAddress(Driver* driver);
         SocketDriverAddress(Driver* driver, const sockaddr* addr);
-        SocketDriverAddress(Driver* driver, const string& ip, unsigned int port);
+        SocketDriverAddress(Driver* driver, const AZStd::string& ip, unsigned int port);
 
         bool operator==(const SocketDriverAddress& rhs) const;
         bool operator!=(const SocketDriverAddress& rhs) const;
@@ -164,17 +164,17 @@ namespace GridMate
         /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data.
         ///  Create address from ip and port. If ip == NULL we will assign a broadcast address.
         virtual string  IPPortToAddress(const char* ip, unsigned int port) const                        { return IPPortToAddressString(ip, port); }
-        virtual bool    AddressToIPPort(const string& address, string& ip, unsigned int& port) const    { return AddressStringToIPPort(address, ip, port); }
+        virtual bool    AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const    { return AddressStringToIPPort(address, ip, port); }
         /// Create address for the socket driver from IP and port
         static string   IPPortToAddressString(const char* ip, unsigned int port);
         /// Decompose an address to IP and port
-        static bool     AddressStringToIPPort(const string& address, string& ip, unsigned int& port);
+        static bool     AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port);
         /// Return the family type of the address (AF_INET,AF_INET6 AF_UNSPEC)
-        static BSDSocketFamilyType  AddressFamilyType(const string& ip);
+        static BSDSocketFamilyType  AddressFamilyType(const AZStd::string& ip);
         static BSDSocketFamilyType  AddressFamilyType(const char* ip)           { return AddressFamilyType(string(ip)); }
         /// @}
 
-        virtual AZStd::intrusive_ptr CreateDriverAddress(const string& address) = 0;
+        virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address) = 0;
         /// Additional CreateDriverAddress function should be implemented.
         virtual AZStd::intrusive_ptr CreateDriverAddress(const sockaddr* sockAddr) = 0;
 
@@ -352,7 +352,7 @@ namespace GridMate
         * \note Driver address allocates internal resources, use it only when you intend to communicate. Otherwise operate with
         * the string address.
         */
-        virtual AZStd::intrusive_ptr CreateDriverAddress(const string& address);
+        virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address);
         virtual AZStd::intrusive_ptr CreateDriverAddress(const sockaddr* addr);
         /// Called only from the DriverAddress when the use count becomes 0
         virtual void    DestroyDriverAddress(DriverAddress* address);
@@ -364,7 +364,7 @@ namespace GridMate
     namespace Utils
     {
         ///< Retrieves ip address corresponding to a host name. Blocks thread until dns resolving is happened.
-        bool GetIpByHostName(int familyType, const char* hostName, string& ip);
+        bool GetIpByHostName(int familyType, const char* hostName, AZStd::string& ip);
     }
 
     /**
diff --git a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp
index 5a34b70e74..a7130218f8 100644
--- a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp
+++ b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp
@@ -224,7 +224,7 @@ namespace GridMate
         // [4/15/2011]
         //=========================================================================
         void
-        SessionDriller::OnSessionError(GridSession* session, const string& errorMsg)
+        SessionDriller::OnSessionError(GridSession* session, const AZStd::string& errorMsg)
         {
             m_output->BeginTag(m_drillerTag);
             m_output->BeginTag(AZ_CRC("SessionError", 0xc689cc40));
diff --git a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h
index b89fae3d73..59f178976f 100644
--- a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h
+++ b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h
@@ -62,7 +62,7 @@ namespace GridMate
             /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns.
             virtual void OnSessionDelete(GridSession* session);
             /// Called when a session error occurs.
-            virtual void OnSessionError(GridSession* session, const string& errorMsg);
+            virtual void OnSessionError(GridSession* session, const AZStd::string& errorMsg);
             /// Called when the actual game(match) starts
             virtual void OnSessionStart(GridSession* session);
             /// Called when the actual game(match) ends
diff --git a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
index fca43c2709..0127d8fa23 100644
--- a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
+++ b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
@@ -37,7 +37,7 @@ namespace GridMate
     {
         friend class LANMemberIDMarshaler;
 
-        static LANMemberID Create(MemberIDCompact id, const string& address)
+        static LANMemberID Create(MemberIDCompact id, const AZStd::string& address)
         {
             LANMemberID mid;
             mid.m_id = id;
@@ -45,7 +45,7 @@ namespace GridMate
             return mid;
         }
 
-        void SetAddress(const string& address)
+        void SetAddress(const AZStd::string& address)
         {
             m_address = address;
         }
@@ -120,14 +120,14 @@ namespace GridMate
         /// Creates the local player.
         GridMember* CreateLocalMember(bool isHost, bool isInvited, RemotePeerMode peerMode);
         /// Creates remote player, when he wants to join.
-        GridMember* CreateRemoteMember(const string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) override;
+        GridMember* CreateRemoteMember(const AZStd::string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) override;
 
         /// Called when we receive the session replica. We create one and return the pointer.
         LANSessionReplica*  OnSessionReplicaArrived();
 
         /// Called when session parameters have changed.
         void OnSessionParamChanged(const GridSessionParam& param) override { (void)param; }
-        void OnSessionParamRemoved(const string& paramId) override { (void)paramId; }
+        void OnSessionParamRemoved(const AZStd::string& paramId) override { (void)paramId; }
 
     private:
         explicit LANSession(LANSessionService* service);
@@ -762,7 +762,7 @@ LANSession::CreateLocalMember(bool isHost, bool isInvited, RemotePeerMode peerMo
 // [2/2/2011]
 //==========================================================================
 GridMember*
-LANSession::CreateRemoteMember(const string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId)
+LANSession::CreateRemoteMember(const AZStd::string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId)
 {
     MemberIDCompact id;
     data.Read(id);
@@ -803,7 +803,7 @@ LANSession::OnStateCreate(AZ::HSM& sm, const AZ::HSM::Event& e)
     {
         // patch the ID if we use implicit port
         AZ_Assert(m_carrier, "Carrier must be created!");
-        string ip;
+        AZStd::string ip;
         unsigned int port;
         SocketDriverCommon::AddressStringToIPPort(m_myMember->GetId().ToAddress(), ip, port);
         AZ_Assert(port == 0 || port == m_carrier->GetPort(), "Carrier port missmatch! It should either be 0 (and patched here) in the implicit bind or the port number for explicit bind!");
diff --git a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
index ee4c0a8659..20ade42a6e 100644
--- a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
+++ b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
@@ -39,9 +39,9 @@ namespace GridMate
         {}
 
         int     m_familyType;                   ///< Socket driver specific, by default 0.
-        string  m_serverAddress;                ///< Address of the server, we empty we create a broadcast address.
+        AZStd::string  m_serverAddress;         ///< Address of the server, we empty we create a broadcast address.
         int     m_serverPort;                   ///< Server port (must be provided).
-        string  m_listenAddress;                ///< Address to bind for listening. By default is empty, which means we are listening to any address.
+        AZStd::string  m_listenAddress;         ///< Address to bind for listening. By default is empty, which means we are listening to any address.
         int     m_listenPort;                   ///< Search listen port, if not set we will use ephimeral port.
         unsigned int m_broadcastFrequencyMs;    ///< Time in MS between search broadcasts.
     };
@@ -52,7 +52,7 @@ namespace GridMate
     struct LANSearchInfo
         : public SearchInfo
     {
-        string m_serverIP; ///< server ID as we see it
+        AZStd::string m_serverIP; ///< server ID as we see it
         AZ::u16 m_serverPort; ///< server port for the session
     };
 }
diff --git a/Code/Framework/GridMate/GridMate/Session/Session.cpp b/Code/Framework/GridMate/GridMate/Session/Session.cpp
index 5746a91c19..8a9bdea273 100644
--- a/Code/Framework/GridMate/GridMate/Session/Session.cpp
+++ b/Code/Framework/GridMate/GridMate/Session/Session.cpp
@@ -92,7 +92,7 @@ namespace GridMate
             */
             virtual bool            OnConfirmAck(ConnectionID id, ReadBuffer& rb)   { (void)id; (void)rb; return true; } // we don't do any further filtering
             /// Return true if you want to reject early reject a connection.
-            virtual bool            OnNewConnection(const string& address);
+            virtual bool            OnNewConnection(const AZStd::string& address);
             /// Called when we close a connection.
             virtual void            OnDisconnect(ConnectionID id);
             /// Return timeout in milliseconds of the handshake procedure.
@@ -684,7 +684,7 @@ GridSession::SetParam(const GridSessionParam& param)
 // RemoveParam
 //=========================================================================
 bool
-GridSession::RemoveParam(const string& paramId)
+GridSession::RemoveParam(const AZStd::string& paramId)
 {
     AZ_Assert(m_state, "Invalid session state replica. Session is not initialized.");
 
@@ -970,7 +970,7 @@ GridSession::AddMember(GridMember* member)
 // IsAddressInMemberList
 //=========================================================================
 bool
-GridSession::IsAddressInMemberList(const string& address)
+GridSession::IsAddressInMemberList(const AZStd::string& address)
 {
     for (AZStd::size_t i = 0; i < m_members.size(); ++i)
     {
@@ -2783,7 +2783,7 @@ bool GridSessionHandshake::OnConfirmRequest(ConnectionID id, ReadBuffer& rb)
 //=========================================================================
 // OnNewConnection
 //=========================================================================
-bool GridSessionHandshake::OnNewConnection(const string& address)
+bool GridSessionHandshake::OnNewConnection(const AZStd::string& address)
 {
     AZStd::lock_guard l(m_dataLock);
 
diff --git a/Code/Framework/GridMate/GridMate/Session/Session.h b/Code/Framework/GridMate/GridMate/Session/Session.h
index 63aa504a49..03556756ba 100644
--- a/Code/Framework/GridMate/GridMate/Session/Session.h
+++ b/Code/Framework/GridMate/GridMate/Session/Session.h
@@ -249,7 +249,7 @@ namespace GridMate
         /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns.
         virtual void OnSessionDelete(GridSession* session) { (void)session; }
         /// Called when a session error occurs.
-        virtual void OnSessionError(GridSession* session, const string& errorMsg) { (void)session; (void)errorMsg; }
+        virtual void OnSessionError(GridSession* session, const AZStd::string& errorMsg) { (void)session; (void)errorMsg; }
         /// Called when the actual game(match) starts
         virtual void OnSessionStart(GridSession* session) { (void)session; }
         /// Called when the actual game(match) ends
@@ -484,7 +484,7 @@ namespace GridMate
         // Adds/updates a parameter. Returns false if parameter can not be added.
         bool SetParam(const GridSessionParam& param);
         // Removes a parameter by id. Returns false if parameter can not be removed.
-        bool RemoveParam(const string& paramId);
+        bool RemoveParam(const AZStd::string& paramId);
         // Removes a parameter by index. Returns false if parameter can not be removed.
         bool RemoveParam(unsigned int index);
 
@@ -543,9 +543,9 @@ namespace GridMate
         /// Frees a slot based on a slot type.
         void FreeSlot(int slotType);
         /// Creates remote player, when he wants to join.
-        virtual GridMember* CreateRemoteMember(const string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) = 0;
+        virtual GridMember* CreateRemoteMember(const AZStd::string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) = 0;
         /// Returns true if this address belongs to a member in the list, otherwise false.
-        virtual bool IsAddressInMemberList(const string& address);
+        virtual bool IsAddressInMemberList(const AZStd::string& address);
         virtual bool IsConnectionIdInMemberList(const ConnectionID& connId);
         /// Adds a created member to the session. Return false if no free slow was found!
         virtual bool AddMember(GridMember* member);
@@ -558,7 +558,7 @@ namespace GridMate
         /// Called when a session parameter is added/changed.
         virtual void OnSessionParamChanged(const GridSessionParam& param) = 0;
         /// Called when a session parameter is deleted.
-        virtual void OnSessionParamRemoved(const string& paramId) = 0;
+        virtual void OnSessionParamRemoved(const AZStd::string& paramId) = 0;
         //////////////////////////////////////////////////////////////////////////
 
         SessionID m_sessionId; ///< Session id. Content of the string will vary based on session types and platforms.
@@ -975,7 +975,7 @@ namespace GridMate
             /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns.
             virtual void OnSessionDelete(GridSession* session) { (void)session; }
             /// Called when a session error occurs.
-            virtual void OnSessionError(GridSession* session, const string& errorMsg) { (void)session; (void)errorMsg; }
+            virtual void OnSessionError(GridSession* session, const AZStd::string& errorMsg) { (void)session; (void)errorMsg; }
             /// Called when the actual game(match) starts
             virtual void OnSessionStart(GridSession* session) { (void)session; }
             /// Called when the actual game(match) ends
diff --git a/Code/Framework/GridMate/Tests/Session.cpp b/Code/Framework/GridMate/Tests/Session.cpp
index 9e10e84e98..0c5baef483 100644
--- a/Code/Framework/GridMate/Tests/Session.cpp
+++ b/Code/Framework/GridMate/Tests/Session.cpp
@@ -241,7 +241,7 @@ namespace UnitTest
                 (void)reason;
             }
 
-            void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+            void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
             {
                 (void)session;
 #ifndef AZ_LAN_TEST_MAIN_THREAD_BLOCKED  // we will receive an error is we block for a long time
@@ -599,7 +599,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             AZ_TEST_ASSERT(false);
@@ -834,7 +834,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
 #ifndef AZ_LAN_TEST_MAIN_THREAD_BLOCKED  // we will receive an error is we block for a long time
@@ -1207,7 +1207,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             AZ_TEST_ASSERT(false);
@@ -1521,7 +1521,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             // On this test we will get a open port error because we have multiple hosts. This is ok, since we test migration here!
@@ -1861,7 +1861,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             // On this test we will get a open port error because we have multiple hosts. This is ok, since we test migration here!
diff --git a/Code/Framework/GridMate/Tests/TestProfiler.cpp b/Code/Framework/GridMate/Tests/TestProfiler.cpp
index 428c1249ee..9f79d5a9fe 100644
--- a/Code/Framework/GridMate/Tests/TestProfiler.cpp
+++ b/Code/Framework/GridMate/Tests/TestProfiler.cpp
@@ -34,7 +34,7 @@ static bool CollectPerformanceCounters(const AZ::Debug::ProfilerRegister& reg, c
     return true;
 }
 
-static string FormatString(const string& pre, const string& name, const string& post, AZ::u64 time, AZ::u64 calls)
+static string FormatString(const AZStd::string& pre, const AZStd::string& name, const AZStd::string& post, AZ::u64 time, AZ::u64 calls)
 {
     string units = "us";
     if (AZ::u64 divtime = time / 1000)
diff --git a/Code/Legacy/CryCommon/LocalizationManagerBus.h b/Code/Legacy/CryCommon/LocalizationManagerBus.h
index 69ab32cebf..1d818de111 100644
--- a/Code/Legacy/CryCommon/LocalizationManagerBus.h
+++ b/Code/Legacy/CryCommon/LocalizationManagerBus.h
@@ -102,7 +102,7 @@ public:
     virtual bool LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0;
 
     // Summary:
-    //   Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false )
+    //   Same as LocalizeString( const char* sString, AZStd::string& outLocalizedString, bool bEnglish=false )
     //   but at the moment this is faster.
     virtual bool LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0;
 
diff --git a/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h b/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h
index 3515dab68e..e04fb6ada7 100644
--- a/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h
+++ b/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h
@@ -120,7 +120,7 @@ public:
     CUiAnimParamType()
         : m_type(eUiAnimParamType_Invalid) {}
 
-    CUiAnimParamType(const string& name)
+    CUiAnimParamType(const AZStd::string& name)
     {
         *this = name;
     }
@@ -136,17 +136,12 @@ public:
         m_type = (EUiAnimParamType)type;
     }
 
-    void operator =(const string& name)
-    {
-        m_type = eUiAnimParamType_ByString;
-        m_name = name;
-    }
-
     void operator =(const AZStd::string& name)
     {
         m_type = eUiAnimParamType_ByString;
         m_name = name.c_str();
     }
+
     // Convert to enum. This needs to be explicit,
     // otherwise operator== will be ambiguous
     EUiAnimParamType GetType() const { return m_type; }
@@ -1301,7 +1296,7 @@ inline void SUiAnimContext::Serialize(IUiAnimationSystem* animationSystem, XmlNo
     {
         if (pSequence)
         {
-            string fullname = pSequence->GetName();
+            AZStd::string fullname = pSequence->GetName();
             xmlNode->setAttr("sequence", fullname.c_str());
         }
         xmlNode->setAttr("dt", dt);
diff --git a/Code/Legacy/CryCommon/LyShine/ISprite.h b/Code/Legacy/CryCommon/LyShine/ISprite.h
index cd2b70ef25..373024d2db 100644
--- a/Code/Legacy/CryCommon/LyShine/ISprite.h
+++ b/Code/Legacy/CryCommon/LyShine/ISprite.h
@@ -59,10 +59,10 @@ public: // member functions
     virtual ~ISprite() {}
 
     //! Get the pathname of this sprite
-    virtual const string& GetPathname() const = 0;
+    virtual const AZStd::string& GetPathname() const = 0;
 
     //! Get the pathname of the texture of this sprite
-    virtual const string& GetTexturePathname() const = 0;
+    virtual const AZStd::string& GetTexturePathname() const = 0;
 
     //! Get the borders of this sprite
     virtual Borders GetBorders() const = 0;
@@ -77,7 +77,7 @@ public: // member functions
     virtual void Serialize(TSerialize ser) = 0;
 
     //! Save this sprite data to disk
-    virtual bool SaveToXml(const string& pathname) = 0;
+    virtual bool SaveToXml(const AZStd::string& pathname) = 0;
 
     //! Test if this sprite has any borders
     virtual bool AreBordersZeroWidth() const = 0;
@@ -136,4 +136,3 @@ public: // member functions
     //! Returns true if this sprite is configured as a sprite-sheet, false otherwise
     virtual bool IsSpriteSheet() const = 0;
 };
-

From 58f1cb9b6c02f4a315c3b21ba6212e382a92166c Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:55:08 -0700
Subject: [PATCH 065/251] Gems/LytShine

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Animation/Controls/UiSplineCtrlEx.cpp     |  2 +-
 .../Animation/Controls/UiSplineCtrlEx.h       |  4 +-
 .../Editor/Animation/UiAnimViewAnimNode.cpp   |  4 +-
 .../Editor/Animation/UiAnimViewDialog.cpp     |  6 +--
 .../Editor/Animation/UiAnimViewFindDlg.cpp    |  3 +-
 .../Animation/UiAnimViewNewSequenceDialog.cpp |  2 +-
 .../Code/Editor/Animation/UiAnimViewNodes.cpp | 14 +++---
 .../Editor/Animation/UiAnimViewSequence.cpp   | 12 ++---
 .../Code/Editor/Animation/UiAnimViewUndo.cpp  |  6 +--
 .../Code/Editor/Animation/UiAnimViewUndo.h    |  6 +--
 Gems/LyShine/Code/Editor/AssetTreeEntry.cpp   |  2 +-
 Gems/LyShine/Code/Editor/EditorMenu.cpp       |  2 +-
 .../Code/Editor/PropertiesContainer.cpp       |  2 +-
 .../Code/Editor/PropertyHandlerChar.cpp       | 13 +++---
 .../Code/Editor/PropertyHandlerDirectory.cpp  |  8 ++--
 .../Code/Editor/SpriteBorderEditor.cpp        |  2 +-
 .../Code/Source/Animation/AnimSequence.cpp    |  4 +-
 .../Code/Source/Animation/AnimSequence.h      |  2 +-
 .../Code/Source/Animation/AzEntityNode.cpp    |  4 +-
 .../Code/Source/Animation/AzEntityNode.h      |  6 +--
 .../Source/Animation/CompoundSplineTrack.h    |  2 +-
 .../Source/Animation/UiAnimationSystem.cpp    | 18 ++++----
 Gems/LyShine/Code/Source/LyShine.cpp          | 10 ++---
 Gems/LyShine/Code/Source/LyShine.h            | 10 ++---
 Gems/LyShine/Code/Source/LyShineDebug.cpp     |  4 +-
 .../LyShine/Code/Source/LyShineLoadScreen.cpp |  6 +--
 .../Platform/Windows/UiClipboard_Windows.cpp  |  6 ++-
 Gems/LyShine/Code/Source/Sprite.cpp           | 18 ++++----
 Gems/LyShine/Code/Source/Sprite.h             | 16 +++----
 Gems/LyShine/Code/Source/StringUtfUtils.h     | 25 +++++------
 .../Tests/internal/test_UiTextComponent.cpp   |  2 +-
 Gems/LyShine/Code/Source/TextMarkup.cpp       |  3 +-
 .../LyShine/Code/Source/UiCanvasComponent.cpp | 12 ++---
 Gems/LyShine/Code/Source/UiCanvasComponent.h  |  6 +--
 Gems/LyShine/Code/Source/UiCanvasManager.cpp  | 16 +++----
 Gems/LyShine/Code/Source/UiCanvasManager.h    |  2 +-
 .../Code/Source/UiDropdownComponent.cpp       |  3 +-
 .../Code/Source/UiInteractableState.cpp       |  2 +-
 Gems/LyShine/Code/Source/UiTextComponent.cpp  | 44 +++++++++++--------
 .../Source/UiTextComponentOffsetsSelector.cpp |  2 +-
 .../Code/Source/UiTextInputComponent.cpp      |  5 ++-
 41 files changed, 161 insertions(+), 155 deletions(-)

diff --git a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp
index 39e5bd0f5f..746ea04559 100644
--- a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp
@@ -135,7 +135,7 @@ private:
         std::vector keySelectionFlags;
         _smart_ptr undo;
         _smart_ptr redo;
-        string id;
+        AZStd::string id;
         ISplineInterpolator* pSpline;
     };
 
diff --git a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h
index 18ee7e173c..2a7b0c3d1f 100644
--- a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h
+++ b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h
@@ -45,8 +45,8 @@ class QRubberBand;
 class ISplineSet
 {
 public:
-    virtual ISplineInterpolator* GetSplineFromID(const string& id) = 0;
-    virtual string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
+    virtual ISplineInterpolator* GetSplineFromID(const AZStd::string& id) = 0;
+    virtual AZStd::string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
     virtual int GetSplineCount() const = 0;
     virtual int GetKeyCountAtTime(float time, float threshold) const = 0;
 };
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp
index f860725276..8880795466 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp
@@ -1100,7 +1100,7 @@ bool CUiAnimViewAnimNode::SetName(const char* pName)
         }
     }
 
-    string oldName = GetName();
+    AZStd::string oldName = GetName();
     m_pAnimNode->SetName(pName);
 
     if (UiAnimUndo::IsRecording())
@@ -1108,7 +1108,7 @@ bool CUiAnimViewAnimNode::SetName(const char* pName)
         UiAnimUndo::Record(new CUndoAnimNodeRename(this, oldName));
     }
 
-    GetSequence()->OnNodeRenamed(this, oldName);
+    GetSequence()->OnNodeRenamed(this, oldName.c_str());
 
     return true;
 }
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp
index 61d6b66b29..ac210ba2f2 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp
@@ -992,7 +992,7 @@ void CUiAnimViewDialog::ReloadSequencesComboBox()
         for (int k = 0; k < numSequences; ++k)
         {
             CUiAnimViewSequence* pSequence = pSequenceManager->GetSequenceByIndex(k);
-            QString fullname = QtUtil::ToQString(pSequence->GetName());
+            QString fullname = pSequence->GetName();
             m_sequencesComboBox->addItem(fullname);
         }
     }
@@ -1132,7 +1132,7 @@ void CUiAnimViewDialog::OnSequenceChanged(CUiAnimViewSequence* pSequence)
 
     if (pSequence)
     {
-        m_currentSequenceName = QtUtil::ToQString(pSequence->GetName());
+        m_currentSequenceName = pSequence->GetName();
 
         pSequence->Reset(true);
         SaveZoomScrollSettings();
@@ -1733,7 +1733,7 @@ void CUiAnimViewDialog::OnNodeRenamed(CUiAnimViewNode* pNode, const char* pOldNa
     {
         if (m_currentSequenceName == QString(pOldName))
         {
-            m_currentSequenceName = QtUtil::ToQString(pNode->GetName());
+            m_currentSequenceName = pNode->GetName();
         }
 
         ReloadSequencesComboBox();
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp
index 86f1f786d0..511866db43 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp
@@ -13,7 +13,6 @@
 #include "UiAnimViewSequenceManager.h"
 
 #include 
-#include 
 #include 
 
 #include 
@@ -64,7 +63,7 @@ void CUiAnimViewFindDlg::FillData()
             ObjName obj;
             obj.m_objName = pNode->GetName();
             obj.m_directorName = pNode->HasDirectorAsParent() ? pNode->HasDirectorAsParent()->GetName() : "";
-            string fullname = seq->GetName();
+            AZStd::string fullname = seq->GetName();
             obj.m_seqName = fullname.c_str();
             m_objs.push_back(obj);
         }
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp
index 7c4882e7f0..ac824bfc4d 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp
@@ -46,7 +46,7 @@ void CUiAVNewSequenceDialog::OnOK()
     for (int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k)
     {
         CUiAnimViewSequence* pSequence = CUiAnimViewSequenceManager::GetSequenceManager()->GetSequenceByIndex(k);
-        QString fullname = QtUtil::ToQString(pSequence->GetName());
+        QString fullname = pSequence->GetName();
 
         if (fullname.compare(m_sequenceName, Qt::CaseInsensitive) == 0)
         {
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
index 9cca6cdf8d..67fd542c3f 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
@@ -486,7 +486,7 @@ CUiAnimViewNodesCtrl::CRecord* CUiAnimViewNodesCtrl::AddAnimNodeRecord(CRecord*
 {
     CRecord* pNewRecord = new CRecord(pAnimNode);
 
-    pNewRecord->setText(0, QtUtil::ToQString(pAnimNode->GetName()));
+    pNewRecord->setText(0, pAnimNode->GetName());
     UpdateUiAnimNodeRecord(pNewRecord, pAnimNode);
     pParentRecord->insertChild(GetInsertPosition(pParentRecord, pAnimNode), pNewRecord);
     FillNodesRec(pNewRecord, pAnimNode);
@@ -499,7 +499,7 @@ CUiAnimViewNodesCtrl::CRecord* CUiAnimViewNodesCtrl::AddTrackRecord(CRecord* pPa
 {
     CRecord* pNewTrackRecord = new CRecord(pTrack);
     pNewTrackRecord->setSizeHint(0, QSize(30, 18));
-    pNewTrackRecord->setText(0, QtUtil::ToQString(pTrack->GetName()));
+    pNewTrackRecord->setText(0, pTrack->GetName());
     UpdateTrackRecord(pNewTrackRecord, pTrack);
     pParentRecord->insertChild(GetInsertPosition(pParentRecord, pTrack), pNewTrackRecord);
     FillNodesRec(pNewTrackRecord, pTrack);
@@ -708,7 +708,7 @@ void CUiAnimViewNodesCtrl::OnFillItems()
         m_nodeToRecordMap.clear();
 
         CRecord* pRootGroupRec = new CRecord(pSequence);
-        pRootGroupRec->setText(0, QtUtil::ToQString(pSequence->GetName()));
+        pRootGroupRec->setText(0, pSequence->GetName());
         QFont f = font();
         f.setBold(true);
         pRootGroupRec->setData(0, Qt::FontRole, f);
@@ -1323,7 +1323,7 @@ int CUiAnimViewNodesCtrl::ShowPopupMenuSingleSelection(UiAnimContextMenu& contex
                     continue;
                 }
 
-                QAction* a = contextMenu.main.addAction(QString("  %1").arg(QtUtil::ToQString(pTrack2->GetName())));
+                QAction* a = contextMenu.main.addAction(QString("  %1").arg(pTrack2->GetName()));
                 a->setData(eMI_ShowHideBase + childIndex);
                 a->setCheckable(true);
                 a->setChecked(!pTrack2->IsHidden());
@@ -1459,7 +1459,7 @@ void CUiAnimViewNodesCtrl::FillAutoCompletionListForFilter()
 
         for (unsigned int i = 0; i < animNodeCount; ++i)
         {
-            strings << QtUtil::ToQString(animNodes.GetNode(i)->GetName());
+            strings << QString(animNodes.GetNode(i)->GetName());
         }
     }
     else
@@ -1512,7 +1512,7 @@ int CUiAnimViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, con
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)
@@ -1763,7 +1763,7 @@ void CUiAnimViewNodesCtrl::OnNodeRenamed(CUiAnimViewNode* pNode, [[maybe_unused]
     if (!m_bIgnoreNotifications)
     {
         CRecord* pNodeRecord = GetNodeRecord(pNode);
-        pNodeRecord->setText(0, QtUtil::ToQString(pNode->GetName()));
+        pNodeRecord->setText(0, pNode->GetName());
 
         update();
     }
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
index 7f7f8f7aaf..cdafd8a4ce 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
@@ -683,7 +683,7 @@ bool CUiAnimViewSequence::SetName(const char* pName)
         return false;
     }
 
-    string oldName = GetName();
+    AZStd::string oldName = GetName();
     m_pAnimSequence->SetName(pName);
 
     if (UiAnimUndo::IsRecording())
@@ -691,7 +691,7 @@ bool CUiAnimViewSequence::SetName(const char* pName)
         UiAnimUndo::Record(new CUndoAnimNodeRename(this, oldName));
     }
 
-    GetSequence()->OnNodeRenamed(this, oldName);
+    GetSequence()->OnNodeRenamed(this, oldName.c_str());
 
     return true;
 }
@@ -893,7 +893,7 @@ std::deque CUiAnimViewSequence::GetMatchingTracks(CUiAnimView
 {
     std::deque matchingTracks;
 
-    const string trackName = trackNode->getAttr("name");
+    const AZStd::string trackName = trackNode->getAttr("name");
 
     IUiAnimationSystem* animationSystem = nullptr;
     EBUS_EVENT_RESULT(animationSystem, UiEditorAnimationBus, GetAnimationSystem);
@@ -956,11 +956,11 @@ void CUiAnimViewSequence::GetMatchedPasteLocationsRec(std::vectorgetChild(nodeIndex);
-        const string tagName = xmlChildNode->getTag();
+        const AZStd::string tagName = xmlChildNode->getTag();
 
         if (tagName == "Node")
         {
-            const string nodeName = xmlChildNode->getAttr("name");
+            const AZStd::string nodeName = xmlChildNode->getAttr("name");
 
             int nodeType = eUiAnimNodeType_Invalid;
             xmlChildNode->getAttr("type", nodeType);
@@ -982,7 +982,7 @@ void CUiAnimViewSequence::GetMatchedPasteLocationsRec(std::vectorgetAttr("name");
+            const AZStd::string trackName = xmlChildNode->getAttr("name");
 
             IUiAnimationSystem* animationSystem = nullptr;
             EBUS_EVENT_RESULT(animationSystem, UiEditorAnimationBus, GetAnimationSystem);
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp
index 8ab6f2e58c..cd4bf5b1ac 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp
@@ -546,7 +546,7 @@ void CUndoAnimNodeReparent::AddParentsInChildren(CUiAnimViewAnimNode* pCurrentNo
 }
 
 //////////////////////////////////////////////////////////////////////////
-CUndoAnimNodeRename::CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const string& oldName)
+CUndoAnimNodeRename::CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const AZStd::string& oldName)
     : m_pNode(pNode)
     , m_newName(pNode->GetName())
     , m_oldName(oldName)
@@ -556,13 +556,13 @@ CUndoAnimNodeRename::CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const strin
 //////////////////////////////////////////////////////////////////////////
 void CUndoAnimNodeRename::Undo([[maybe_unused]] bool bUndo)
 {
-    m_pNode->SetName(m_oldName);
+    m_pNode->SetName(m_oldName.c_str());
 }
 
 //////////////////////////////////////////////////////////////////////////
 void CUndoAnimNodeRename::Redo()
 {
-    m_pNode->SetName(m_newName);
+    m_pNode->SetName(m_newName.c_str());
 }
 
 //////////////////////////////////////////////////////////////////////////
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h
index d79336cedd..923420c653 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h
@@ -304,7 +304,7 @@ class CUndoAnimNodeRename
     : public UiAnimUndoObject
 {
 public:
-    CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const string& oldName);
+    CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const AZStd::string& oldName);
 
 protected:
     virtual int GetSize() override { return sizeof(*this); };
@@ -315,8 +315,8 @@ protected:
 
 private:
     CUiAnimViewAnimNode* m_pNode;
-    string m_newName;
-    string m_oldName;
+    AZStd::string m_newName;
+    AZStd::string m_oldName;
 };
 
 /** Base class for track event transactions
diff --git a/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp b/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp
index caff5d2da0..206da8cb3a 100644
--- a/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp
+++ b/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp
@@ -75,7 +75,7 @@ void AssetTreeEntry::Insert(const AZStd::string& path, const AZStd::string& menu
         AZStd::string folderName;
         AZStd::string remainderPath;
         size_t separator = path.find('/');
-        if (separator == string::npos)
+        if (separator == AZStd::string::npos)
         {
             folderName = path;
         }
diff --git a/Gems/LyShine/Code/Editor/EditorMenu.cpp b/Gems/LyShine/Code/Editor/EditorMenu.cpp
index 97db065a4d..840bd206ab 100644
--- a/Gems/LyShine/Code/Editor/EditorMenu.cpp
+++ b/Gems/LyShine/Code/Editor/EditorMenu.cpp
@@ -724,7 +724,7 @@ void EditorWindow::AddMenu_View_LanguageSetting(QMenu* viewMenu)
     // Iterate through the subdirectories of the localization folder. Each
     // directory corresponds to a different language containing localization
     // translations for that language.
-    string fullLocPath(string(gEnv->pFileIO->GetAlias("@assets@")) + "/" + string(m_startupLocFolderName.toUtf8().constData()));
+    AZStd::string fullLocPath(AZStd::string(gEnv->pFileIO->GetAlias("@assets@")) + "/" + AZStd::string(m_startupLocFolderName.toUtf8().constData()));
     QDir locDir(fullLocPath.c_str());
     locDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
     locDir.setSorting(QDir::Name);
diff --git a/Gems/LyShine/Code/Editor/PropertiesContainer.cpp b/Gems/LyShine/Code/Editor/PropertiesContainer.cpp
index 36a78fe684..21b3b99b02 100644
--- a/Gems/LyShine/Code/Editor/PropertiesContainer.cpp
+++ b/Gems/LyShine/Code/Editor/PropertiesContainer.cpp
@@ -788,7 +788,7 @@ void PropertiesContainer::Update()
     }
     else // more than one entity selected
     {
-        displayName = ToString(selectedEntitiesAmount) + " elements selected";
+        displayName = (ToString(selectedEntitiesAmount) + " elements selected").c_str();
     }
 
     // Update the selected element display name
diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
index ac55cd38e9..b3cacec065 100644
--- a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
+++ b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
@@ -9,6 +9,8 @@
 
 #include "PropertyHandlerChar.h"
 
+#include 
+
 QWidget* PropertyHandlerChar::CreateGUI(QWidget* pParent)
 {
     AzToolsFramework::PropertyStringLineEditCtrl* ctrl = aznew AzToolsFramework::PropertyStringLineEditCtrl(pParent);
@@ -29,12 +31,8 @@ void PropertyHandlerChar::WriteGUIValuesIntoProperty(size_t index, AzToolsFramew
 {
     (int)index;
     AZStd::string str = GUI->value();
-    uint32_t character = '\0';
-    if (!str.empty())
-    {
-        Unicode::CIterator pChar(str.c_str());
-        character = *pChar;
-    }
+    wchar_t character = '\0';
+    AZStd::to_wstring(&character, 1, str.c_str());
     instance = character;
 }
 
@@ -47,7 +45,8 @@ bool PropertyHandlerChar::ReadValuesIntoGUI(size_t index, AzToolsFramework::Prop
         // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
         // work for cases tested but may not in general.
         wchar_t wcharString[2] = { static_cast(instance), 0 };
-        AZStd::string val(CryStringUtils::WStrToUTF8(wcharString));
+        AZStd::string val;
+        AZStd::to_string(val, wcharString);
         GUI->setValue(val);
     }
     GUI->blockSignals(false);
diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp
index ab51c3a29d..1f3e28b077 100644
--- a/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp
+++ b/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp
@@ -93,7 +93,7 @@ AzToolsFramework::AssetBrowser::AssetSelectionModel PropertyAssetDirectorySelect
 
 void PropertyAssetDirectorySelectionCtrl::SetFolderSelection(const AZStd::string& folderPath)
 {
-    string strFolderPath = folderPath.c_str();
+    AZStd::string strFolderPath = folderPath.c_str();
     if (strFolderPath.empty())
     {
         m_folderPath.clear();
@@ -106,12 +106,14 @@ void PropertyAssetDirectorySelectionCtrl::SetFolderSelection(const AZStd::string
         // the project folder, which we need to omit since file IO routines
         // seem to assume this anyways.
         strFolderPath = strFolderPath.substr(strFolderPath.find('/') + 1);
-        m_folderPath = PathUtil::MakeGamePath(strFolderPath).MakeLower();
+        m_folderPath = PathUtil::MakeGamePath(strFolderPath);
+        AZStd::to_lower(m_folderPath.begin(), m_folderPath.end());
     }
     // For paths in gems, absolute paths are returned
     else
     {
-        m_folderPath = Path::FullPathToGamePath(strFolderPath.c_str()).MakeLower();
+        m_folderPath = Path::FullPathToGamePath(strFolderPath.c_str());
+        AZStd::to_lower(m_folderPath.begin(), m_folderPath.end());
     }
 }
 
diff --git a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
index 2bb1686a93..d833c93af8 100644
--- a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
+++ b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
@@ -921,7 +921,7 @@ void SpriteBorderEditor::AddButtonsSection(QGridLayout* gridLayout, int& rowNum)
                 // The texture is guaranteed to exist so use that to get the full path.
                 QString fullTexturePath = Path::GamePathToFullPath(m_sprite->GetTexturePathname().c_str());
                 const char* const spriteExtension = "sprite";
-                string fullSpritePath = PathUtil::ReplaceExtension(fullTexturePath.toUtf8().data(), spriteExtension);
+                AZStd::string fullSpritePath = PathUtil::ReplaceExtension(fullTexturePath.toUtf8().data(), spriteExtension);
 
                 FileHelpers::SourceControlAddOrEdit(fullSpritePath.c_str(), QApplication::activeWindow());
 
diff --git a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
index f1ecb4af9e..43a80d5002 100644
--- a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
+++ b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
@@ -80,10 +80,10 @@ void CUiAnimSequence::SetName(const char* name)
         return;   // should never happen, null pointer guard
     }
 
-    string originalName = GetName();
+    AZStd::string originalName = GetName();
 
     m_name = name;
-    m_pUiAnimationSystem->OnSequenceRenamed(originalName, m_name.c_str());
+    m_pUiAnimationSystem->OnSequenceRenamed(originalName.c_str(), m_name.c_str());
 
     if (GetOwner())
     {
diff --git a/Gems/LyShine/Code/Source/Animation/AnimSequence.h b/Gems/LyShine/Code/Source/Animation/AnimSequence.h
index efbe886ce2..e4026ce250 100644
--- a/Gems/LyShine/Code/Source/Animation/AnimSequence.h
+++ b/Gems/LyShine/Code/Source/Animation/AnimSequence.h
@@ -146,7 +146,7 @@ private:
 
     uint32 m_id;
     AZStd::string m_name;
-    mutable string m_fullNameHolder;
+    mutable AZStd::string m_fullNameHolder;
     Range m_timeRange;
     UiTrackEvents m_events;
 
diff --git a/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp b/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp
index ca435dadf9..32dfb97a58 100644
--- a/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp
+++ b/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp
@@ -278,8 +278,8 @@ const AZ::SerializeContext::ClassElement* CUiAnimAzEntityNode::ComputeOffsetFrom
 
         if (mismatch)
         {
-            string warnMsg = "Data mismatch reading animation data for type ";
-            warnMsg += classData->m_typeId.ToString();
+            AZStd::string warnMsg = "Data mismatch reading animation data for type ";
+            warnMsg += classData->m_typeId.ToString();
             warnMsg += ". The field \"";
             warnMsg += paramData.GetName();
             if (!element)
diff --git a/Gems/LyShine/Code/Source/Animation/AzEntityNode.h b/Gems/LyShine/Code/Source/Animation/AzEntityNode.h
index 6ca26ef84a..56680f1094 100644
--- a/Gems/LyShine/Code/Source/Animation/AzEntityNode.h
+++ b/Gems/LyShine/Code/Source/Animation/AzEntityNode.h
@@ -170,14 +170,14 @@ private:
 
     struct SScriptPropertyParamInfo
     {
-        string variableName;
-        string displayName;
+        AZStd::string variableName;
+        AZStd::string displayName;
         bool isVectorTable;
         SParamInfo animNodeParamInfo;
     };
 
     std::vector< SScriptPropertyParamInfo > m_entityScriptPropertiesParamInfos;
-    typedef AZStd::unordered_map< string, size_t, stl::hash_string_caseless, stl::equality_string_caseless > TScriptPropertyParamInfoMap;
+    typedef AZStd::unordered_map, stl::equality_string_caseless > TScriptPropertyParamInfoMap;
     TScriptPropertyParamInfoMap m_nameToScriptPropertyParamInfo;
     #ifdef CHECK_FOR_TOO_MANY_ONPROPERTY_SCRIPT_CALLS
     uint32 m_OnPropertyCalls;
diff --git a/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h b/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h
index b707d0bc77..3ae230d4e4 100644
--- a/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h
+++ b/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h
@@ -112,7 +112,7 @@ public:
 
     virtual int NextKeyByTime(int key) const;
 
-    void SetSubTrackName(const int i, const string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
+    void SetSubTrackName(const int i, const AZStd::string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
 
 #ifdef UI_ANIMATION_SYSTEM_SUPPORT_EDITING
     virtual ColorB GetCustomColor() const
diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
index 5c897620c7..1ea35006e2 100644
--- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
+++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
@@ -27,19 +27,19 @@
 // Serialization for anim nodes & param types
 #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(eUiAnimNodeType_ ## name) == g_animNodeEnumToStringMap.end()); \
     g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = STRINGIFY(name);                                                            \
-    g_animNodeStringToEnumMap[string(STRINGIFY(name))] = eUiAnimNodeType_ ## name;
+    g_animNodeStringToEnumMap[AZStd::string(STRINGIFY(name))] = eUiAnimNodeType_ ## name;
 
 #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(eUiAnimParamType_ ## name) == g_animParamEnumToStringMap.end()); \
     g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = STRINGIFY(name);                                                              \
-    g_animParamStringToEnumMap[string(STRINGIFY(name))] = eUiAnimParamType_ ## name;
+    g_animParamStringToEnumMap[AZStd::string(STRINGIFY(name))] = eUiAnimParamType_ ## name;
 
 namespace
 {
-    AZStd::unordered_map g_animNodeEnumToStringMap;
-    StaticInstance >> g_animNodeStringToEnumMap;
+    AZStd::unordered_map g_animNodeEnumToStringMap;
+    StaticInstance >> g_animNodeStringToEnumMap;
 
-    AZStd::unordered_map g_animParamEnumToStringMap;
-    StaticInstance >> g_animParamStringToEnumMap;
+    AZStd::unordered_map g_animParamEnumToStringMap;
+    StaticInstance >> g_animParamStringToEnumMap;
 
     // If you get an assert in this function, it means two node types have the same enum value.
     void RegisterNodeTypes()
@@ -1189,7 +1189,7 @@ void UiAnimationSystem::SerializeNodeType(EUiAnimNodeType& animNodeType, XmlNode
     {
         const char* pTypeString = "Invalid";
         assert(g_animNodeEnumToStringMap.find(animNodeType) != g_animNodeEnumToStringMap.end());
-        pTypeString = g_animNodeEnumToStringMap[animNodeType];
+        pTypeString = g_animNodeEnumToStringMap[animNodeType].c_str();
         xmlNode->setAttr(kType, pTypeString);
     }
 }
@@ -1273,7 +1273,7 @@ void UiAnimationSystem::SerializeParamType(CUiAnimParamType& animParamType, XmlN
         else
         {
             assert(g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end());
-            pTypeString = g_animParamEnumToStringMap[animParamType.m_type];
+            pTypeString = g_animParamEnumToStringMap[animParamType.m_type].c_str();
         }
 
         xmlNode->setAttr(kParamType, pTypeString);
@@ -1341,7 +1341,7 @@ const char* UiAnimationSystem::GetParamTypeName(const CUiAnimParamType& animPara
     {
         if (g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end())
         {
-            return g_animParamEnumToStringMap[animParamType.m_type];
+            return g_animParamEnumToStringMap[animParamType.m_type].c_str();
         }
     }
 
diff --git a/Gems/LyShine/Code/Source/LyShine.cpp b/Gems/LyShine/Code/Source/LyShine.cpp
index f5edc4d7f1..4e265bd973 100644
--- a/Gems/LyShine/Code/Source/LyShine.cpp
+++ b/Gems/LyShine/Code/Source/LyShine.cpp
@@ -287,7 +287,7 @@ AZ::EntityId CLyShine::CreateCanvas()
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId CLyShine::LoadCanvas(const string& assetIdPathname)
+AZ::EntityId CLyShine::LoadCanvas(const AZStd::string& assetIdPathname)
 {
     return m_uiCanvasManager->LoadCanvas(assetIdPathname.c_str());
 }
@@ -299,7 +299,7 @@ AZ::EntityId CLyShine::CreateCanvasInEditor(UiEntityContext* entityContext)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId CLyShine::LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext)
+AZ::EntityId CLyShine::LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext)
 {
     return m_uiCanvasManager->LoadCanvasInEditor(assetIdPathname, sourceAssetPathname, entityContext);
 }
@@ -317,7 +317,7 @@ AZ::EntityId CLyShine::FindCanvasById(LyShine::CanvasId id)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId CLyShine::FindLoadedCanvasByPathName(const string& assetIdPathname)
+AZ::EntityId CLyShine::FindLoadedCanvasByPathName(const AZStd::string& assetIdPathname)
 {
     return m_uiCanvasManager->FindLoadedCanvasByPathName(assetIdPathname.c_str());
 }
@@ -335,13 +335,13 @@ void CLyShine::ReleaseCanvasDeferred(AZ::EntityId canvas)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-ISprite* CLyShine::LoadSprite(const string& pathname)
+ISprite* CLyShine::LoadSprite(const AZStd::string& pathname)
 {
     return CSprite::LoadSprite(pathname);
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-ISprite* CLyShine::CreateSprite(const string& renderTargetName)
+ISprite* CLyShine::CreateSprite(const AZStd::string& renderTargetName)
 {
     return CSprite::CreateSprite(renderTargetName);
 }
diff --git a/Gems/LyShine/Code/Source/LyShine.h b/Gems/LyShine/Code/Source/LyShine.h
index a7a8cab700..cb5b77a861 100644
--- a/Gems/LyShine/Code/Source/LyShine.h
+++ b/Gems/LyShine/Code/Source/LyShine.h
@@ -56,18 +56,18 @@ public:
     IDraw2d* GetDraw2d() override;
 
     AZ::EntityId CreateCanvas() override;
-    AZ::EntityId LoadCanvas(const string& assetIdPathname) override;
+    AZ::EntityId LoadCanvas(const AZStd::string& assetIdPathname) override;
     AZ::EntityId CreateCanvasInEditor(UiEntityContext* entityContext) override;
-    AZ::EntityId LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext) override;
+    AZ::EntityId LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext) override;
     AZ::EntityId ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext) override;
     AZ::EntityId FindCanvasById(LyShine::CanvasId id) override;
-    AZ::EntityId FindLoadedCanvasByPathName(const string& assetIdPathname) override;
+    AZ::EntityId FindLoadedCanvasByPathName(const AZStd::string& assetIdPathname) override;
 
     void ReleaseCanvas(AZ::EntityId canvas, bool forEditor) override;
     void ReleaseCanvasDeferred(AZ::EntityId canvas) override;
 
-    ISprite* LoadSprite(const string& pathname) override;
-    ISprite* CreateSprite(const string& renderTargetName) override;
+    ISprite* LoadSprite(const AZStd::string& pathname) override;
+    ISprite* CreateSprite(const AZStd::string& renderTargetName) override;
     bool DoesSpriteTextureAssetExist(const AZStd::string& pathname) override;
 
     void PostInit() override;
diff --git a/Gems/LyShine/Code/Source/LyShineDebug.cpp b/Gems/LyShine/Code/Source/LyShineDebug.cpp
index c7ffea1aec..c7dccc162f 100644
--- a/Gems/LyShine/Code/Source/LyShineDebug.cpp
+++ b/Gems/LyShine/Code/Source/LyShineDebug.cpp
@@ -995,7 +995,7 @@ static AZ::Entity* CreateButton(const char* name, bool atRoot, AZ::EntityId pare
         EBUS_EVENT_ID(buttonId, UiInteractableStatesBus, SetStateColor, UiInteractableStatesInterface::StatePressed, buttonId, pressedColor);
         EBUS_EVENT_ID(buttonId, UiInteractableStatesBus, SetStateAlpha, UiInteractableStatesInterface::StatePressed, buttonId, pressedColor.GetA());
 
-        string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
+        AZStd::string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
         ISprite* sprite = gEnv->pLyShine->LoadSprite(pathname);
 
         EBUS_EVENT_ID(buttonId, UiImageBus, SetSprite, sprite);
@@ -1094,7 +1094,7 @@ static AZ::Entity* CreateTextInput(const char* name, bool atRoot, AZ::EntityId p
         EBUS_EVENT_ID(textInputId, UiInteractableStatesBus, SetStateColor, UiInteractableStatesInterface::StatePressed, textInputId, pressedColor);
         EBUS_EVENT_ID(textInputId, UiInteractableStatesBus, SetStateAlpha, UiInteractableStatesInterface::StatePressed, textInputId, pressedColor.GetA());
 
-        string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
+        AZStd::string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
         ISprite* sprite = gEnv->pLyShine->LoadSprite(pathname);
 
         EBUS_EVENT_ID(textInputId, UiImageBus, SetSprite, sprite);
diff --git a/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp b/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp
index 9d4f0bcc3c..64a577efa2 100644
--- a/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp
+++ b/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp
@@ -215,7 +215,7 @@ namespace LyShine
     AZ::EntityId LyShineLoadScreenComponent::loadFromCfg(const char* pathVarName, const char* autoPlayVarName)
     {
         ICVar* pathVar = gEnv->pConsole->GetCVar(pathVarName);
-        string path = pathVar ? pathVar->GetString() : "";
+        AZStd::string path = pathVar ? pathVar->GetString() : "";
         if (path.empty())
         {
             // No canvas specified.
@@ -238,7 +238,7 @@ namespace LyShine
         EBUS_EVENT_ID(canvasId, UiCanvasBus, SetDrawOrder, std::numeric_limits::max());
 
         ICVar* autoPlayVar = gEnv->pConsole->GetCVar(autoPlayVarName);
-        string sequence = autoPlayVar ? autoPlayVar->GetString() : "";
+        AZStd::string sequence = autoPlayVar ? autoPlayVar->GetString() : "";
         if (sequence.empty())
         {
             // Nothing to auto-play.
@@ -253,7 +253,7 @@ namespace LyShine
             return canvasId;
         }
 
-        animSystem->PlaySequence(sequence, nullptr, false, false);
+        animSystem->PlaySequence(sequence.c_str(), nullptr, false, false);
 
         return canvasId;
     }
diff --git a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
index 7bcdc26712..ae118aee00 100644
--- a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
+++ b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
@@ -9,6 +9,7 @@
 
 #include "UiClipboard.h"
 #include 
+#include 
 
 bool UiClipboard::SetText(const AZStd::string& text)
 {
@@ -19,7 +20,8 @@ bool UiClipboard::SetText(const AZStd::string& text)
         {
             if (text.length() > 0)
             {
-                auto wstr = CryStringUtils::UTF8ToWStr(text.c_str());
+                AZStd::wstring wstr;
+                AZStd::to_wstring(wstr, text.c_str());
                 const SIZE_T buffSize = (wstr.size() + 1) * sizeof(WCHAR);
                 if (HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, buffSize))
                 {
@@ -45,7 +47,7 @@ AZStd::string UiClipboard::GetText()
         if (HANDLE hText = GetClipboardData(CF_UNICODETEXT))
         {
             const WCHAR* text = static_cast(GlobalLock(hText));
-            outText = CryStringUtils::WStrToUTF8(text);
+            AZStd::to_string(outText, text);
             GlobalUnlock(hText);
         }
         CloseClipboard();
diff --git a/Gems/LyShine/Code/Source/Sprite.cpp b/Gems/LyShine/Code/Source/Sprite.cpp
index 134768f814..0e0edb8e34 100644
--- a/Gems/LyShine/Code/Source/Sprite.cpp
+++ b/Gems/LyShine/Code/Source/Sprite.cpp
@@ -146,9 +146,9 @@ namespace
     {
         if (ser.IsReading())
         {
-            string stringVal;
+            AZStd::string stringVal;
             ser.Value(attributeName, stringVal);
-            stringVal.replace(',', ' ');
+            AZ::StringFunc::Replace(stringVal, ',', ' ');
             char* pEnd = nullptr;
             float uVal = strtof(stringVal.c_str(), &pEnd);
             float vVal = strtof(pEnd, nullptr);
@@ -202,13 +202,13 @@ CSprite::~CSprite()
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-const string& CSprite::GetPathname() const
+const AZStd::string& CSprite::GetPathname() const
 {
     return m_pathname;
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-const string& CSprite::GetTexturePathname() const
+const AZStd::string& CSprite::GetTexturePathname() const
 {
     return m_texturePathname;
 }
@@ -283,7 +283,7 @@ void CSprite::Serialize(TSerialize ser)
                 m_spriteSheetCells.push_back(SpriteSheetCell());
             }
 
-            string aliasTemp;
+            AZStd::string aliasTemp;
             if (ser.IsReading())
             {
                 ser.Value("alias", aliasTemp);
@@ -318,7 +318,7 @@ void CSprite::Serialize(TSerialize ser)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-bool CSprite::SaveToXml(const string& pathname)
+bool CSprite::SaveToXml(const AZStd::string& pathname)
 {
     // NOTE: The input pathname has to be a path that can used to save - so not an Asset ID
     // because of this we do not store the pathname
@@ -331,7 +331,7 @@ bool CSprite::SaveToXml(const string& pathname)
     ser.Value(spriteVersionNumberTag, spriteFileVersionNumber);
     Serialize(ser);
 
-    return root->saveToFile(pathname);
+    return root->saveToFile(pathname.c_str());
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -629,7 +629,7 @@ void CSprite::Shutdown()
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-CSprite* CSprite::LoadSprite(const string& pathname)
+CSprite* CSprite::LoadSprite(const AZStd::string& pathname)
 {
     AZStd::string spritePath;
     AZStd::string texturePath;
@@ -691,7 +691,7 @@ CSprite* CSprite::LoadSprite(const string& pathname)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-CSprite* CSprite::CreateSprite(const string& renderTargetName)
+CSprite* CSprite::CreateSprite(const AZStd::string& renderTargetName)
 {
     // test if the sprite is already loaded, if so return loaded sprite
     auto result = s_loadedSprites->find(renderTargetName);
diff --git a/Gems/LyShine/Code/Source/Sprite.h b/Gems/LyShine/Code/Source/Sprite.h
index e7e353a77b..8a645b78b1 100644
--- a/Gems/LyShine/Code/Source/Sprite.h
+++ b/Gems/LyShine/Code/Source/Sprite.h
@@ -32,13 +32,13 @@ public: // member functions
 
     ~CSprite() override;
 
-    const string& GetPathname() const override;
-    const string& GetTexturePathname() const override;
+    const AZStd::string& GetPathname() const override;
+    const AZStd::string& GetTexturePathname() const override;
     Borders GetBorders() const override;
     void SetBorders(Borders borders) override;
     void SetCellBorders(int cellIndex, Borders borders) override;
     void Serialize(TSerialize ser) override;
-    bool SaveToXml(const string& pathname) override;
+    bool SaveToXml(const AZStd::string& pathname) override;
     bool AreBordersZeroWidth() const override;
     bool AreCellBordersZeroWidth(int index) const override;
     AZ::Vector2 GetSize() override;
@@ -72,8 +72,8 @@ public: // static member functions
 
     static void Initialize();
     static void Shutdown();
-    static CSprite* LoadSprite(const string& pathname);
-    static CSprite* CreateSprite(const string& renderTargetName);
+    static CSprite* LoadSprite(const AZStd::string& pathname);
+    static CSprite* CreateSprite(const AZStd::string& renderTargetName);
     static bool DoesSpriteTextureAssetExist(const AZStd::string& pathname);
 
     //! Replaces baseSprite with newSprite with proper ref-count handling and null-checks.
@@ -96,7 +96,7 @@ protected: // member functions
     bool CellIndexWithinRange(int cellIndex) const;
 
 private: // types
-    typedef AZStd::unordered_map, stl::equality_string_caseless > CSpriteHashMap;
+    typedef AZStd::unordered_map, stl::equality_string_caseless > CSpriteHashMap;
 
 private: // member functions
     bool LoadFromXmlFile();
@@ -109,8 +109,8 @@ private: // data
 
     SpriteSheetCellContainer m_spriteSheetCells;  //!< Stores information for each cell defined within the sprite-sheet.
 
-    string m_pathname;
-    string m_texturePathname;
+    AZStd::string m_pathname;
+    AZStd::string m_texturePathname;
     Borders m_borders;
     AZ::Data::Instance m_image;
     int m_numSpriteSheetCellTags;                       //!< Number of Cell child-tags in sprite XML; unfortunately needed to help with serialization.
diff --git a/Gems/LyShine/Code/Source/StringUtfUtils.h b/Gems/LyShine/Code/Source/StringUtfUtils.h
index 74a27afe9f..40dd22dd33 100644
--- a/Gems/LyShine/Code/Source/StringUtfUtils.h
+++ b/Gems/LyShine/Code/Source/StringUtfUtils.h
@@ -7,6 +7,8 @@
  */
 #pragma once
 
+#include 
+
 namespace LyShine
 {
     //! \brief Returns the number of UTF8 characters in a string.
@@ -16,15 +18,9 @@ namespace LyShine
     //! character in the string.
     inline int GetUtf8StringLength(const AZStd::string& utf8String)
     {
-        int utf8StrLen = 0;
-        Unicode::CIterator pChar(utf8String.c_str());
-        while (uint32_t ch = *pChar)
-        {
-            ++pChar;
-            ++utf8StrLen;
-        }
-
-        return utf8StrLen;
+        AZStd::wstring utf8StringW;
+        AZStd::to_wstring(utf8StringW, utf8String.c_str());
+        return static_cast(utf8StringW.size());
     }
 
     //! \brief Returns the number of bytes of the size of the given multi-byte char.
@@ -34,17 +30,16 @@ namespace LyShine
         // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
         // work for cases tested but may not in general.
         // In the long run it would be better to eliminate
-        // this function and use Unicode::CIterator<>::Position instead.
-        wchar_t wcharString[2] = { static_cast(multiByteChar), 0 };
-        AZStd::string utf8String(CryStringUtils::WStrToUTF8(wcharString));
-        int utf8Length = utf8String.length();
-        return utf8Length;
+        // this function and use some sequence_lenght function that is not internal.
+        return Utf8::Internal::sequence_length(&multiByteChar);
     }
 
     inline int GetByteLengthOfUtf8Chars(const char* utf8String, int numUtf8Chars)
     {
+        AZStd::wstring utf8StringW;
+        AZStd::to_wstring(utf8StringW, utf8String);
+        AZStd::wstring::const_iterator pChar = utf8StringW.begin();
         int byteStrlen = 0;
-        Unicode::CIterator pChar(utf8String);
         for (int i = 0; i < numUtf8Chars; i++)
         {
             uint32_t ch = *pChar;
diff --git a/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp b/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp
index 3cd137b25f..8cf2cd2edb 100644
--- a/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp
+++ b/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp
@@ -3508,7 +3508,7 @@ void UiTextComponent::UnitTestLocalization(CLyShine* lyshine, IConsoleCmdArgs* /
 {
     ILocalizationManager* pLocMan = GetISystem()->GetLocalizationManager();
 
-    string localizationXml("libs/localization/localization.xml");
+    AZStd::string localizationXml("libs/localization/localization.xml");
 
     bool initLocSuccess = false;
 
diff --git a/Gems/LyShine/Code/Source/TextMarkup.cpp b/Gems/LyShine/Code/Source/TextMarkup.cpp
index 864d7a2cfc..8c1a6e0b62 100644
--- a/Gems/LyShine/Code/Source/TextMarkup.cpp
+++ b/Gems/LyShine/Code/Source/TextMarkup.cpp
@@ -162,7 +162,8 @@ namespace
                     }
                     else if (AZStd::string(key) == "color")
                     {
-                        AZStd::string colorValue(string(value).Trim());
+                        AZStd::string colorValue(value);
+                        AZ::StringFunc::TrimWhiteSpace(colorValue, true, true);
                         AZStd::string::size_type ExpectedNumChars = 7;
                         if (ExpectedNumChars == colorValue.size() && '#' == colorValue.at(0))
                         {
diff --git a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp
index 72d9f92d1f..b665f039b0 100644
--- a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp
@@ -177,11 +177,11 @@ namespace
 
     ////////////////////////////////////////////////////////////////////////////////////////////////
     // test if the given text file starts with the given text string
-    bool TestFileStartString(const string& pathname, const char* expectedStart)
+    bool TestFileStartString(const AZStd::string& pathname, const char* expectedStart)
     {
         // Open the file using CCryFile, this supports it being in the pak file or a standalone file
         CCryFile file;
-        if (!file.Open(pathname, "r"))
+        if (!file.Open(pathname.c_str(), "r"))
         {
             return false;
         }
@@ -208,7 +208,7 @@ namespace
 
     ////////////////////////////////////////////////////////////////////////////////////////////////
     // Check if the given file was saved using AZ serialization
-    bool IsValidAzSerializedFile(const string& pathname)
+    bool IsValidAzSerializedFile(const AZStd::string& pathname)
     {
         return TestFileStartString(pathname, " dstData;
@@ -3884,7 +3884,7 @@ UiCanvasComponent* UiCanvasComponent::CreateCanvasInternal(UiEntityContext* enti
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-UiCanvasComponent*  UiCanvasComponent::LoadCanvasInternal(const string& pathnameToOpen, bool forEditor, const string& assetIdPathname, UiEntityContext* entityContext,
+UiCanvasComponent*  UiCanvasComponent::LoadCanvasInternal(const AZStd::string& pathnameToOpen, bool forEditor, const AZStd::string& assetIdPathname, UiEntityContext* entityContext,
     const AZ::SliceComponent::EntityIdToEntityIdMap* previousRemapTable, AZ::EntityId previousCanvasId)
 {
     UiCanvasComponent* canvasComponent = nullptr;
diff --git a/Gems/LyShine/Code/Source/UiCanvasComponent.h b/Gems/LyShine/Code/Source/UiCanvasComponent.h
index 852bb482d0..097f23cbda 100644
--- a/Gems/LyShine/Code/Source/UiCanvasComponent.h
+++ b/Gems/LyShine/Code/Source/UiCanvasComponent.h
@@ -99,7 +99,7 @@ public: // member functions
     LyShine::EntityArray PickElements(const AZ::Vector2& bound0, const AZ::Vector2& bound1) override;
     AZ::EntityId FindInteractableToHandleEvent(AZ::Vector2 point) override;
 
-    bool SaveToXml(const string& assetIdPathname, const string& sourceAssetPathname) override;
+    bool SaveToXml(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname) override;
     void FixupCreatedEntities(LyShine::EntityArray topLevelEntities, bool makeUniqueNamesAndIds, AZ::Entity* optionalInsertionPoint) override;
     void AddElement(AZ::Entity* element, AZ::Entity* parent, AZ::Entity* insertBefore) override;
     void ReinitializeElements() override;
@@ -307,7 +307,7 @@ public: // static member functions
     static void Shutdown();
 
     static UiCanvasComponent* CreateCanvasInternal(UiEntityContext* entityContext, bool forEditor);
-    static UiCanvasComponent* LoadCanvasInternal(const string& pathToOpen, bool forEditor, const string& assetIdPathname, UiEntityContext* entityContext,
+    static UiCanvasComponent* LoadCanvasInternal(const AZStd::string& pathToOpen, bool forEditor, const AZStd::string& assetIdPathname, UiEntityContext* entityContext,
         const AZ::SliceComponent::EntityIdToEntityIdMap* previousRemapTable = nullptr, AZ::EntityId previousCanvasId = AZ::EntityId());
     static UiCanvasComponent* FixupReloadedCanvasForEditorInternal(AZ::Entity* newCanvasEntity,
         AZ::Entity* rootSliceEntity, UiEntityContext* entityContext,
@@ -403,7 +403,7 @@ private: // member functions
     void DestroyRenderTarget();
     void RenderCanvasToTexture();
 
-    bool SaveCanvasToFile(const string& pathname, AZ::DataStream::StreamType streamType);
+    bool SaveCanvasToFile(const AZStd::string& pathname, AZ::DataStream::StreamType streamType);
     bool SaveCanvasToStream(AZ::IO::GenericStream& stream, AZ::DataStream::StreamType streamType);
 
     //! Notify elements that their canvas space rect has changed since the last update, and recompute invalid layouts
diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.cpp b/Gems/LyShine/Code/Source/UiCanvasManager.cpp
index cb27f09672..bed3bcf433 100644
--- a/Gems/LyShine/Code/Source/UiCanvasManager.cpp
+++ b/Gems/LyShine/Code/Source/UiCanvasManager.cpp
@@ -342,7 +342,7 @@ void UiCanvasManager::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId)
 
             // reload canvas with the same entity IDs (except for new entities, deleted entities etc)
             UiGameEntityContext* entityContext = new UiGameEntityContext();
-            string pathname(assetPath.c_str());
+            AZStd::string pathname(assetPath.c_str());
             UiCanvasComponent* newCanvasComponent = UiCanvasComponent::LoadCanvasInternal(pathname, false, "", entityContext, &existingRemapTable, existingCanvasEntityId);
 
             if (!newCanvasComponent)
@@ -393,7 +393,7 @@ AZ::EntityId UiCanvasManager::CreateCanvasInEditor(UiEntityContext* entityContex
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId UiCanvasManager::LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext)
+AZ::EntityId UiCanvasManager::LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext)
 {
     return LoadCanvasInternal(assetIdPathname.c_str(), true, sourceAssetPathname.c_str(), entityContext);
 }
@@ -1064,10 +1064,10 @@ void UiCanvasManager::DebugDisplayCanvasData(int setting) const
     for (auto canvas : m_loadedCanvases)
     {
         // Name
-        const string pathname = canvas->GetPathname().c_str();
+        const AZStd::string pathname = canvas->GetPathname().c_str();
         size_t lastDot = pathname.find_last_of(".");
         size_t lastSlash = pathname.find_last_of("/");
-        string leafName = pathname;
+        AZStd::string leafName = pathname;
         if (lastDot > lastSlash)
         {
             leafName = pathname.substr(lastSlash+1, lastDot-lastSlash-1);
@@ -1209,10 +1209,10 @@ void UiCanvasManager::DebugDisplayDrawCallData() const
     for (auto canvas : m_loadedCanvases)
     {
         // Name
-        const string pathname = canvas->GetPathname().c_str();
+        const AZStd::string pathname = canvas->GetPathname().c_str();
         size_t lastDot = pathname.find_last_of(".");
         size_t lastSlash = pathname.find_last_of("/");
-        string leafName = pathname;
+        AZStd::string leafName = pathname;
         if (lastDot > lastSlash)
         {
             leafName = pathname.substr(lastSlash+1, lastDot-lastSlash-1);
@@ -1373,7 +1373,7 @@ void UiCanvasManager::DebugReportDrawCalls(const AZStd::string& name) const
         }
 
         // Name of canvas
-        const string pathname = canvas->GetPathname().c_str();
+        const AZStd::string pathname = canvas->GetPathname().c_str();
         logLine = "\r\n=====================================================================================\r\n";
         AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
         logLine = AZStd::string::format("Canvas: %s\r\n", pathname.c_str());
@@ -1461,7 +1461,7 @@ void UiCanvasManager::DebugReportDrawCalls(const AZStd::string& name) const
                 {
                     if (!loggedCanvasHeader)
                     {
-                        const string pathname = canvas->GetPathname().c_str();
+                        const AZStd::string pathname = canvas->GetPathname().c_str();
                         logLine = AZStd::string::format("\r\nCanvas: %s\r\n\r\n", pathname.c_str());
                         AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
                         loggedCanvasHeader = true;
diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.h b/Gems/LyShine/Code/Source/UiCanvasManager.h
index 85783fab84..ebcee200e4 100644
--- a/Gems/LyShine/Code/Source/UiCanvasManager.h
+++ b/Gems/LyShine/Code/Source/UiCanvasManager.h
@@ -68,7 +68,7 @@ public: // member functions
     // ~AssetCatalogEventBus::Handler
 
     AZ::EntityId CreateCanvasInEditor(UiEntityContext* entityContext);
-    AZ::EntityId LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext);
+    AZ::EntityId LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext);
     AZ::EntityId ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext);
 
     void ReleaseCanvas(AZ::EntityId canvas, bool forEditor);
diff --git a/Gems/LyShine/Code/Source/UiDropdownComponent.cpp b/Gems/LyShine/Code/Source/UiDropdownComponent.cpp
index 1940d57cbb..448c208c5e 100644
--- a/Gems/LyShine/Code/Source/UiDropdownComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiDropdownComponent.cpp
@@ -826,7 +826,8 @@ AZ::Outcome UiDropdownComponent::ValidatePotentialExpandedP
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::FailureValue FailureMessage(string message) {
+AZ::FailureValue FailureMessage(AZStd::string message)
+{
     return AZ::Failure(AZStd::string(message));
 }
 
diff --git a/Gems/LyShine/Code/Source/UiInteractableState.cpp b/Gems/LyShine/Code/Source/UiInteractableState.cpp
index d3440a9354..98abae4484 100644
--- a/Gems/LyShine/Code/Source/UiInteractableState.cpp
+++ b/Gems/LyShine/Code/Source/UiInteractableState.cpp
@@ -575,7 +575,7 @@ void UiInteractableStateFont::SetFontPathname(const AZStd::string& pathname)
             fontFamily = gEnv->pCryFont->LoadFontFamily(fileName.c_str());
             if (!fontFamily)
             {
-                string errorMsg = "Error loading a font from ";
+                AZStd::string errorMsg = "Error loading a font from ";
                 errorMsg += fileName.c_str();
                 errorMsg += ".";
                 CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg.c_str());
diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp
index fadf09571f..be26a5a618 100644
--- a/Gems/LyShine/Code/Source/UiTextComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp
@@ -623,12 +623,14 @@ namespace
 
             int batchCurChar = 0;
 
-            Unicode::CIterator pChar(drawBatch.text.c_str());
+            Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
             uint32_t prevCh = 0;
             while (uint32_t ch = *pChar)
             {
-                char codepoint[5];
-                Unicode::Convert(codepoint, ch);
+                size_t maxSize = 5;
+                char codepoint[5] = { 0 };
+                char* codepointPtr = codepoint;
+                Utf8::Unchecked::octet_iterator::to_utf8_sequence(ch, codepointPtr, maxSize);
 
                 float curCharWidth = drawBatch.font->GetTextSize(codepoint, true, ctx).x;
 
@@ -652,15 +654,15 @@ namespace
                     lastSpaceIndexInBatch = batchCurChar;
                     lastSpaceBatch = &drawBatch;
                     lastSpaceWidth = curLineWidth + curCharWidth;
-                    pLastSpace = pChar.GetPosition();
+                    pLastSpace = pChar.base();
                     assert(*pLastSpace == ' ');
                 }
 
                 bool prevCharWasNewline = false;
-                const bool isFirstChar = pChar.GetPosition() == drawBatch.text.c_str();
+                const bool isFirstChar = pChar.base() == drawBatch.text.c_str();
                 if (ch && !isFirstChar)
                 {
-                    const char* pPrevCharStr = pChar.GetPosition() - 1;
+                    const char* pPrevCharStr = pChar.base() - 1;
                     prevCharWasNewline = pPrevCharStr[0] == '\n';
                 }
                 else if (isFirstChar)
@@ -705,12 +707,12 @@ namespace
                     }
                     else
                     {
-                        const char* pBuf = pChar.GetPosition();
+                        char* pBuf = pChar.base();
                         AZStd::string::size_type bytesProcessed = pBuf - drawBatch.text.c_str();
                         drawBatch.text.insert(bytesProcessed, "\n"); // Insert the newline, this invalidates the iterator
-                        pBuf = drawBatch.text.c_str() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
+                        pBuf = drawBatch.text.data() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
                         assert(*pBuf == '\n');
-                        pChar.SetPosition(pBuf); // pChar once again points inside the target string, at the current character
+                        pChar = Utf8::Unchecked::octet_iterator(pBuf); // pChar once again points inside the target string, at the current character
                         assert(*pChar == ch);
                         ++pChar;
                         ++curChar;
@@ -1189,7 +1191,7 @@ void UiTextComponent::DrawBatch::CalculateSize(const STextDrawContext& ctx, bool
             if (displayString.length() > 0)
             {
                 AZStd::string::size_type endpos = displayString.find_last_not_of(" \t\n\v\f\r");
-                if ((endpos != string::npos) && (endpos != displayString.length() - 1))
+                if ((endpos != AZStd::string::npos) && (endpos != displayString.length() - 1))
                 {
                     displayString.erase(endpos + 1);
                 }
@@ -1295,12 +1297,14 @@ bool UiTextComponent::DrawBatch::GetOverflowInfo(const STextDrawContext& ctx,
 
         float maxEffectOffsetX = font->GetMaxEffectOffset(ctx.m_fxIdx).x;
 
-        Unicode::CIterator pChar(text.c_str());
+        Utf8::Unchecked::octet_iterator pChar(text.data());
         uint32_t prevCh = 0;
         while (uint32_t ch = *pChar)
         {
-            char codepoint[5];
-            Unicode::Convert(codepoint, ch);
+            size_t maxSize = 5;
+            char codepoint[5] = { 0 };
+            char* codepointPtr = codepoint;
+            Utf8::Unchecked::octet_iterator::to_utf8_sequence(ch, codepointPtr, maxSize);
 
             float curCharWidth = font->GetTextSize(codepoint, true, ctx).x;
             if (prevCh)
@@ -2274,7 +2278,7 @@ int UiTextComponent::GetCharIndexFromCanvasSpacePoint(AZ::Vector2 point, bool mu
         // Iterate across the line
         for (const DrawBatch& drawBatch : batchLine.drawBatchList)
         {
-            Unicode::CIterator pChar(drawBatch.text.c_str());
+            Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
             while (uint32_t ch = *pChar)
             {
                 ++pChar;
@@ -4827,14 +4831,16 @@ int UiTextComponent::GetStartEllipseIndexInDrawBatch(const DrawBatch* drawBatchT
 {
     float overflowStringSize = 0.0f;
     int ellipsisCharPos = 0;
-    Unicode::CIterator pChar(drawBatchToEllipse->text.c_str());
+    Utf8::Unchecked::octet_iterator pChar(drawBatchToEllipse->text.data());
     uint32_t stringBufferIndex = 0;
     uint32_t prevCh = 0;
     while (uint32_t ch = *pChar)
     {
         ++pChar;
-        char codepoint[5];
-        Unicode::Convert(codepoint, ch);
+        size_t maxSize = 5;
+        char codepoint[5] = { 0 };
+        char* codepointPtr = codepoint;
+        Utf8::Unchecked::octet_iterator::to_utf8_sequence(ch, codepointPtr, maxSize);
         
         overflowStringSize += drawBatchToEllipse->font->GetTextSize(codepoint, true, ctx).x;
 
@@ -4925,7 +4931,7 @@ AZ::Vector2 UiTextComponent::GetTextSizeFromDrawBatchLines(const UiTextComponent
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 AZStd::string UiTextComponent::GetLocalizedText([[maybe_unused]] const AZStd::string& text)
 {
-    string locText;
+    AZStd::string locText;
     LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::LocalizeString_ch, m_text.c_str(), locText, false);
     return locText.c_str();
 }
@@ -5110,7 +5116,7 @@ int UiTextComponent::GetLineNumberFromCharIndex(const DrawBatchLines& drawBatchL
 
         for (const DrawBatch& drawBatch : batchLine.drawBatchList)
         {
-            Unicode::CIterator pChar(drawBatch.text.c_str());
+            Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
             while (uint32_t ch = *pChar)
             {
                 ++pChar;
diff --git a/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp b/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp
index b4e8a8d63e..b472f79bd6 100644
--- a/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp
+++ b/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp
@@ -30,7 +30,7 @@ void UiTextComponentOffsetsSelector::ParseBatchLine(const UiTextComponent::DrawB
     {
         // Iterate character by character over DrawBatch string contents,
         // looking for m_firstIndex and m_lastIndex.
-        Unicode::CIterator pChar(drawBatch.text.c_str());
+        Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
         while (uint32_t ch = *pChar)
         {
             ++pChar;
diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
index c149c5a4d4..8cc0efcaaf 100644
--- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
@@ -70,7 +70,7 @@ namespace
         if (stringLength > 0 && stringLength >= utf8Index)
         {
             // Iterate over the string until the given index is found.
-            Unicode::CIterator pChar(utf8String.c_str());
+            Utf8::Unchecked::octet_iterator pChar(utf8String.data());
             while (uint32_t ch = *pChar)
             {
                 if (utf8Index == utfIndexIter)
@@ -1185,7 +1185,8 @@ void UiTextInputComponent::UpdateDisplayedTextFunction()
                 // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
                 // work for cases tested but may not in general.
                 wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 };
-                AZStd::string replacementCharString(CryStringUtils::WStrToUTF8(wcharString));
+                AZStd::string replacementCharString;
+                AZStd::to_string(replacementCharString, wcharString, 1);
 
                 int numReplacementChars = LyShine::GetUtf8StringLength(originalText);
 

From ad14d9cdd7a65ef44decde1ada4bb76741ba4a29 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:55:27 -0700
Subject: [PATCH 066/251] AtomFont

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h  | 2 +-
 .../AtomFont/Code/Platform/Common/FontTexture_Common.cpp        | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h
index 0e97440538..6443633245 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h
@@ -26,7 +26,7 @@ namespace AZ
         int Create(int width, int height);
         int Release();
 
-        int SaveBitmap(const string& fileName);
+        int SaveBitmap(const AZStd::string& fileName);
         int Get32Bpp(unsigned int** buffer)
         {
             (*buffer) = new unsigned int[m_width * m_height];
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp
index 02cbb5a7a4..e3be52965c 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp
@@ -11,7 +11,7 @@
 #include 
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontTexture::WriteToFile([[maybe_unused]] const string& fileName)
+int AZ::FontTexture::WriteToFile([[maybe_unused]] const AZStd::string& fileName)
 {
     return 1;
 }

From b1e9d81d96b2d30cd5e3a82dcb6503f7617ac73c Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:55:55 -0700
Subject: [PATCH 067/251] Gems/GameStateSamples

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../GameStateSamples/GameStatePrimaryControllerDisconnected.inl | 2 +-
 .../Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl
index 4e9fb33c7e..ded069a638 100644
--- a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl
+++ b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl
@@ -83,7 +83,7 @@ namespace GameStateSamples
             return;
         }
 
-        string localizedMessage;
+        AZStd::string localizedMessage;
         const char* localizationKey = AZ_TRAIT_GAMESTATESAMPLES_PRIMARY_CONTROLLER_DISCONNECTED_LOC_KEY;
         bool wasLocalized = false;
         LocalizationManagerRequestBus::BroadcastResult(wasLocalized,
diff --git a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl
index d7e45fcbdd..62fa9710dc 100644
--- a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl
+++ b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl
@@ -99,7 +99,7 @@ namespace GameStateSamples
             return;
         }
 
-        string localizedMessage;
+        AZStd::string localizedMessage;
         const char* localizationKey = "@PRIMARY_CONTROLLER_DISCONNECTED_LOC_KEY";
         bool wasLocalized = false;
         LocalizationManagerRequestBus::BroadcastResult(wasLocalized,

From 3b28267569005e7eed1f88b0ce082a129898b454 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:56:28 -0700
Subject: [PATCH 068/251] Gems/PhysXDebug

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Gems/PhysXDebug/Code/Source/SystemComponent.cpp | 1 -
 Gems/PhysXDebug/Code/Source/SystemComponent.h   | 1 +
 2 files changed, 1 insertion(+), 1 deletion(-)

diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
index 0ccc77bba4..4944626d77 100644
--- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
+++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
@@ -30,7 +30,6 @@
 #include 
 
 #include 
-#include 
 
 #include 
 
diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.h b/Gems/PhysXDebug/Code/Source/SystemComponent.h
index 40434ad3e1..83756f20f9 100644
--- a/Gems/PhysXDebug/Code/Source/SystemComponent.h
+++ b/Gems/PhysXDebug/Code/Source/SystemComponent.h
@@ -18,6 +18,7 @@
 
 #include 
 #include 
+#include 
 
 #include 
 

From a14b4e478ee4b893fca85f00f56e4f4378f1d6e3 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:56:56 -0700
Subject: [PATCH 069/251] Code/Editor

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/BaseLibraryManager.cpp            |   4 +-
 Code/Editor/Commands/CommandManager.cpp       |  71 +-
 Code/Editor/Commands/CommandManager.h         |   8 +-
 Code/Editor/ConfigGroup.cpp                   |   6 +-
 Code/Editor/ConfigGroup.h                     |   4 +-
 Code/Editor/Controls/ConsoleSCB.cpp           |   4 +-
 Code/Editor/Controls/FolderTreeCtrl.cpp       |   2 +-
 .../PropertyGenericCtrl.cpp                   |   4 +-
 Code/Editor/Controls/SplineCtrlEx.cpp         |   2 +-
 Code/Editor/Controls/SplineCtrlEx.h           |   2 +-
 Code/Editor/Core/QtEditorApplication.cpp      |   2 +-
 Code/Editor/Core/Tests/test_Main.cpp          |   2 +-
 Code/Editor/CryEdit.cpp                       |  38 +-
 Code/Editor/CryEdit.h                         |  24 +-
 Code/Editor/CryEditDoc.cpp                    |   8 +-
 Code/Editor/CryEditDoc.h                      |   2 +-
 Code/Editor/CryEditPy.cpp                     |   4 +-
 Code/Editor/EditorFileMonitor.cpp             |  12 +-
 Code/Editor/GameExporter.cpp                  |  10 +-
 Code/Editor/IEditorImpl.cpp                   |  33 +-
 Code/Editor/Include/Command.h                 |  24 +-
 Code/Editor/LevelFileDialog.cpp               |   6 +-
 Code/Editor/LogFile.cpp                       |  26 +-
 Code/Editor/MainWindow.cpp                    |   2 +-
 .../Platform/Windows/Util/Mailer_Windows.cpp  |   4 +-
 Code/Editor/PluginManager.cpp                 |   4 +-
 .../EditorAssetImporter/AssetImporterPlugin.h |   2 +-
 Code/Editor/ResourceSelectorHost.cpp          |   4 +-
 Code/Editor/SelectSequenceDialog.cpp          |   2 +-
 Code/Editor/ToolBox.cpp                       |  10 +-
 .../Editor/TrackView/CommentKeyUIControls.cpp |   2 +-
 .../TrackView/SequenceKeyUIControls.cpp       |   2 +-
 Code/Editor/TrackView/TrackViewAnimNode.cpp   |   4 +-
 Code/Editor/TrackView/TrackViewFindDlg.cpp    |   2 +-
 Code/Editor/TrackView/TrackViewNodes.cpp      |   2 +-
 Code/Editor/TrackView/TrackViewSequence.cpp   |   8 +-
 Code/Editor/TrackViewNewSequenceDialog.cpp    |   2 +-
 .../Util/AutoDirectoryRestoreFileDialog.cpp   |   2 +-
 Code/Editor/Util/FileUtil.cpp                 |  15 +-
 Code/Editor/Util/ImageASC.cpp                 |   3 +-
 Code/Editor/Util/ImageTIF.cpp                 |   6 +-
 Code/Editor/Util/ImageUtil.cpp                |   3 +-
 Code/Editor/Util/StringHelpers.cpp            | 847 +-----------------
 Code/Editor/Util/StringHelpers.h              | 188 +---
 Code/Editor/Util/XmlHistoryManager.cpp        |   6 +-
 Code/Editor/Util/XmlHistoryManager.h          |   2 +-
 Code/Legacy/CrySystem/XConsole.cpp            |   7 +-
 47 files changed, 208 insertions(+), 1219 deletions(-)

diff --git a/Code/Editor/BaseLibraryManager.cpp b/Code/Editor/BaseLibraryManager.cpp
index 2189156454..da41525d8b 100644
--- a/Code/Editor/BaseLibraryManager.cpp
+++ b/Code/Editor/BaseLibraryManager.cpp
@@ -526,7 +526,7 @@ void CBaseLibraryManager::Serialize(XmlNodeRef& node, bool bLoading)
 QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QString& libName)
 {
     // unlikely we'll ever encounter more than 16
-    std::vector possibleDuplicates;
+    std::vector possibleDuplicates;
     possibleDuplicates.reserve(16);
 
     // search for strings in the database that might have a similar name (ignore case)
@@ -550,7 +550,7 @@ QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QS
         const QString& name = pItem->GetName();
         if (name.startsWith(srcName, Qt::CaseInsensitive))
         {
-            possibleDuplicates.push_back(string(name.toUtf8().data()));
+            possibleDuplicates.push_back(AZStd::string(name.toUtf8().data()));
         }
     }
     pEnum->Release();
diff --git a/Code/Editor/Commands/CommandManager.cpp b/Code/Editor/Commands/CommandManager.cpp
index 708fccd16b..35f55babe2 100644
--- a/Code/Editor/Commands/CommandManager.cpp
+++ b/Code/Editor/Commands/CommandManager.cpp
@@ -79,9 +79,9 @@ CEditorCommandManager::~CEditorCommandManager()
     m_uiCommands.clear();
 }
 
-string CEditorCommandManager::GetFullCommandName(const AZStd::string& module, const string& name)
+AZStd::string CEditorCommandManager::GetFullCommandName(const AZStd::string& module, const AZStd::string& name)
 {
-    string fullName = module;
+    AZStd::string fullName = module;
     fullName += ".";
     fullName += name;
     return fullName;
@@ -91,10 +91,10 @@ bool CEditorCommandManager::AddCommand(CCommand* pCommand, TPfnDeleter deleter)
 {
     assert(pCommand);
 
-    string module = pCommand->GetModule();
-    string name = pCommand->GetName();
+    AZStd::string module = pCommand->GetModule();
+    AZStd::string name = pCommand->GetName();
 
-    if (IsRegistered(module, name) && m_bWarnDuplicate)
+    if (IsRegistered(module.c_str(), name.c_str()) && m_bWarnDuplicate)
     {
         QString errMsg;
 
@@ -118,7 +118,7 @@ bool CEditorCommandManager::AddCommand(CCommand* pCommand, TPfnDeleter deleter)
 
 bool CEditorCommandManager::UnregisterCommand(const char* module, const char* name)
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::iterator itr = m_commands.find(fullName);
 
     if (itr != m_commands.end())
@@ -154,7 +154,7 @@ bool CEditorCommandManager::RegisterUICommand(
         return false;
     }
 
-    return AttachUIInfo(GetFullCommandName(module, name), uiInfo);
+    return AttachUIInfo(GetFullCommandName(module, name).c_str(), uiInfo);
 }
 
 bool CEditorCommandManager::AttachUIInfo(const char* fullCmdName, const CCommand0::SUIInfo& uiInfo)
@@ -190,14 +190,14 @@ bool CEditorCommandManager::AttachUIInfo(const char* fullCmdName, const CCommand
     return true;
 }
 
-bool CEditorCommandManager::GetUIInfo(const string& module, const string& name, CCommand0::SUIInfo& uiInfo) const
+bool CEditorCommandManager::GetUIInfo(const AZStd::string& module, const AZStd::string& name, CCommand0::SUIInfo& uiInfo) const
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
 
     return GetUIInfo(fullName, uiInfo);
 }
 
-bool CEditorCommandManager::GetUIInfo(const string& fullCmdName, CCommand0::SUIInfo& uiInfo) const
+bool CEditorCommandManager::GetUIInfo(const AZStd::string& fullCmdName, CCommand0::SUIInfo& uiInfo) const
 {
     CommandTable::const_iterator iter = m_commands.find(fullCmdName);
 
@@ -223,9 +223,9 @@ int CEditorCommandManager::GenNewCommandId()
     return uniqueId++;
 }
 
-QString CEditorCommandManager::Execute(const string& module, const string& name, const CCommand::CArgs& args)
+QString CEditorCommandManager::Execute(const AZStd::string& module, const AZStd::string& name, const CCommand::CArgs& args)
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::iterator iter = m_commands.find(fullName);
 
     if (iter != m_commands.end())
@@ -245,18 +245,18 @@ QString CEditorCommandManager::Execute(const string& module, const string& name,
     return "";
 }
 
-QString CEditorCommandManager::Execute(const string& cmdLine)
+QString CEditorCommandManager::Execute(const AZStd::string& cmdLine)
 {
-    string cmdTxt, argsTxt;
+    AZStd::string cmdTxt, argsTxt;
     size_t argStart = cmdLine.find_first_of(' ');
 
     cmdTxt = cmdLine.substr(0, argStart);
     argsTxt = "";
 
-    if (argStart != string::npos)
+    if (argStart != AZStd::string::npos)
     {
         argsTxt = cmdLine.substr(argStart + 1);
-        argsTxt.Trim();
+        AZ::StringFunc::TrimWhiteSpace(argsTxt, true, true);
     }
 
     CommandTable::iterator itr = m_commands.find(cmdTxt);
@@ -301,7 +301,7 @@ void CEditorCommandManager::Execute(int commandId)
     }
 }
 
-void CEditorCommandManager::GetCommandList(std::vector& cmds) const
+void CEditorCommandManager::GetCommandList(std::vector& cmds) const
 {
     cmds.clear();
     cmds.reserve(m_commands.size());
@@ -315,9 +315,9 @@ void CEditorCommandManager::GetCommandList(std::vector& cmds) const
     std::sort(cmds.begin(), cmds.end());
 }
 
-string CEditorCommandManager::AutoComplete(const string& substr) const
+AZStd::string CEditorCommandManager::AutoComplete(const AZStd::string& substr) const
 {
-    std::vector cmds;
+    std::vector cmds;
     GetCommandList(cmds);
 
     // If substring is empty return first command.
@@ -358,7 +358,7 @@ string CEditorCommandManager::AutoComplete(const string& substr) const
 
 bool CEditorCommandManager::IsRegistered(const char* module, const char* name) const
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::const_iterator iter = m_commands.find(fullName);
 
     if (iter != m_commands.end())
@@ -373,7 +373,7 @@ bool CEditorCommandManager::IsRegistered(const char* module, const char* name) c
 
 bool CEditorCommandManager::IsRegistered(const char* cmdLine_) const
 {
-    string cmdTxt, argsTxt, cmdLine(cmdLine_);
+    AZStd::string cmdTxt, argsTxt, cmdLine(cmdLine_);
     size_t argStart = cmdLine.find_first_of(' ');
     cmdTxt = cmdLine.substr(0, argStart);
     CommandTable::const_iterator iter = m_commands.find(cmdTxt);
@@ -402,9 +402,9 @@ bool CEditorCommandManager::IsRegistered(int commandId) const
     return false;
 }
 
-void CEditorCommandManager::SetCommandAvailableInScripting(const string& module, const string& name)
+void CEditorCommandManager::SetCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name)
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::iterator iter = m_commands.find(fullName);
 
     if (iter != m_commands.end())
@@ -413,7 +413,7 @@ void CEditorCommandManager::SetCommandAvailableInScripting(const string& module,
     }
 }
 
-bool CEditorCommandManager::IsCommandAvailableInScripting(const string& fullCmdName) const
+bool CEditorCommandManager::IsCommandAvailableInScripting(const AZStd::string& fullCmdName) const
 {
     CommandTable::const_iterator iter = m_commands.find(fullCmdName);
 
@@ -425,16 +425,16 @@ bool CEditorCommandManager::IsCommandAvailableInScripting(const string& fullCmdN
     return false;
 }
 
-bool CEditorCommandManager::IsCommandAvailableInScripting(const string& module, const string& name) const
+bool CEditorCommandManager::IsCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name) const
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
 
     return IsCommandAvailableInScripting(fullName);
 }
 
-void CEditorCommandManager::LogCommand(const string& fullCmdName, const CCommand::CArgs& args) const
+void CEditorCommandManager::LogCommand(const AZStd::string& fullCmdName, const CCommand::CArgs& args) const
 {
-    string cmdLine = fullCmdName;
+    AZStd::string cmdLine = fullCmdName;
 
     for (int i = 0; i < args.GetArgCount(); ++i)
     {
@@ -509,7 +509,7 @@ void CEditorCommandManager::LogCommand(const string& fullCmdName, const CCommand
 
     if (pScriptTermDialog)
     {
-        string text = "> ";
+        AZStd::string text = "> ";
         text += cmdLine;
         text += "\r\n";
         pScriptTermDialog->AppendText(text.c_str());
@@ -526,14 +526,14 @@ QString CEditorCommandManager::ExecuteAndLogReturn(CCommand* pCommand, const CCo
     return result;
 }
 
-void CEditorCommandManager::GetArgsFromString(const string& argsTxt, CCommand::CArgs& argList)
+void CEditorCommandManager::GetArgsFromString(const AZStd::string& argsTxt, CCommand::CArgs& argList)
 {
     const char quoteSymbol = '\'';
     int curPos = 0;
     int prevPos = 0;
-    string arg = argsTxt.Tokenize(" ", curPos);
-
-    while (!arg.empty())
+    AZStd::vector tokens;
+    AZ::StringFunc::Tokenize(argsTxt, tokens, ' ');
+    for(AZStd::string& arg : tokens)
     {
         if (arg[0] == quoteSymbol)   // A special consideration for a quoted string
         {
@@ -542,11 +542,11 @@ void CEditorCommandManager::GetArgsFromString(const string& argsTxt, CCommand::C
                 size_t openingQuotePos = argsTxt.find(quoteSymbol, prevPos);
                 size_t closingQuotePos = argsTxt.find(quoteSymbol, curPos);
 
-                if (closingQuotePos != string::npos)
+                if (closingQuotePos != AZStd::string::npos)
                 {
                     arg = argsTxt.substr(openingQuotePos + 1, closingQuotePos - openingQuotePos - 1);
                     size_t nextArgPos = argsTxt.find(' ', closingQuotePos + 1);
-                    curPos = nextArgPos != string::npos ? nextArgPos + 1 : argsTxt.length();
+                    curPos = nextArgPos != AZStd::string::npos ? nextArgPos + 1 : argsTxt.length();
 
                     for (; curPos < argsTxt.length(); ++curPos)    // Skip spaces.
                     {
@@ -565,6 +565,5 @@ void CEditorCommandManager::GetArgsFromString(const string& argsTxt, CCommand::C
 
         argList.Add(arg.c_str());
         prevPos = curPos;
-        arg = argsTxt.Tokenize(" ", curPos);
     }
 }
diff --git a/Code/Editor/Commands/CommandManager.h b/Code/Editor/Commands/CommandManager.h
index a76df830d0..0af744ac72 100644
--- a/Code/Editor/Commands/CommandManager.h
+++ b/Code/Editor/Commands/CommandManager.h
@@ -53,9 +53,9 @@ public:
     QString Execute(const AZStd::string& cmdLine);
     QString Execute(const AZStd::string& module, const AZStd::string& name, const CCommand::CArgs& args);
     void Execute(int commandId);
-    void GetCommandList(std::vector& cmds) const;
+    void GetCommandList(std::vector& cmds) const;
     //! Used in the console dialog
-    string AutoComplete(const AZStd::string& substr) const;
+    AZStd::string AutoComplete(const AZStd::string& substr) const;
     bool IsRegistered(const char* module, const char* name) const;
     bool IsRegistered(const char* cmdLine) const;
     bool IsRegistered(int commandId) const;
@@ -74,7 +74,7 @@ protected:
     };
 
     //! A full command name to an actual command mapping
-    typedef std::map CommandTable;
+    typedef std::map CommandTable;
     AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING
     CommandTable m_commands;
 
@@ -86,7 +86,7 @@ protected:
     bool m_bWarnDuplicate;
 
     static int GenNewCommandId();
-    static string GetFullCommandName(const AZStd::string& module, const AZStd::string& name);
+    static AZStd::string GetFullCommandName(const AZStd::string& module, const AZStd::string& name);
     static void GetArgsFromString(const AZStd::string& argsTxt, CCommand::CArgs& argList);
     void LogCommand(const AZStd::string& fullCmdName, const CCommand::CArgs& args) const;
     QString ExecuteAndLogReturn(CCommand* pCommand, const CCommand::CArgs& args);
diff --git a/Code/Editor/ConfigGroup.cpp b/Code/Editor/ConfigGroup.cpp
index 4e61c38f4b..04c92ff155 100644
--- a/Code/Editor/ConfigGroup.cpp
+++ b/Code/Editor/ConfigGroup.cpp
@@ -127,9 +127,9 @@ namespace Config
 
                     case IConfigVar::eType_STRING:
                     {
-                        string currentValue = 0;
+                        AZStd::string currentValue = 0;
                         var->Get(¤tValue);
-                        node->setAttr(szName, currentValue);
+                        node->setAttr(szName, currentValue.c_str());
                         break;
                     }
                     }
@@ -186,7 +186,7 @@ namespace Config
 
                 case IConfigVar::eType_STRING:
                 {
-                    string currentValue = 0;
+                    AZStd::string currentValue = 0;
                     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 5d9b22b2b9..aa379d4445 100644
--- a/Code/Editor/ConfigGroup.h
+++ b/Code/Editor/ConfigGroup.h
@@ -76,8 +76,8 @@ namespace Config
     protected:
         EType m_type;
         uint8 m_flags;
-        string m_name;
-        string m_description;
+        AZStd::string m_name;
+        AZStd::string m_description;
         void* m_ptr;
         ICVar* m_pCVar;
     };
diff --git a/Code/Editor/Controls/ConsoleSCB.cpp b/Code/Editor/Controls/ConsoleSCB.cpp
index 9f1921395c..0c664bbc59 100644
--- a/Code/Editor/Controls/ConsoleSCB.cpp
+++ b/Code/Editor/Controls/ConsoleSCB.cpp
@@ -180,7 +180,7 @@ bool ConsoleLineEdit::event(QEvent* ev)
 
         if (newStr.isEmpty())
         {
-            newStr = GetIEditor()->GetCommandManager()->AutoComplete(cstring.toUtf8().data());
+            newStr = GetIEditor()->GetCommandManager()->AutoComplete(cstring.toUtf8().data()).c_str();
         }
     }
 
@@ -211,7 +211,7 @@ void ConsoleLineEdit::keyPressEvent(QKeyEvent* ev)
         {
             if (commandManager->IsRegistered(str.toUtf8().data()))
             {
-                commandManager->Execute(QtUtil::ToString(str));
+                commandManager->Execute(str.toUtf8().data());
             }
             else
             {
diff --git a/Code/Editor/Controls/FolderTreeCtrl.cpp b/Code/Editor/Controls/FolderTreeCtrl.cpp
index 17b6dccac7..b1cbb9414e 100644
--- a/Code/Editor/Controls/FolderTreeCtrl.cpp
+++ b/Code/Editor/Controls/FolderTreeCtrl.cpp
@@ -400,7 +400,7 @@ void CFolderTreeCtrl::RemoveEmptyFolderItems(const QString& folder)
 
 void CFolderTreeCtrl::Edit(const QString& path)
 {
-    CFileUtil::EditTextFile(QtUtil::ToString(path), 0, IFileUtil::FILE_TYPE_SCRIPT);
+    CFileUtil::EditTextFile(path.toUtf8().data(), 0, IFileUtil::FILE_TYPE_SCRIPT);
 }
 
 void CFolderTreeCtrl::ShowInExplorer(const QString& path)
diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp
index 1916ce5e16..a2c66b8b10 100644
--- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp
+++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp
@@ -132,7 +132,9 @@ void LocalStringPropertyEditor::onEditClicked()
         if (pMgr->GetLocalizedInfoByIndex(i, sInfo))
         {
             item.desc = tr("English Text:\r\n");
-            item.desc += QString::fromWCharArray(Unicode::Convert(sInfo.sUtf8TranslatedText).c_str());
+            AZStd::wstring utf8TranslatedTextW;
+            AZStd::to_wstring(utf8TranslatedTextW, sInfo.sUtf8TranslatedText);
+            item.desc += QString::fromWCharArray(utf8TranslatedTextW.c_str());
             item.name = sInfo.sKey;
             items.push_back(item);
         }
diff --git a/Code/Editor/Controls/SplineCtrlEx.cpp b/Code/Editor/Controls/SplineCtrlEx.cpp
index 2afc3f16aa..73ede63951 100644
--- a/Code/Editor/Controls/SplineCtrlEx.cpp
+++ b/Code/Editor/Controls/SplineCtrlEx.cpp
@@ -127,7 +127,7 @@ private:
         std::vector keySelectionFlags;
         _smart_ptr undo;
         _smart_ptr redo;
-        string id;
+        AZStd::string id;
         ISplineInterpolator* pSpline;
     };
 
diff --git a/Code/Editor/Controls/SplineCtrlEx.h b/Code/Editor/Controls/SplineCtrlEx.h
index de07c4214b..add4bcb0a9 100644
--- a/Code/Editor/Controls/SplineCtrlEx.h
+++ b/Code/Editor/Controls/SplineCtrlEx.h
@@ -54,7 +54,7 @@ class ISplineSet
 {
 public:
     virtual ISplineInterpolator* GetSplineFromID(const AZStd::string& id) = 0;
-    virtual string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
+    virtual AZStd::string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
     virtual int GetSplineCount() const = 0;
     virtual int GetKeyCountAtTime(float time, float threshold) const = 0;
 };
diff --git a/Code/Editor/Core/QtEditorApplication.cpp b/Code/Editor/Core/QtEditorApplication.cpp
index 9ec3b57e29..11f65bfaa5 100644
--- a/Code/Editor/Core/QtEditorApplication.cpp
+++ b/Code/Editor/Core/QtEditorApplication.cpp
@@ -206,7 +206,7 @@ namespace
 
     static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
     {
-        AZ::Debug::Platform::OutputToDebugger("Qt", message.utf8());
+        AZ::Debug::Platform::OutputToDebugger("Qt", message.toUtf8().data());
         AZ::Debug::Platform::OutputToDebugger(nullptr, "\n");
     }
 }
diff --git a/Code/Editor/Core/Tests/test_Main.cpp b/Code/Editor/Core/Tests/test_Main.cpp
index c0772753c6..c0e34311ec 100644
--- a/Code/Editor/Core/Tests/test_Main.cpp
+++ b/Code/Editor/Core/Tests/test_Main.cpp
@@ -52,7 +52,7 @@ protected:
     }
 
 private:
-    AZ::AllocatorScope m_allocatorScope;
+    AZ::AllocatorScope m_allocatorScope;
     SSystemGlobalEnvironment m_stubEnv;
     AZ::IO::LocalFileIO m_fileIO;
     NiceMock* m_cryPak;
diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp
index 973a818b92..b69bfa78f3 100644
--- a/Code/Editor/CryEdit.cpp
+++ b/Code/Editor/CryEdit.cpp
@@ -272,8 +272,8 @@ void CCryDocManager::OnFileNew()
     m_pDefTemplate->OpenDocumentFile(NULL);
     // 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,7 +287,7 @@ BOOL CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT n
 
     return false;
 }
-CCryEditDoc* CCryDocManager::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU)
+CCryEditDoc* CCryDocManager::OpenDocumentFile(const char* lpszFileName, bool bAddToMRU)
 {
     assert(lpszFileName != NULL);
 
@@ -657,7 +657,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();
@@ -805,12 +805,12 @@ void CCryEditApp::InitDirectory()
 // Needed to work with custom memory manager.
 //////////////////////////////////////////////////////////////////////////
 
-CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible /*= true*/)
+CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bMakeVisible /*= true*/)
 {
     return OpenDocumentFile(lpszPathName, true, bMakeVisible);
 }
 
-CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL bAddToMRU, [[maybe_unused]] BOOL bMakeVisible)
+CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bAddToMRU, [[maybe_unused]] bool bMakeVisible)
 {
     CCryEditDoc* pCurDoc = GetIEditor()->GetDocument();
 
@@ -849,7 +849,7 @@ CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL
     return pCurDoc;
 }
 
-CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(LPCTSTR lpszPathName, CCryEditDoc*& rpDocMatch)
+CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch)
 {
     assert(lpszPathName != NULL);
     rpDocMatch = NULL;
@@ -1059,7 +1059,7 @@ AZ::Outcome CCryEditApp::InitGameSystem(HWND hwndForInputSy
 }
 
 /////////////////////////////////////////////////////////////////////////////
-BOOL CCryEditApp::CheckIfAlreadyRunning()
+bool CCryEditApp::CheckIfAlreadyRunning()
 {
     bool bForceNewInstance = false;
 
@@ -1303,7 +1303,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())
@@ -1593,7 +1593,7 @@ void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo)
 
 /////////////////////////////////////////////////////////////////////////////
 // CCryEditApp initialization
-BOOL CCryEditApp::InitInstance()
+bool CCryEditApp::InitInstance()
 {
     QElapsedTimer startupTimer;
     startupTimer.start();
@@ -2281,7 +2281,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)
     {
@@ -3226,7 +3226,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());
@@ -3280,7 +3280,7 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
         GetIEditor()->GetDocument()->DeleteTemporaryLevel();
     }
 
-    if (levelName.length() == 0 || !CryStringUtils::IsValidFileName(levelName.toUtf8().data()))
+    if (levelName.length() == 0 || !AZ::StringFunc::Path::IsValid(levelName.toUtf8().data()))
     {
         QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level name is invalid, please choose another name."));
         return false;
@@ -3313,13 +3313,15 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
         DWORD dw = GetLastError();
 
 #ifdef WIN32
-        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+        wchar_t windowsErrorMessageW[ERROR_LEN] = { 0 };
+        FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
             NULL,
             dw,
             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-            windowsErrorMessage.data(),
-            windowsErrorMessage.length(), NULL);
+            windowsErrorMessageW,
+            ERROR_LEN - 1, NULL);
         _getcwd(cwd.data(), cwd.length());
+        AZStd::to_string(windowsErrorMessage.data(), ERROR_LEN, windowsErrorMessageW);
 #else
         windowsErrorMessage = strerror(dw);
         cwd = QDir::currentPath().toUtf8();
@@ -3393,7 +3395,7 @@ void CCryEditApp::OnOpenSlice()
 }
 
 //////////////////////////////////////////////////////////////////////////
-CCryEditDoc* CCryEditApp::OpenDocumentFile(LPCTSTR lpszFileName)
+CCryEditDoc* CCryEditApp::OpenDocumentFile(const char* lpszFileName)
 {
     if (m_openingLevel)
     {
@@ -4250,7 +4252,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 af0fbb0971..431a9cb817 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,10 +171,10 @@ 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 CCryEditDoc* OpenDocumentFile(LPCTSTR lpszFileName);
+    virtual bool OnIdle(LONG lCount);
+    virtual CCryEditDoc* OpenDocumentFile(const char* lpszFileName);
 
     CCryDocManager* GetDocManager() { return m_pDocManager; }
 
@@ -454,9 +454,9 @@ 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 Confidence MatchDocType(LPCTSTR lpszPathName, CCryEditDoc*& rpDocMatch);
+    virtual CCryEditDoc* OpenDocumentFile(const char* lpszPathName, bool bAddToMRU, bool bMakeVisible);
+    virtual CCryEditDoc* OpenDocumentFile(const char* lpszPathName, bool bMakeVisible = TRUE);
+    virtual Confidence MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch);
 
 private:
     const QMetaObject* m_documentClass = nullptr;
@@ -471,9 +471,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(const char* lpszFileName, bool bAddToMRU);
 
     QVector m_templateList;
 };
diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp
index 43f599b191..5438f44f37 100644
--- a/Code/Editor/CryEditDoc.cpp
+++ b/Code/Editor/CryEditDoc.cpp
@@ -426,8 +426,8 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename)
         Audio::AudioSystemRequestBus::BroadcastResult(controlsPath, &Audio::AudioSystemRequestBus::Events::GetControlsPath);
         QString sAudioLevelPath(controlsPath);
         sAudioLevelPath += "levels/";
-        string const sLevelNameOnly = PathUtil::GetFileName(fileName.toUtf8().data());
-        sAudioLevelPath += sLevelNameOnly;
+        AZStd::string const sLevelNameOnly = PathUtil::GetFileName(fileName.toUtf8().data());
+        sAudioLevelPath += sLevelNameOnly.c_str();
         QByteArray path = sAudioLevelPath.toUtf8();
         Audio::SAudioManagerRequestData oAMData(path, Audio::eADS_LEVEL_SPECIFIC);
         Audio::SAudioRequest oAudioRequestData;
@@ -1919,7 +1919,7 @@ void CCryEditDoc::LogLoadTime(int time)
 
     CLogFile::FormatLine("[LevelLoadTime] Level %s loaded in %d seconds", level.toUtf8().data(), time / 1000);
 #if defined(AZ_PLATFORM_WINDOWS)
-    SetFileAttributes(filename.toUtf8().data(), FILE_ATTRIBUTE_ARCHIVE);
+    SetFileAttributesW(filename.toStdWString().c_str(), FILE_ATTRIBUTE_ARCHIVE);
 #endif
 
     FILE* file = nullptr;
@@ -2152,7 +2152,7 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar)
     }
 }
 
-QString CCryEditDoc::GetCryIndexPath(const LPCTSTR levelFilePath)
+QString CCryEditDoc::GetCryIndexPath(const char* levelFilePath)
 {
     QString levelPath = Path::GetPath(levelFilePath);
     QString levelName = Path::GetFileName(levelFilePath);
diff --git a/Code/Editor/CryEditDoc.h b/Code/Editor/CryEditDoc.h
index 574f8eb7da..9d86f62489 100644
--- a/Code/Editor/CryEditDoc.h
+++ b/Code/Editor/CryEditDoc.h
@@ -180,7 +180,7 @@ protected:
     void OnStartLevelResourceList();
     static void OnValidateSurfaceTypesChanged(ICVar*);
 
-    QString GetCryIndexPath(const LPCTSTR levelFilePath);
+    QString GetCryIndexPath(const char* levelFilePath);
 
     //////////////////////////////////////////////////////////////////////////
     // SliceEditorEntityOwnershipServiceNotificationBus::Handler
diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp
index e65af3a19b..6abaf933fe 100644
--- a/Code/Editor/CryEditPy.cpp
+++ b/Code/Editor/CryEditPy.cpp
@@ -210,7 +210,7 @@ namespace
     const char* PyGetCurrentLevelName()
     {
         // Using static member to capture temporary data
-        static string tempLevelName;
+        static AZStd::string tempLevelName;
         tempLevelName = GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().data();
         return tempLevelName.c_str();
     }
@@ -218,7 +218,7 @@ namespace
     const char* PyGetCurrentLevelPath()
     {
         // Using static member to capture temporary data
-        static string tempLevelPath;
+        static AZStd::string tempLevelPath;
         tempLevelPath = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
         return tempLevelPath.c_str();
     }
diff --git a/Code/Editor/EditorFileMonitor.cpp b/Code/Editor/EditorFileMonitor.cpp
index 96dc883ab0..ae5d900f2d 100644
--- a/Code/Editor/EditorFileMonitor.cpp
+++ b/Code/Editor/EditorFileMonitor.cpp
@@ -55,10 +55,10 @@ bool CEditorFileMonitor::RegisterListener(IFileChangeListener* pListener, const
 
 
 //////////////////////////////////////////////////////////////////////////
-static string CanonicalizePath(const char* path)
+static AZStd::string CanonicalizePath(const char* path)
 {
     auto canon = QFileInfo(path).canonicalFilePath();
-    return canon.isEmpty() ? string(path) : string(canon.toUtf8());
+    return canon.isEmpty() ? AZStd::string(path) : AZStd::string(canon.toUtf8());
 }
 
 //////////////////////////////////////////////////////////////////////////
@@ -66,8 +66,8 @@ bool CEditorFileMonitor::RegisterListener(IFileChangeListener* pListener, const
 {
     bool success = true;
 
-    string gameFolder = Path::GetEditingGameDataFolder().c_str();
-    string naivePath;
+    AZStd::string gameFolder = Path::GetEditingGameDataFolder().c_str();
+    AZStd::string naivePath;
     CFileChangeMonitor* fileChangeMonitor = CFileChangeMonitor::Instance();
     AZ_Assert(fileChangeMonitor, "CFileChangeMonitor singleton missing.");
 
@@ -75,12 +75,12 @@ bool CEditorFileMonitor::RegisterListener(IFileChangeListener* pListener, const
     // Append slash in preparation for appending the second part.
     naivePath = PathUtil::AddSlash(naivePath);
     naivePath += sFolderRelativeToGame;
-    naivePath.replace('/', '\\');
+    AZ::StringFunc::Replace(naivePath, '/', '\\');
 
     // Remove the final slash if the given item is a folder so the file change monitor correctly picks up on it.
     naivePath = PathUtil::RemoveSlash(naivePath);
 
-    string canonicalizedPath = CanonicalizePath(naivePath.c_str());
+    AZStd::string canonicalizedPath = CanonicalizePath(naivePath.c_str());
 
     if (fileChangeMonitor->IsDirectory(canonicalizedPath.c_str()) || fileChangeMonitor->IsFile(canonicalizedPath.c_str()))
     {
diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp
index 006eb9189c..4c9031f08d 100644
--- a/Code/Editor/GameExporter.cpp
+++ b/Code/Editor/GameExporter.cpp
@@ -378,11 +378,11 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName
 {
     // process the folder of the specified map name, producing a filelist.xml file
     //  that can later be used for map downloads
-    string newpath;
+    AZStd::string newpath;
 
     QString filename = levelName;
-    string mapname = (filename + ".dds").toUtf8().data();
-    string metaname = (filename + ".xml").toUtf8().data();
+    AZStd::string mapname = (filename + ".dds").toUtf8().data();
+    AZStd::string metaname = (filename + ".xml").toUtf8().data();
 
     XmlNodeRef rootNode = gEnv->pSystem->CreateXmlNode("download");
     rootNode->setAttr("name", filename.toUtf8().data());
@@ -434,9 +434,9 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName
                     newFileNode->setAttr("size", handle.m_fileDesc.nSize);
 
                     unsigned char md5[16];
-                    string filenameToHash = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
+                    AZStd::string filenameToHash = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
                     filenameToHash += "/";
-                    filenameToHash += string{ handle.m_filename.data(), handle.m_filename.size() };
+                    filenameToHash += AZStd::string{ handle.m_filename.data(), handle.m_filename.size() };
                     if (gEnv->pCryPak->ComputeMD5(filenameToHash.data(), md5))
                     {
                         char md5string[33];
diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp
index 2e755bd36a..65d5792aa5 100644
--- a/Code/Editor/IEditorImpl.cpp
+++ b/Code/Editor/IEditorImpl.cpp
@@ -26,6 +26,7 @@ AZ_POP_DISABLE_WARNING
 #include 
 #include 
 #include 
+#include 
 
 // AzFramework
 #include 
@@ -1107,16 +1108,18 @@ void CEditorImpl::DetectVersion()
     DWORD dwHandle;
     UINT len;
 
-    char ver[1024 * 8];
+    wchar_t ver[1024 * 8];
 
     AZ::Utils::GetExecutablePath(exe, _MAX_PATH);
+    AZStd::wstring exeW;
+    AZStd::to_wstring(exeW, exe);
 
-    int verSize = GetFileVersionInfoSize(exe, &dwHandle);
+    int verSize = GetFileVersionInfoSizeW(exeW.c_str(), &dwHandle);
     if (verSize > 0)
     {
-        GetFileVersionInfo(exe, dwHandle, 1024 * 8, ver);
+        GetFileVersionInfoW(exeW.c_str(), dwHandle, 1024 * 8, ver);
         VS_FIXEDFILEINFO* vinfo;
-        VerQueryValue(ver, "\\", (void**)&vinfo, &len);
+        VerQueryValueW(ver, L"\\", (void**)&vinfo, &len);
 
         m_fileVersion.v[0] = vinfo->dwFileVersionLS & 0xFFFF;
         m_fileVersion.v[1] = vinfo->dwFileVersionLS >> 16;
@@ -1557,31 +1560,31 @@ IExportManager* CEditorImpl::GetExportManager()
 void CEditorImpl::AddUIEnums()
 {
     // Spec settings for shadow casting lights
-    string SpecString[4];
+    AZStd::string SpecString[4];
     QStringList types;
     types.push_back("Never=0");
-    SpecString[0].Format("VeryHigh Spec=%d", CONFIG_VERYHIGH_SPEC);
+    SpecString[0] = AZStd::string::format("VeryHigh Spec=%d", CONFIG_VERYHIGH_SPEC);
     types.push_back(SpecString[0].c_str());
-    SpecString[1].Format("High Spec=%d", CONFIG_HIGH_SPEC);
+    SpecString[1] = AZStd::string::format("High Spec=%d", CONFIG_HIGH_SPEC);
     types.push_back(SpecString[1].c_str());
-    SpecString[2].Format("Medium Spec=%d", CONFIG_MEDIUM_SPEC);
+    SpecString[2] = AZStd::string::format("Medium Spec=%d", CONFIG_MEDIUM_SPEC);
     types.push_back(SpecString[2].c_str());
-    SpecString[3].Format("Low Spec=%d", CONFIG_LOW_SPEC);
+    SpecString[3] = AZStd::string::format("Low Spec=%d", CONFIG_LOW_SPEC);
     types.push_back(SpecString[3].c_str());
     m_pUIEnumsDatabase->SetEnumStrings("CastShadows", types);
 
     // Power-of-two percentages
-    string percentStringPOT[5];
+    AZStd::string percentStringPOT[5];
     types.clear();
-    percentStringPOT[0].Format("Default=%d", 0);
+    percentStringPOT[0] = AZStd::string::format("Default=%d", 0);
     types.push_back(percentStringPOT[0].c_str());
-    percentStringPOT[1].Format("12.5=%d", 1);
+    percentStringPOT[1] = AZStd::string::format("12.5=%d", 1);
     types.push_back(percentStringPOT[1].c_str());
-    percentStringPOT[2].Format("25=%d", 2);
+    percentStringPOT[2] = AZStd::string::format("25=%d", 2);
     types.push_back(percentStringPOT[2].c_str());
-    percentStringPOT[3].Format("50=%d", 3);
+    percentStringPOT[3] = AZStd::string::format("50=%d", 3);
     types.push_back(percentStringPOT[3].c_str());
-    percentStringPOT[4].Format("100=%d", 4);
+    percentStringPOT[4] = AZStd::string::format("100=%d", 4);
     types.push_back(percentStringPOT[4].c_str());
     m_pUIEnumsDatabase->SetEnumStrings("ShadowMinResPercent", types);
 }
diff --git a/Code/Editor/Include/Command.h b/Code/Editor/Include/Command.h
index 92a7736446..e4fea5a3e7 100644
--- a/Code/Editor/Include/Command.h
+++ b/Code/Editor/Include/Command.h
@@ -18,7 +18,7 @@
 
 #include "Util/EditorUtils.h"
 
-inline string ToString(const QString& s)
+inline AZStd::string ToString(const QString& s)
 {
     return s.toUtf8().data();
 }
@@ -85,7 +85,7 @@ public:
             return m_args[i];
         }
     private:
-        DynArray m_args;
+        DynArray m_args;
         unsigned char m_stringFlags;    // This is needed to quote string parameters when logging a command.
     };
 
@@ -104,15 +104,15 @@ public:
 
 protected:
     friend class CEditorCommandManager;
-    string m_module;
-    string m_name;
-    string m_description;
-    string m_example;
+    AZStd::string m_module;
+    AZStd::string m_name;
+    AZStd::string m_description;
+    AZStd::string m_example;
     bool m_bAlsoAvailableInScripting;
 
     template 
-    static string ToString_(T t) { return ::ToString(t); }
-    static inline string ToString_(const char* val)
+    static AZStd::string ToString_(T t) { return ::ToString(t); }
+    static inline AZStd::string ToString_(const char* val)
     { return val; }
     template 
     static bool FromString_(T& t, const char* s) { return ::FromString(t, s); }
@@ -146,10 +146,10 @@ public:
     // UI metadata for this command, if any
     struct SUIInfo
     {
-        string caption;
-        string tooltip;
-        string description;
-        string iconFilename;
+        AZStd::string caption;
+        AZStd::string tooltip;
+        AZStd::string description;
+        AZStd::string iconFilename;
         int iconIndex;
         int commandId; // Windows command id
 
diff --git a/Code/Editor/LevelFileDialog.cpp b/Code/Editor/LevelFileDialog.cpp
index 41bb4d6faa..cefa1330eb 100644
--- a/Code/Editor/LevelFileDialog.cpp
+++ b/Code/Editor/LevelFileDialog.cpp
@@ -98,7 +98,7 @@ CLevelFileDialog::CLevelFileDialog(bool openDialog, QWidget* parent)
         connect(ui->nameLineEdit, &QLineEdit::textChanged, this, &CLevelFileDialog::OnNameChanged);
     }
 
-    // reject invalid file names (see CryStringUtils::IsValidFileName)
+    // reject invalid file names
     ui->nameLineEdit->setValidator(new QRegExpValidator(QRegExp("^[a-zA-Z0-9_\\-./]*$"), ui->nameLineEdit));
 
     ReloadTree();
@@ -315,7 +315,7 @@ void CLevelFileDialog::OnNewFolder()
             const QString newFolderName = inputDlg.textValue();
             const QString newFolderPath = parentFullPath + "/" + newFolderName;
 
-            if (!CryStringUtils::IsValidFileName(newFolderName.toUtf8().data()))
+            if (!AZ::StringFunc::Path::IsValid(newFolderName.toUtf8().data()))
             {
                 QMessageBox box(this);
                 box.setText(tr("Please enter a single, valid folder name(standard English alphanumeric characters only)"));
@@ -416,7 +416,7 @@ bool CLevelFileDialog::ValidateSaveLevelPath(QString& errorMessage) const
     const QString enteredPath = GetEnteredPath();
     const QString levelPath = GetLevelPath();
 
-    if (!CryStringUtils::IsValidFileName(Path::GetFileName(levelPath).toUtf8().data()))
+    if (!AZ::StringFunc::Path::IsValid(Path::GetFileName(levelPath).toUtf8().data()))
     {
         errorMessage = tr("Please enter a valid level name (standard English alphanumeric characters only)");
         return false;
diff --git a/Code/Editor/LogFile.cpp b/Code/Editor/LogFile.cpp
index 8c04eab58c..76c6f34181 100644
--- a/Code/Editor/LogFile.cpp
+++ b/Code/Editor/LogFile.cpp
@@ -180,14 +180,14 @@ void CLogFile::FormatLineV(const char * format, va_list argList)
 void CLogFile::AboutSystem()
 {
     char szBuffer[MAX_LOGBUFFER_SIZE];
+    wchar_t szBufferW[MAX_LOGBUFFER_SIZE];
 #if defined(AZ_PLATFORM_WINDOWS) || defined(AZ_PLATFORM_LINUX)
     //////////////////////////////////////////////////////////////////////
     // Write the system informations to the log
     //////////////////////////////////////////////////////////////////////
 
-    char szProfileBuffer[128];
-    char szLanguageBuffer[64];
-    //char szCPUModel[64];
+    wchar_t szLanguageBufferW[64];
+    //wchar_t szCPUModel[64];
     MEMORYSTATUS MemoryStatus;
 #endif // defined(AZ_PLATFORM_WINDOWS) || defined(AZ_PLATFORM_LINUX)
 
@@ -201,11 +201,13 @@ void CLogFile::AboutSystem()
     //////////////////////////////////////////////////////////////////////
 
     // Get system language
-    GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SENGLANGUAGE,
-        szLanguageBuffer, sizeof(szLanguageBuffer));
+    GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SENGLANGUAGE,
+        szLanguageBufferW, sizeof(szLanguageBufferW));
+    AZStd::string szLanguageBuffer;
+    AZStd::to_string(szLanguageBuffer, szLanguageBufferW);
 
     // Format and send OS information line
-    azsnprintf(szBuffer, MAX_LOGBUFFER_SIZE, "Current Language: %s ", szLanguageBuffer);
+    azsnprintf(szBuffer, MAX_LOGBUFFER_SIZE, "Current Language: %s ", szLanguageBuffer.c_str());
     CryLog("%s", szBuffer);
 #else
     QLocale locale;
@@ -294,7 +296,8 @@ AZ_POP_DISABLE_WARNING
     //////////////////////////////////////////////////////////////////////
 
     str += " (";
-    GetWindowsDirectory(szBuffer, sizeof(szBuffer));
+    GetWindowsDirectoryW(szBufferW, sizeof(szBufferW));
+    AZStd::to_string(szBuffer, MAX_LOGBUFFER_SIZE, szBufferW);
     str += szBuffer;
     str += ")";
     CryLog("%s", str.toUtf8().data());
@@ -381,12 +384,13 @@ AZ_POP_DISABLE_WARNING
 
 #if defined(AZ_PLATFORM_WINDOWS)
     EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &DisplayConfig);
-    GetPrivateProfileString("boot.description", "display.drv",
-        "(Unknown graphics card)", szProfileBuffer, sizeof(szProfileBuffer),
-        "system.ini");
+    GetPrivateProfileStringW(L"boot.description", L"display.drv",
+        L"(Unknown graphics card)", szLanguageBufferW, sizeof(szLanguageBufferW),
+        L"system.ini");
+    AZStd::to_string(szLanguageBuffer, szLanguageBufferW);
     azsnprintf(szBuffer, MAX_LOGBUFFER_SIZE, "Current display mode is %dx%dx%d, %s",
         DisplayConfig.dmPelsWidth, DisplayConfig.dmPelsHeight,
-        DisplayConfig.dmBitsPerPel, szProfileBuffer);
+        DisplayConfig.dmBitsPerPel, szLanguageBuffer.c_str());
     CryLog("%s", szBuffer);
 #else
     auto screen = QGuiApplication::primaryScreen();
diff --git a/Code/Editor/MainWindow.cpp b/Code/Editor/MainWindow.cpp
index ff322b79ac..c5352cbc4c 100644
--- a/Code/Editor/MainWindow.cpp
+++ b/Code/Editor/MainWindow.cpp
@@ -1634,7 +1634,7 @@ void MainWindow::OnUpdateConnectionStatus()
 
         status = tr("Pending Jobs : %1  Failed Jobs : %2").arg(m_connectionListener->GetJobsCount()).arg(failureCount);
 
-        statusBar->SetItem(QtUtil::ToQString("connection"), status, tooltip, icon);
+        statusBar->SetItem("connection", status, tooltip, icon);
 
         if (m_showAPDisconnectDialog && m_connectionListener->GetState() != EConnectionState::Connected)
         {
diff --git a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
index e7cc8658f0..0b33caed88 100644
--- a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
+++ b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
@@ -60,11 +60,11 @@ bool CMailer::SendMail(const char* subject,
     // Handle Recipients
     MapiRecipDesc* recipients = new MapiRecipDesc[numRecipients];
 
-    std::vector addresses;
+    std::vector addresses;
     addresses.resize(numRecipients);
     for (i = 0; i < numRecipients; i++)
     {
-        addresses[i] = string("SMTP:") + _recipients[i];
+        addresses[i] = AZStd::string("SMTP:") + _recipients[i];
     }
 
     for (i = 0; i < numRecipients; i++)
diff --git a/Code/Editor/PluginManager.cpp b/Code/Editor/PluginManager.cpp
index f03cb54fce..3432ca33ba 100644
--- a/Code/Editor/PluginManager.cpp
+++ b/Code/Editor/PluginManager.cpp
@@ -126,8 +126,8 @@ namespace
 
 bool CPluginManager::LoadPlugins(const char* pPathWithMask)
 {
-    QString strPath = QtUtil::ToQString(PathUtil::GetPath(pPathWithMask));
-    QString strMask = QString::fromUtf8(PathUtil::GetFile(pPathWithMask));
+    QString strPath = PathUtil::GetPath(pPathWithMask).c_str();
+    QString strMask = PathUtil::GetFile(pPathWithMask);
 
     CLogFile::WriteLine("[Plugin Manager] Loading plugins...");
 
diff --git a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
index 8bdfb48774..d78e6cab4e 100644
--- a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
+++ b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
@@ -88,7 +88,7 @@ private:
     IEditor* const m_editor;
 
     // Tool name
-    string m_toolName;
+    AZStd::string m_toolName;
 
     // Context provider for the Asset Browser
     AZ::AssetBrowserContextProvider m_assetBrowserContextProvider;
diff --git a/Code/Editor/ResourceSelectorHost.cpp b/Code/Editor/ResourceSelectorHost.cpp
index d265b3ffbe..edab4be57c 100644
--- a/Code/Editor/ResourceSelectorHost.cpp
+++ b/Code/Editor/ResourceSelectorHost.cpp
@@ -101,10 +101,10 @@ public:
     }
 
 private:
-    typedef std::map > TTypeMap;
+    typedef std::map > TTypeMap;
     TTypeMap m_typeMap;
 
-    std::map m_globallySelectedResources;
+    std::map m_globallySelectedResources;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/Code/Editor/SelectSequenceDialog.cpp b/Code/Editor/SelectSequenceDialog.cpp
index 2566a8be82..11e30b91d7 100644
--- a/Code/Editor/SelectSequenceDialog.cpp
+++ b/Code/Editor/SelectSequenceDialog.cpp
@@ -37,7 +37,7 @@ CSelectSequenceDialog::GetItems(std::vector& outItems)
     {
         IAnimSequence* pSeq = pMovieSys->GetSequence(i);
         SItem item;
-        string fullname = pSeq->GetName();
+        AZStd::string fullname = pSeq->GetName();
         item.name = fullname.c_str();
         outItems.push_back(item);
     }
diff --git a/Code/Editor/ToolBox.cpp b/Code/Editor/ToolBox.cpp
index 77cb479873..0a1752a509 100644
--- a/Code/Editor/ToolBox.cpp
+++ b/Code/Editor/ToolBox.cpp
@@ -350,7 +350,7 @@ void CToolBoxManager::LoadShelves(QString scriptPath, QString shelvesPath, Actio
             continue;
         }
 
-        QString shelfName(PathUtil::GetFileName(files[idx].filename.toUtf8().data()));
+        QString shelfName(PathUtil::GetFileName(files[idx].filename.toUtf8().data()).c_str());
 
         AmazonToolbar toolbar(shelfName, shelfName);
         Load(shelvesPath + QString("/") + files[idx].filename, &toolbar, false, actionManager);
@@ -408,7 +408,7 @@ void CToolBoxManager::Load(QString xmlpath, AmazonToolbar* pToolbar, bool bToolb
     AZ::IO::FixedMaxPathString engineRoot = AZ::Utils::GetEnginePath();
     QDir engineDir = !engineRoot.empty() ? QDir(QString(engineRoot.c_str())) : QDir::current();
 
-    string enginePath = PathUtil::AddSlash(engineDir.absolutePath().toUtf8().data());
+    AZStd::string enginePath = PathUtil::AddSlash(engineDir.absolutePath().toUtf8().data());
 
     for (int i = 0; i < toolBoxNode->getChildCount(); ++i)
     {
@@ -434,11 +434,11 @@ void CToolBoxManager::Load(QString xmlpath, AmazonToolbar* pToolbar, bool bToolb
             continue;
         }
 
-        string shelfPath = PathUtil::GetParentDirectory(xmlpath.toUtf8().data());
-        string fullIconPath = enginePath + PathUtil::AddSlash(shelfPath.c_str());
+        AZStd::string shelfPath = PathUtil::GetParentDirectory(xmlpath.toUtf8().data());
+        AZStd::string fullIconPath = enginePath + PathUtil::AddSlash(shelfPath.c_str());
         fullIconPath.append(iconPath.toUtf8().data());
 
-        pMacro->SetIconPath(fullIconPath);
+        pMacro->SetIconPath(fullIconPath.c_str());
 
         QString toolTip(macroNode->getAttr("tooltip"));
         pMacro->action()->setToolTip(toolTip);
diff --git a/Code/Editor/TrackView/CommentKeyUIControls.cpp b/Code/Editor/TrackView/CommentKeyUIControls.cpp
index 4c5dc10bfa..91fa969e20 100644
--- a/Code/Editor/TrackView/CommentKeyUIControls.cpp
+++ b/Code/Editor/TrackView/CommentKeyUIControls.cpp
@@ -52,7 +52,7 @@ public:
         CFileUtil::ScanDirectory((Path::GetEditingGameDataFolder() + "/Fonts/").c_str(), "*.xml", fa, true);
         for (size_t i = 0; i < fa.size(); ++i)
         {
-            string name = fa[i].filename.toUtf8().data();
+            AZStd::string name = fa[i].filename.toUtf8().data();
             PathUtil::RemoveExtension(name);
             mv_font->AddEnumItem(name.c_str(), name.c_str());
         }
diff --git a/Code/Editor/TrackView/SequenceKeyUIControls.cpp b/Code/Editor/TrackView/SequenceKeyUIControls.cpp
index 5ef5a9c4ab..e280f06dc7 100644
--- a/Code/Editor/TrackView/SequenceKeyUIControls.cpp
+++ b/Code/Editor/TrackView/SequenceKeyUIControls.cpp
@@ -91,7 +91,7 @@ bool CSequenceKeyUIControls::OnKeySelectionChange(CTrackViewKeyBundle& selectedK
                 bool bNotParent = !bNotMe || pCurrentSequence->IsAncestorOf(pSequence) == false;
                 if (bNotMe && bNotParent)
                 {
-                    string seqName = pCurrentSequence->GetName();
+                    AZStd::string seqName = pCurrentSequence->GetName();
 
                     QString ownerIdString = CTrackViewDialog::GetEntityIdAsString(pCurrentSequence->GetSequenceComponentEntityId());
                     mv_sequence->AddEnumItem(seqName.c_str(), ownerIdString);
diff --git a/Code/Editor/TrackView/TrackViewAnimNode.cpp b/Code/Editor/TrackView/TrackViewAnimNode.cpp
index c66ea5635c..abff423ab7 100644
--- a/Code/Editor/TrackView/TrackViewAnimNode.cpp
+++ b/Code/Editor/TrackView/TrackViewAnimNode.cpp
@@ -1010,13 +1010,13 @@ bool CTrackViewAnimNode::SetName(const char* pName)
         }
     }
 
-    string oldName = GetName();
+    AZStd::string oldName = GetName();
     m_animNode->SetName(pName);
 
     CTrackViewSequence* sequence = GetSequence();
     AZ_Assert(sequence, "Nodes should never have a null sequence.");
 
-    sequence->OnNodeRenamed(this, oldName);
+    sequence->OnNodeRenamed(this, oldName.c_str());
 
     return true;
 }
diff --git a/Code/Editor/TrackView/TrackViewFindDlg.cpp b/Code/Editor/TrackView/TrackViewFindDlg.cpp
index 3d6e93fb05..18d574bf0b 100644
--- a/Code/Editor/TrackView/TrackViewFindDlg.cpp
+++ b/Code/Editor/TrackView/TrackViewFindDlg.cpp
@@ -61,7 +61,7 @@ void CTrackViewFindDlg::FillData()
             ObjName obj;
             obj.m_objName = pNode->GetName();
             obj.m_directorName = pNode->HasDirectorAsParent() ? pNode->HasDirectorAsParent()->GetName() : "";
-            string fullname = seq->GetName();
+            AZStd::string fullname = seq->GetName();
             obj.m_seqName = fullname.c_str();
             m_objs.push_back(obj);
         }
diff --git a/Code/Editor/TrackView/TrackViewNodes.cpp b/Code/Editor/TrackView/TrackViewNodes.cpp
index 90e5598876..000bdf21d0 100644
--- a/Code/Editor/TrackView/TrackViewNodes.cpp
+++ b/Code/Editor/TrackView/TrackViewNodes.cpp
@@ -2516,7 +2516,7 @@ int CTrackViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, cons
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)
diff --git a/Code/Editor/TrackView/TrackViewSequence.cpp b/Code/Editor/TrackView/TrackViewSequence.cpp
index 7ccecd7292..3647c554dc 100644
--- a/Code/Editor/TrackView/TrackViewSequence.cpp
+++ b/Code/Editor/TrackView/TrackViewSequence.cpp
@@ -1073,7 +1073,7 @@ std::deque CTrackViewSequence::GetMatchingTracks(CTrackViewAni
 {
     std::deque matchingTracks;
 
-    const string trackName = trackNode->getAttr("name");
+    const AZStd::string trackName = trackNode->getAttr("name");
 
     CAnimParamType animParamType;
     animParamType.LoadFromXml(trackNode);
@@ -1133,11 +1133,11 @@ void CTrackViewSequence::GetMatchedPasteLocationsRec(std::vectorgetChild(nodeIndex);
-        const string tagName = xmlChildNode->getTag();
+        const AZStd::string tagName = xmlChildNode->getTag();
 
         if (tagName == "Node")
         {
-            const string nodeName = xmlChildNode->getAttr("name");
+            const AZStd::string nodeName = xmlChildNode->getAttr("name");
 
             int nodeType = static_cast(AnimNodeType::Invalid);
             xmlChildNode->getAttr("type", nodeType);
@@ -1159,7 +1159,7 @@ void CTrackViewSequence::GetMatchedPasteLocationsRec(std::vectorgetAttr("name");
+            const AZStd::string trackName = xmlChildNode->getAttr("name");
 
             CAnimParamType trackParamType;
             trackParamType.Serialize(xmlChildNode, true);
diff --git a/Code/Editor/TrackViewNewSequenceDialog.cpp b/Code/Editor/TrackViewNewSequenceDialog.cpp
index 30691b0215..0efc7a932e 100644
--- a/Code/Editor/TrackViewNewSequenceDialog.cpp
+++ b/Code/Editor/TrackViewNewSequenceDialog.cpp
@@ -81,7 +81,7 @@ void CTVNewSequenceDialog::OnOK()
     for (int k = 0; k < GetIEditor()->GetSequenceManager()->GetCount(); ++k)
     {
         CTrackViewSequence* pSequence = GetIEditor()->GetSequenceManager()->GetSequenceByIndex(k);
-        QString fullname = QtUtil::ToQString(pSequence->GetName());
+        QString fullname = pSequence->GetName();
 
         if (fullname.compare(m_sequenceName, Qt::CaseInsensitive) == 0)
         {
diff --git a/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp b/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp
index f5ba0c507d..a14303cd69 100644
--- a/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp
+++ b/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp
@@ -45,7 +45,7 @@ int CAutoDirectoryRestoreFileDialog::exec()
         foreach(const QString&fileName, selectedFiles())
         {
             QFileInfo info(fileName);
-            if (!CryStringUtils::IsValidFileName(info.fileName().toStdString().c_str()))
+            if (!AZ::StringFunc::Path::IsValid(info.fileName().toStdString().c_str()))
             {
                 QMessageBox::warning(this, tr("Error"), tr("Please select a valid file name (standard English alphanumeric characters only)"));
                 problem = true;
diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp
index d57d690154..f5535f5590 100644
--- a/Code/Editor/Util/FileUtil.cpp
+++ b/Code/Editor/Util/FileUtil.cpp
@@ -264,7 +264,7 @@ void CFileUtil::EditTextureFile(const char* textureFile, [[maybe_unused]] bool b
     }
 
     bool failedToLaunch = true;
-    QByteArray textureEditorPath = gSettings.textureEditor.toUtf8();
+    const QString& textureEditorPath = gSettings.textureEditor;
 
     // Give the user a warning if they don't have a texture editor configured
     if (textureEditorPath.isEmpty())
@@ -278,8 +278,7 @@ void CFileUtil::EditTextureFile(const char* textureFile, [[maybe_unused]] bool b
     // Use the Win32 API calls to open the right editor; the OS knows how to do this even better than
     // Qt does.
     QString fullTexturePathFixedForWindows = QString(fullTexturePath.data()).replace('/', '\\');
-    QByteArray fullTexturePathFixedForWindowsUtf8 = fullTexturePathFixedForWindows.toUtf8();
-    HINSTANCE hInst = ShellExecute(NULL, "open", textureEditorPath.data(), fullTexturePathFixedForWindowsUtf8.data(), NULL, SW_SHOWNORMAL);
+    HINSTANCE hInst = ShellExecuteW(NULL, L"open", textureEditorPath.toStdWString().c_str(), fullTexturePathFixedForWindows.toStdWString().c_str(), NULL, SW_SHOWNORMAL);
     failedToLaunch = ((DWORD_PTR)hInst <= 32);
 #elif defined(AZ_PLATFORM_MAC)
     failedToLaunch = QProcess::execute(QString("/usr/bin/open"), {"-a", gSettings.textureEditor, QString(fullTexturePath.data()) }) != 0;
@@ -298,7 +297,7 @@ void CFileUtil::EditTextureFile(const char* textureFile, [[maybe_unused]] bool b
 //////////////////////////////////////////////////////////////////////////
 bool CFileUtil::EditMayaFile(const char* filepath, const bool bExtractFromPak, const bool bUseGameFolder)
 {
-    QString dosFilepath = QtUtil::ToQString(PathUtil::ToDosPath(filepath));
+    QString dosFilepath = PathUtil::ToDosPath(filepath).c_str();
     if (bExtractFromPak)
     {
         ExtractFile(dosFilepath);
@@ -313,7 +312,7 @@ bool CFileUtil::EditMayaFile(const char* filepath, const bool bExtractFromPak, c
             dosFilepath = sGameFolder + '\\' + filepath;
         }
 
-        dosFilepath = PathUtil::ToDosPath(dosFilepath.toUtf8().data());
+        dosFilepath = PathUtil::ToDosPath(dosFilepath.toUtf8().data()).c_str();
     }
 
     const char* engineRoot;
@@ -1304,7 +1303,7 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory
     // all with the same names and all with the same files names inside. If you would make a depth-first search
     // you could end up with the files from the deepest folder in ALL your folders.
 
-    std::vector ignoredPatterns;
+    std::vector ignoredPatterns;
     StringHelpers::Split(ignoreFilesAndFolders, "|", false, ignoredPatterns);
 
     QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags;
@@ -2218,7 +2217,9 @@ uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*=
         return SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK;
     }
 
-    DWORD dwAttrib = ::GetFileAttributes(file.GetAdjustedFilename());
+    AZStd::wstring fileW;
+    AZStd::to_wstring(fileW, file.GetAdjustedFilename());
+    DWORD dwAttrib = ::GetFileAttributesW(fileW.c_str());
     if (dwAttrib == INVALID_FILE_ATTRIBUTES)
     {
         return SCC_FILE_ATTRIBUTE_INVALID;
diff --git a/Code/Editor/Util/ImageASC.cpp b/Code/Editor/Util/ImageASC.cpp
index 69a6892c65..e6e947f342 100644
--- a/Code/Editor/Util/ImageASC.cpp
+++ b/Code/Editor/Util/ImageASC.cpp
@@ -24,8 +24,7 @@ bool CImageASC::Save(const QString& fileName, const CFloatImage& image)
     uint32 height = image.GetHeight();
     float* pixels = image.GetData();
 
-    string fileHeader;
-    fileHeader.Format(
+    AZStd::string fileHeader = AZStd::string::format(
         // Number of columns and rows in the data
         "ncols %d\n"
         "nrows %d\n"
diff --git a/Code/Editor/Util/ImageTIF.cpp b/Code/Editor/Util/ImageTIF.cpp
index 9040306a44..7029609825 100644
--- a/Code/Editor/Util/ImageTIF.cpp
+++ b/Code/Editor/Util/ImageTIF.cpp
@@ -399,8 +399,8 @@ bool CImageTIF::SaveRAW(const QString& fileName, const void* pData, int width, i
 
         if (preset && preset[0])
         {
-            string tiffphotoshopdata, valueheader;
-            string presetkeyvalue = string("/preset=") + string(preset);
+            AZStd::string tiffphotoshopdata, valueheader;
+            AZStd::string presetkeyvalue = AZStd::string("/preset=") + AZStd::string(preset);
 
             valueheader.push_back('\x1C');
             valueheader.push_back('\x02');
@@ -472,7 +472,7 @@ const char* CImageTIF::GetPreset(const QString& fileName)
             libtiffDummyWriteProc, libtiffDummySeekProc,
             libtiffDummyCloseProc, libtiffDummySizeProc, libtiffDummyMapFileProc, libtiffDummyUnmapFileProc);
 
-    string strReturn;
+    AZStd::string strReturn;
     char* preset = NULL;
     int size;
     if (tif)
diff --git a/Code/Editor/Util/ImageUtil.cpp b/Code/Editor/Util/ImageUtil.cpp
index 1b985c82f9..3ac15495cc 100644
--- a/Code/Editor/Util/ImageUtil.cpp
+++ b/Code/Editor/Util/ImageUtil.cpp
@@ -86,8 +86,7 @@ bool CImageUtil::SavePGM(const QString& fileName, const CImageEx& image)
     uint32* pixels = image.GetData();
 
     // Create the file header.
-    string fileHeader;
-    fileHeader.Format(
+    AZStd::string fileHeader = AZStd::string::format(
         // P2 = PGM header for ASCII output.  (P5 is PGM header for binary output)
         "P2\n"
         // width and height of the image
diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp
index bf607e475e..a1e2b4ae08 100644
--- a/Code/Editor/Util/StringHelpers.cpp
+++ b/Code/Editor/Util/StringHelpers.cpp
@@ -7,117 +7,10 @@
  */
 
 
-#include 
 #include "StringHelpers.h"
 #include "Util.h"
-#include "StringUtils.h" // From CryCommon
-#include "UnicodeFunctions.h"
-#include 
-#include 
-
-#include  // WideCharToMultibyte(), CP_UTF8, etc.
-#include 
-
-static inline char ToLower(const char c)
-{
-    return tolower(c);
-}
-
-static inline wchar_t ToLower(const wchar_t c)
-{
-    return towlower(c);
-}
-
-
-static inline char ToUpper(const char c)
-{
-    return toupper(c);
-}
-
-static inline wchar_t ToUpper(const wchar_t c)
-{
-    return towupper(c);
-}
-
-
-static inline int Vscprintf(const char* format, va_list argList)
-{
-#if defined(AZ_PLATFORM_WINDOWS)
-    return _vscprintf(format, argList);
-#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX)
-    int retval;
-    va_list argcopy;
-    va_copy(argcopy, argList);
-    retval = azvsnprintf(NULL, 0, format, argcopy);
-    va_end(argcopy);
-    return retval;
-#else
-    #error Not supported!
-#endif
-}
-
-static inline int Vscprintf(const wchar_t* format, va_list argList)
-{
-#if defined(AZ_PLATFORM_WINDOWS)
-    return _vscwprintf(format, argList);
-#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX)
-    int retval;
-    va_list argcopy;
-    va_copy(argcopy, argList);
-    retval = azvsnwprintf(NULL, 0, format, argcopy);
-    va_end(argcopy);
-    return retval;
-#else
-    #error Not supported!
-#endif
-}
-
-
-static inline int Vsnprintf_s(char* str, size_t sizeInBytes, [[maybe_unused]] size_t count, const char* format, va_list argList)
-{
-    return azvsnprintf(str, sizeInBytes, format, argList);
-}
-
-static inline int Vsnprintf_s(wchar_t* str, size_t sizeInBytes, [[maybe_unused]] size_t count, const wchar_t* format, va_list argList)
-{
-    return azvsnwprintf(str, sizeInBytes, format, argList);
-}
-
-
-int StringHelpers::Compare(const AZStd::string& str0, const AZStd::string& str1)
-{
-    const size_t minLength = Util::getMin(str0.length(), str1.length());
-    const int result = std::memcmp(str0.c_str(), str1.c_str(), minLength);
-    if (result)
-    {
-        return result;
-    }
-    else
-    {
-        return (str0.length() == str1.length())
-               ? 0
-               : ((str0.length() < str1.length()) ? -1 : +1);
-    }
-}
-
-int StringHelpers::Compare(const wstring& str0, const wstring& str1)
-{
-    const size_t minLength = Util::getMin(str0.length(), str1.length());
-    for (size_t i = 0; i < minLength; ++i)
-    {
-        const wchar_t c0 = str0[i];
-        const wchar_t c1 = str1[i];
-        if (c0 != c1)
-        {
-            return (c0 < c1) ? -1 : 1;
-        }
-    }
-
-    return (str0.length() == str1.length())
-           ? 0
-           : ((str0.length() < str1.length()) ? -1 : +1);
-}
 
+#include 
 
 int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
 {
@@ -135,7 +28,7 @@ int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::str
     }
 }
 
-int StringHelpers::CompareIgnoreCase(const wstring& str0, const wstring& str1)
+int StringHelpers::CompareIgnoreCase(const AZStd::wstring& str0, const AZStd::wstring& str1)
 {
     const size_t minLength = Util::getMin(str0.length(), str1.length());
     for (size_t i = 0; i < minLength; ++i)
@@ -153,402 +46,6 @@ int StringHelpers::CompareIgnoreCase(const wstring& str0, const wstring& str1)
            : ((str0.length() < str1.length()) ? -1 : +1);
 }
 
-
-bool StringHelpers::Equals(const AZStd::string& str0, const AZStd::string& str1)
-{
-    if (str0.length() != str1.length())
-    {
-        return false;
-    }
-    return std::memcmp(str0.c_str(), str1.c_str(), str1.length()) == 0;
-}
-
-bool StringHelpers::Equals(const wstring& str0, const wstring& str1)
-{
-    if (str0.length() != str1.length())
-    {
-        return false;
-    }
-    return std::memcmp(str0.c_str(), str1.c_str(), str1.length() * sizeof(wstring::value_type)) == 0;
-}
-
-
-bool StringHelpers::EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
-{
-    if (str0.length() != str1.length())
-    {
-        return false;
-    }
-    return azmemicmp(str0.c_str(), str1.c_str(), str1.length()) == 0;
-}
-
-bool StringHelpers::EqualsIgnoreCase(const wstring& str0, const wstring& str1)
-{
-    const size_t str1Length = str1.length();
-    if (str0.length() != str1Length)
-    {
-        return false;
-    }
-    for (size_t i = 0; i < str1Length; ++i)
-    {
-        if (towlower(str0[i]) != towlower(str1[i]))
-        {
-            return false;
-        }
-    }
-    return true;
-}
-
-
-bool StringHelpers::StartsWith(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::StartsWith(const wstring& str, const wstring& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str(), pattern.c_str(), pattern.length() * sizeof(wstring::value_type)) == 0;
-}
-
-
-bool StringHelpers::StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return azmemicmp(str.c_str(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::StartsWithIgnoreCase(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    for (size_t i = 0; i < patternLength; ++i)
-    {
-        if (towlower(str[i]) != towlower(pattern[i]))
-        {
-            return false;
-        }
-    }
-    return true;
-}
-
-
-bool StringHelpers::EndsWith(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str() + str.length() - pattern.length(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::EndsWith(const wstring& str, const wstring& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str() + str.length() - pattern.length(), pattern.c_str(), pattern.length() * sizeof(wstring::value_type)) == 0;
-}
-
-
-bool StringHelpers::EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return azmemicmp(str.c_str() + str.length() - pattern.length(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::EndsWithIgnoreCase(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    for (size_t i = str.length() - patternLength, j = 0; i < patternLength; ++i, ++j)
-    {
-        if (towlower(str[i]) != towlower(pattern[j]))
-        {
-            return false;
-        }
-    }
-    return true;
-}
-
-
-bool StringHelpers::Contains(const AZStd::string& str, const AZStd::string& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        if (std::memcmp(str.c_str() + i, pattern.c_str(), patternLength) == 0)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-bool StringHelpers::Contains(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        if (std::memcmp(str.c_str() + i, pattern.c_str(), patternLength * sizeof(wstring::value_type)) == 0)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-
-bool StringHelpers::ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        if (azmemicmp(str.c_str() + i, pattern.c_str(), patternLength) == 0)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-bool StringHelpers::ContainsIgnoreCase(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (patternLength == 0)
-    {
-        return true;
-    }
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-
-    const wstring::value_type firstPatternLetter = towlower(pattern[0]);
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        bool match = true;
-        for (size_t j = 0; j < patternLength; ++j)
-        {
-            if (towlower(str[i + j]) != towlower(pattern[j]))
-            {
-                match = false;
-                break;
-            }
-        }
-        if (match)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-string StringHelpers::TrimLeft(const AZStd::string& s)
-{
-    const size_t first = s.find_first_not_of(" \r\t");
-    return (first == s.npos) ? string() : s.substr(first);
-}
-
-wstring StringHelpers::TrimLeft(const wstring& s)
-{
-    const size_t first = s.find_first_not_of(L" \r\t");
-    return (first == s.npos) ? wstring() : s.substr(first);
-}
-
-
-string StringHelpers::TrimRight(const AZStd::string& s)
-{
-    const size_t last = s.find_last_not_of(" \r\t");
-    return (last == s.npos) ? s : s.substr(0, last + 1);
-}
-
-wstring StringHelpers::TrimRight(const wstring& s)
-{
-    const size_t last = s.find_last_not_of(L" \r\t");
-    return (last == s.npos) ? s : s.substr(0, last + 1);
-}
-
-
-string StringHelpers::Trim(const AZStd::string& s)
-{
-    return TrimLeft(TrimRight(s));
-}
-
-wstring StringHelpers::Trim(const wstring& s)
-{
-    return TrimLeft(TrimRight(s));
-}
-
-
-template 
-static inline TS RemoveDuplicateSpaces_Tpl(const TS& s)
-{
-    TS res;
-    bool spaceFound = false;
-
-    for (size_t i = 0, n = s.length(); i < n; ++i)
-    {
-        if ((s[i] == ' ') || (s[i] == '\r') || (s[i] == '\t'))
-        {
-            spaceFound = true;
-        }
-        else
-        {
-            if (spaceFound)
-            {
-                res += ' ';
-                spaceFound = false;
-            }
-            res += s[i];
-        }
-    }
-
-    if (spaceFound)
-    {
-        res += ' ';
-    }
-    return res;
-}
-
-string StringHelpers::RemoveDuplicateSpaces(const AZStd::string& s)
-{
-    return RemoveDuplicateSpaces_Tpl(s);
-}
-
-wstring StringHelpers::RemoveDuplicateSpaces(const wstring& s)
-{
-    return RemoveDuplicateSpaces_Tpl(s);
-}
-
-
-template 
-static inline TS MakeLowerCase_Tpl(const TS& s)
-{
-    TS copy;
-    copy.reserve(s.length());
-    for (typename TS::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
-    {
-        copy.append(1, ToLower(*it));
-    }
-    return copy;
-}
-
-string StringHelpers::MakeLowerCase(const AZStd::string& s)
-{
-    return MakeLowerCase_Tpl(s);
-}
-
-wstring StringHelpers::MakeLowerCase(const wstring& s)
-{
-    return MakeLowerCase_Tpl(s);
-}
-
-
-template 
-static inline TS MakeUpperCase_Tpl(const TS& s)
-{
-    TS copy;
-    copy.reserve(s.length());
-    for (typename TS::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
-    {
-        copy.append(1, ToUpper(*it));
-    }
-    return copy;
-}
-
-string StringHelpers::MakeUpperCase(const AZStd::string& s)
-{
-    return MakeUpperCase_Tpl(s);
-}
-
-wstring StringHelpers::MakeUpperCase(const wstring& s)
-{
-    return MakeUpperCase_Tpl(s);
-}
-
-
-template 
-static inline TS Replace_Tpl(const TS& s, const typename TS::value_type oldChar, const typename TS::value_type newChar)
-{
-    TS copy;
-    copy.reserve(s.length());
-    for (typename TS::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
-    {
-        const typename TS::value_type c = (*it);
-        copy.append(1, ((c == oldChar) ? newChar : c));
-    }
-    return copy;
-}
-
-string StringHelpers::Replace(const AZStd::string& s, char oldChar, char newChar)
-{
-    return Replace_Tpl(s, oldChar, newChar);
-}
-
-wstring StringHelpers::Replace(const wstring& s, wchar_t oldChar, wchar_t newChar)
-{
-    return Replace_Tpl(s, oldChar, newChar);
-}
-
-
-void StringHelpers::ConvertStringByRef(string& out, const AZStd::string& in)
-{
-    out = in;
-}
-
-void StringHelpers::ConvertStringByRef(wstring& out, const AZStd::string& in)
-{
-    Unicode::Convert(out, in);
-}
-
-void StringHelpers::ConvertStringByRef(string& out, const wstring& in)
-{
-    Unicode::Convert(out, in);
-}
-
-void StringHelpers::ConvertStringByRef(wstring& out, const wstring& in)
-{
-    out = in;
-}
-
-
 template 
 static inline void Split_Tpl(const TS& str, const TS& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
@@ -588,348 +85,12 @@ static inline void Split_Tpl(const TS& str, const TS& separator, bool bReturnEmp
     }
 }
 
-
-template 
-static inline void SplitByAnyOf_Tpl(const TS& str, const TS& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
-{
-    if (str.empty())
-    {
-        return;
-    }
-
-    if (separators.empty())
-    {
-        for (size_t i = 0; i < str.length(); ++i)
-        {
-            outParts.push_back(str.substr(i, 1));
-        }
-        return;
-    }
-
-    size_t partStart = 0;
-
-    for (;; )
-    {
-        const size_t pos = str.find_first_of(separators, partStart);
-        if (pos == TS::npos)
-        {
-            break;
-        }
-        if (bReturnEmptyPartsToo || (pos > partStart))
-        {
-            outParts.push_back(str.substr(partStart, pos - partStart));
-        }
-        partStart = pos + 1;
-    }
-
-    if (bReturnEmptyPartsToo || (partStart < str.length()))
-    {
-        outParts.push_back(str.substr(partStart, str.length() - partStart));
-    }
-}
-
-
-
-void StringHelpers::Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
 }
 
-void StringHelpers::Split(const wstring& str, const wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::Split(const AZStd::wstring& str, const AZStd::wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
 }
-
-
-void StringHelpers::SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
-{
-    SplitByAnyOf_Tpl(str, separators, bReturnEmptyPartsToo, outParts);
-}
-
-void StringHelpers::SplitByAnyOf(const wstring& str, const wstring& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
-{
-    SplitByAnyOf_Tpl(str, separators, bReturnEmptyPartsToo, outParts);
-}
-
-
-template 
-static inline TS FormatVA_Tpl(const typename TS::value_type* const format, va_list parg)
-{
-    if ((format == 0) || (format[0] == 0))
-    {
-        return TS();
-    }
-
-    std::vector bf;
-    size_t capacity = 0;
-
-    size_t wantedCapacity = Vscprintf(format, parg);
-    wantedCapacity += 2;  // '+ 2' to prevent uncertainty when Vsnprintf_s() returns 'size - 1'
-
-    for (;; )
-    {
-        if (wantedCapacity > capacity)
-        {
-            capacity = wantedCapacity;
-            bf.resize(capacity + 1);
-        }
-
-        const int countWritten = Vsnprintf_s(&bf[0], capacity + 1, _TRUNCATE, format, parg);
-
-        if ((countWritten >= 0) && (capacity > (size_t)countWritten + 1))
-        {
-            bf[countWritten] = 0;
-            return TS(&bf[0]);
-        }
-
-        wantedCapacity = capacity * 2;
-    }
-}
-
-string StringHelpers::FormatVA(const char* const format, va_list parg)
-{
-    return FormatVA_Tpl(format, parg);
-}
-
-wstring StringHelpers::FormatVA(const wchar_t* const format, va_list parg)
-{
-    return FormatVA_Tpl(format, parg);
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-template 
-static inline void SafeCopy_Tpl(TC* const pDstBuffer, const size_t dstBufferSizeInBytes, const TC* const pSrc)
-{
-    if (dstBufferSizeInBytes >= sizeof(TC))
-    {
-        const size_t n = dstBufferSizeInBytes / sizeof(TC) - 1;
-        size_t i;
-        for (i = 0; i < n && pSrc[i]; ++i)
-        {
-            pDstBuffer[i] = pSrc[i];
-        }
-        pDstBuffer[i] = 0;
-    }
-}
-
-template 
-static inline void SafeCopyPadZeros_Tpl(TC* const pDstBuffer, const size_t dstBufferSizeInBytes, const TC* const pSrc)
-{
-    if (dstBufferSizeInBytes > 0)
-    {
-        const size_t n = (dstBufferSizeInBytes < sizeof(TC)) ? 0 : dstBufferSizeInBytes / sizeof(TC) - 1;
-        size_t i;
-        for (i = 0; i < n && pSrc[i]; ++i)
-        {
-            pDstBuffer[i] = pSrc[i];
-        }
-        memset(&pDstBuffer[i], 0, dstBufferSizeInBytes - i * sizeof(TC));
-    }
-}
-
-
-void StringHelpers::SafeCopy(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc)
-{
-    SafeCopy_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-void StringHelpers::SafeCopy(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc)
-{
-    SafeCopy_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-
-void StringHelpers::SafeCopyPadZeros(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc)
-{
-    SafeCopyPadZeros_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-void StringHelpers::SafeCopyPadZeros(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc)
-{
-    SafeCopyPadZeros_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-bool StringHelpers::Utf16ContainsAsciiOnly(const wchar_t* wstr)
-{
-    while (*wstr)
-    {
-        if (*wstr > 127 || *wstr < 0)
-        {
-            return false;
-        }
-        ++wstr;
-    }
-    return true;
-}
-
-
-string StringHelpers::ConvertAsciiUtf16ToAscii(const wchar_t* wstr)
-{
-    const size_t len = wcslen(wstr);
-
-    string result;
-    result.reserve(len);
-
-    for (size_t i = 0; i < len; ++i)
-    {
-        result.push_back(wstr[i] & 0x7F);
-    }
-
-    return result;
-}
-
-
-wstring StringHelpers::ConvertAsciiToUtf16(const char* str)
-{
-    const size_t len = strlen(str);
-
-    wstring result;
-    result.reserve(len);
-
-    for (size_t i = 0; i < len; ++i)
-    {
-        result.push_back(str[i] & 0x7F);
-    }
-
-    return result;
-}
-
-#if defined(AZ_PLATFORM_WINDOWS)
-static string ConvertUtf16ToMultibyte(const wchar_t* wstr, uint codePage, char badChar)
-{
-    if (wstr[0] == 0)
-    {
-        return string();
-    }
-
-    const int len = aznumeric_caster(wcslen(wstr));
-
-    // Request needed buffer size, in bytes
-    int neededByteCount = WideCharToMultiByte(
-            codePage,
-            0,
-            wstr,
-            len,
-            0,
-            0,
-            ((badChar && codePage != CP_UTF8) ? &badChar : NULL),
-            NULL);
-    if (neededByteCount <= 0)
-    {
-        return string();
-    }
-    ++neededByteCount; // extra space for terminating zero
-
-    std::vector buffer(neededByteCount);
-
-    const int byteCount = WideCharToMultiByte(
-            codePage,
-            0,
-            wstr,
-            len,
-            &buffer[0], // output buffer
-            neededByteCount - 1, // size of the output buffer in bytes
-            ((badChar && codePage != CP_UTF8) ? &badChar : NULL),
-            NULL);
-    if (byteCount != neededByteCount - 1)
-    {
-        return string();
-    }
-
-    buffer[byteCount] = 0;
-
-    return string(&buffer[0]);
-}
-
-
-static wstring ConvertMultibyteToUtf16(const char* str, uint codePage)
-{
-    if (str[0] == 0)
-    {
-        return wstring();
-    }
-
-    const int len = aznumeric_caster(strlen(str));
-
-    // Request needed buffer size, in characters
-    int neededCharCount = MultiByteToWideChar(
-            codePage,
-            0,
-            str,
-            len,
-            0,
-            0);
-    if (neededCharCount <= 0)
-    {
-        return wstring();
-    }
-    ++neededCharCount; // extra space for terminating zero
-
-    std::vector wbuffer(neededCharCount);
-
-    const int charCount = MultiByteToWideChar(
-            codePage,
-            0,
-            str,
-            len,
-            &wbuffer[0], // output buffer
-            neededCharCount - 1); // size of the output buffer in characters
-    if (charCount != neededCharCount - 1)
-    {
-        return wstring();
-    }
-
-    wbuffer[charCount] = 0;
-
-    return wstring(&wbuffer[0]);
-}
-
-
-wstring StringHelpers::ConvertUtf8ToUtf16(const char* str)
-{
-    return ConvertMultibyteToUtf16(str, CP_UTF8);
-}
-
-
-string StringHelpers::ConvertUtf16ToUtf8(const wchar_t* wstr)
-{
-    return ConvertUtf16ToMultibyte(wstr, CP_UTF8, 0);
-}
-
-
-wstring StringHelpers::ConvertAnsiToUtf16(const char* str)
-{
-    return ConvertMultibyteToUtf16(str, CP_ACP);
-}
-
-
-string StringHelpers::ConvertUtf16ToAnsi(const wchar_t* wstr, char badChar)
-{
-    return ConvertUtf16ToMultibyte(wstr, CP_ACP, badChar);
-}
-#endif  //AZ_PLATFORM_WINDOWS
-
-string StringHelpers::ConvertAnsiToAscii(const char* str, char badChar)
-{
-    const size_t len = strlen(str);
-
-    string result;
-    result.reserve(len);
-
-    for (size_t i = 0; i < len; ++i)
-    {
-        char c = str[i];
-        if (c < 0 || c > 127)
-        {
-            c = badChar;
-        }
-        result.push_back(c);
-    }
-
-    return result;
-}
-
-// eof
diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h
index ec5515fbc9..0e393e92dd 100644
--- a/Code/Editor/Util/StringHelpers.h
+++ b/Code/Editor/Util/StringHelpers.h
@@ -13,193 +13,13 @@
 
 namespace StringHelpers
 {
-    // compares two strings to see if they are the same or different, case sensitive
-    // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
-    int Compare(const AZStd::string& str0, const AZStd::string& str1);
-    int Compare(const wstring& str0, const wstring& str1);
-
     // compares two strings to see if they are the same or different, case is ignored
     // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
     int CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
-    int CompareIgnoreCase(const wstring& str0, const wstring& str1);
-
-    // compares two strings to see if they are the same, case senstive
-    // returns true if they are the same or false if they are different
-    bool Equals(const AZStd::string& str0, const AZStd::string& str1);
-    bool Equals(const wstring& str0, const wstring& str1);
-
-    // compares two strings to see if they are the same, case is ignored
-    // returns true if they are the same or false if they are different
-    bool EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
-    bool EqualsIgnoreCase(const wstring& str0, const wstring& str1);
-
-    // checks to see if a string starts with a specified string, case sensitive
-    // returns true if the string does start with a specified string or false if it does not
-    bool StartsWith(const AZStd::string& str, const AZStd::string& pattern);
-    bool StartsWith(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string starts with a specified string, case is ignored
-    // returns true if the string does start with a specified string or false if it does not
-    bool StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
-    bool StartsWithIgnoreCase(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string ends with a specified string, case sensitive
-    // returns true if the string does end with a specified string or false if it does not
-    bool EndsWith(const AZStd::string& str, const AZStd::string& pattern);
-    bool EndsWith(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string ends with a specified string, case is ignored
-    // returns true if the string does end with a specified string or false if it does not
-    bool EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
-    bool EndsWithIgnoreCase(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string contains a specified string, case sensitive
-    // returns true if the string does contain the specified string or false if it does not
-    bool Contains(const AZStd::string& str, const AZStd::string& pattern);
-    bool Contains(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string contains a specified string, case is ignored
-    // returns true if the string does contain the specified string or false if it does not
-    bool ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
-    bool ContainsIgnoreCase(const wstring& str, const wstring& pattern);
-
-    string TrimLeft(const AZStd::string& s);
-    wstring TrimLeft(const wstring& s);
-
-    string TrimRight(const AZStd::string& s);
-    wstring TrimRight(const wstring& s);
-
-    string Trim(const AZStd::string& s);
-    wstring Trim(const wstring& s);
-
-    string RemoveDuplicateSpaces(const AZStd::string& s);
-    wstring RemoveDuplicateSpaces(const wstring& s);
-
-    // converts a string with upper case characters to be all lower case
-    // returns the string in all lower case
-    string MakeLowerCase(const AZStd::string& s);
-    wstring MakeLowerCase(const wstring& s);
-
-    // converts a string with lower case characters to be all upper case
-    // returns the string in all upper case
-    string MakeUpperCase(const AZStd::string& s);
-    wstring MakeUpperCase(const wstring& s);
-
-    // replace a specified character in a string with a specified replacement character
-    // returns string with specified character replaced
-    string Replace(const AZStd::string& s, char oldChar, char newChar);
-    wstring Replace(const wstring& s, wchar_t oldChar, wchar_t newChar);
-
-    void ConvertStringByRef(string& out, const AZStd::string& in);
-    void ConvertStringByRef(wstring& out, const AZStd::string& in);
-    void ConvertStringByRef(string& out, const wstring& in);
-    void ConvertStringByRef(wstring& out, const wstring& in);
-
-    template 
-    O ConvertString(const I& in)
-    {
-        O out;
-        ConvertStringByRef(out, in);
-        return out;
-    }
-    
-    void Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
-    void Split(const wstring& str, const wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
-
-    void SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
-    void SplitByAnyOf(const wstring& str, const wstring& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
-
-    string FormatVA(const char* const format, va_list parg);
-    wstring FormatVA(const wchar_t* const format, va_list parg);
-
-    inline string Format(const char* const format, ...)
-    {
-        if ((format == 0) || (format[0] == 0))
-        {
-            return string();
-        }
-        va_list parg;
-        va_start(parg, format);
-        const string result = FormatVA(format, parg);
-        va_end(parg);
-        return result;
-    }
-
-    inline wstring Format(const wchar_t* const format, ...)
-    {
-        if ((format == 0) || (format[0] == 0))
-        {
-            return wstring();
-        }
-        va_list parg;
-        va_start(parg, format);
-        const wstring result = FormatVA(format, parg);
-        va_end(parg);
-        return result;
-    }
-
-    //////////////////////////////////////////////////////////////////////////
-
-    void SafeCopy(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc);
-    void SafeCopy(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc);
-
-    void SafeCopyPadZeros(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc);
-    void SafeCopyPadZeros(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc);
-
-    //////////////////////////////////////////////////////////////////////////
-
-    // ASCII
-    // ANSI (system default Windows ANSI code page)
-    // UTF-8
-    // UTF-16
-
-    // ASCII -> UTF-16
-
-    bool Utf16ContainsAsciiOnly(const wchar_t* wstr);
-    string ConvertAsciiUtf16ToAscii(const wchar_t* wstr);
-    wstring ConvertAsciiToUtf16(const char* str);
-
-    // UTF-8 <-> UTF-16
-#if defined(AZ_PLATFORM_WINDOWS)
-    wstring ConvertUtf8ToUtf16(const char* str);
-    string ConvertUtf16ToUtf8(const wchar_t* wstr);
-
-    inline string ConvertUtfToUtf8(const char* str)
-    {
-        return string(str);
-    }
-
-    inline string ConvertUtfToUtf8(const wchar_t* wstr)
-    {
-        return ConvertUtf16ToUtf8(wstr);
-    }
-
-    inline wstring ConvertUtfToUtf16(const char* str)
-    {
-        return ConvertUtf8ToUtf16(str);
-    }
-
-    inline wstring ConvertUtfToUtf16(const wchar_t* wstr)
-    {
-        return wstring(wstr);
-    }
-
-    // ANSI <-> UTF-8, UTF-16
-
-    wstring ConvertAnsiToUtf16(const char* str);
-    string ConvertUtf16ToAnsi(const wchar_t* wstr, char badChar);
-
-    inline string ConvertAnsiToUtf8(const char* str)
-    {
-        return ConvertUtf16ToUtf8(ConvertAnsiToUtf16(str).c_str());
-    }
-    inline string ConvertUtf8ToAnsi(const char* str, char badChar)
-    {
-        return ConvertUtf16ToAnsi(ConvertUtf8ToUtf16(str).c_str(), badChar);
-    }
-#endif
+    int CompareIgnoreCase(const AZStd::wstring& str0, const AZStd::wstring& str1);
+  
+    void Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
+    void Split(const AZStd::wstring& str, const AZStd::wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
 
-    // ANSI -> ASCII
-    string ConvertAnsiToAscii(const char* str, char badChar);
 }
 #endif // CRYINCLUDE_CRYCOMMONTOOLS_STRINGHELPERS_H
diff --git a/Code/Editor/Util/XmlHistoryManager.cpp b/Code/Editor/Util/XmlHistoryManager.cpp
index 5a1bc237bb..b642929af1 100644
--- a/Code/Editor/Util/XmlHistoryManager.cpp
+++ b/Code/Editor/Util/XmlHistoryManager.cpp
@@ -427,7 +427,7 @@ const AZStd::string& CXmlHistoryManager::GetVersionDesc(int number) const
         return it->second.HistoryDescription;
     }
 
-    static string undef("UNDEFINED");
+    static AZStd::string undef("UNDEFINED");
     return undef;
 }
 
@@ -493,7 +493,7 @@ void CXmlHistoryManager::SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const
     UnloadInt();
 
     TEventHandlerList eventHandler;
-    string undoDesc;
+    AZStd::string undoDesc;
 
     if (pGroup)
     {
@@ -534,7 +534,7 @@ void CXmlHistoryManager::SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const
                 }
             }
         }
-        undoDesc.Format("Changed View to \"%s\"", displayName ? displayName : "UNDEFINED");
+        undoDesc = AZStd::string::format("Changed View to \"%s\"", displayName ? displayName : "UNDEFINED");
     }
     else
     {
diff --git a/Code/Editor/Util/XmlHistoryManager.h b/Code/Editor/Util/XmlHistoryManager.h
index 12699536e5..176f0a8d83 100644
--- a/Code/Editor/Util/XmlHistoryManager.h
+++ b/Code/Editor/Util/XmlHistoryManager.h
@@ -161,7 +161,7 @@ private:
 
         const SXmlHistoryGroup* CurrGroup;
         TGroupIndexMap CurrUserIndex;
-        string HistoryDescription;
+        AZStd::string HistoryDescription;
         bool IsNullUndo;
         bool HistoryInvalidated;
         TXmlHistotyGroupPtrList ActiveGroups;
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index 0f67e4ffd9..252ab8137d 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -2907,14 +2907,13 @@ void CXConsole::Paste()
         Utf8::Unchecked::octet_iterator end(data.end());
         for (Utf8::Unchecked::octet_iterator it(data.begin()); it != end; ++it)
         {
-            const uint32 cp = *it;
+            const wchar_t cp = *it;
             if (cp != '\r')
             {
                 // Convert UCS code-point into UTF-8 string
                 AZStd::fixed_string<5> utf8_buf = {0};
-                size_t size = 5;
-                it.to_utf8_sequence(cp, utf8_buf.data(), size);
-                AddInputUTF8(utf8_buf);
+                AZStd::to_string(utf8_buf.data(), 5, &cp, 1);
+                AddInputUTF8(utf8_buf.c_str());
             }
         }
     }

From 2ed07c2a6ad3937cd53f97cce159111cfd87a961 Mon Sep 17 00:00:00 2001
From: Dayo Lawal 
Date: Mon, 2 Aug 2021 23:09:28 -0500
Subject: [PATCH 070/251] delete MEWindowsRequestBus

Signed-off-by: Dayo Lawal 
---
 .../Window/AtomToolsMainWindow.h              |  2 +-
 .../Window/AtomToolsMainWindowRequestBus.h    |  2 +-
 .../Window/MaterialEditorWindowRequestBus.h   | 64 -------------------
 3 files changed, 2 insertions(+), 66 deletions(-)
 delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h

diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
index edb8ff4322..6b02bd1c06 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h
@@ -23,7 +23,7 @@ namespace AtomToolsFramework
 {
     class AtomToolsMainWindow
         : public AzQtComponents::DockMainWindow
-        , protected AtomToolsFramework::AtomToolsMainWindowRequestBus::Handler
+        , protected AtomToolsMainWindowRequestBus::Handler
     {
     public:
         AtomToolsMainWindow(QWidget* parent = 0);
diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h
index fd98b3b68b..ee21554844 100644
--- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h
+++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h
@@ -48,7 +48,7 @@ namespace AtomToolsFramework
         //! 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) {};
 
diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h
deleted file mode 100644
index 6b62549684..0000000000
--- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h
+++ /dev/null
@@ -1,64 +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 
-
-class QWidget;
-
-namespace MaterialEditor
-{
-    //! MaterialEditorWindowRequestBus provides 
-    class MaterialEditorWindowRequests
-        : public AZ::EBusTraits
-    {
-    public:
-        static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single;
-        static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single;
-
-        //! Bring main window to foreground
-        virtual void ActivateWindow() = 0;
-
-        //! Add dockable widget in main window
-        //! @param name title of the dockable window
-        //! @param widget docked window content
-        //! @param area location of docked window corresponding to Qt::DockWidgetArea
-        //! @param orientation orientation of docked window corresponding to Qt::Orientation
-        virtual bool AddDockWidget(const AZStd::string& name, QWidget* widget, uint32_t area, uint32_t orientation) = 0;
-
-        //! Destroy dockable widget in main window
-        //! @param name title of the dockable window
-        virtual void RemoveDockWidget(const AZStd::string& name) = 0;
-
-        //! Show or hide dockable widget in main window
-        //! @param name title of the dockable window
-        virtual void SetDockWidgetVisible(const AZStd::string& name, bool visible) = 0;
-
-        //! Determine visibility of dockable widget in main window
-        //! @param name title of the dockable window
-        virtual bool IsDockWidgetVisible(const AZStd::string& name) const = 0;
-
-        //! 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.
-        //! (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;
-
-        //! 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;
-
-        //! Releases the viewport's render target resolution lock, allowing it to match the viewport widget again.
-        virtual void UnlockViewportRenderTargetSize() = 0;
-    };
-    using MaterialEditorWindowRequestBus = AZ::EBus;
-
-} // namespace MaterialEditor

From f9d5a4a93b661f77363e17b1b4b0b3625a317776 Mon Sep 17 00:00:00 2001
From: Benjamin Jillich 
Date: Tue, 3 Aug 2021 16:06:51 +0200
Subject: [PATCH 071/251] Ported MCommon::RenderUtil

* Removed collision mesh based AABB rendering.
* Ported to AZ::Aabb
* Reduced the number of triangles used for rendering default spheres for joints to improve rendering times.

Signed-off-by: Benjamin Jillich 
---
 .../EMotionFX/Rendering/Common/RenderUtil.cpp | 73 +++++++------------
 .../EMotionFX/Rendering/Common/RenderUtil.h   | 24 +++---
 2 files changed, 37 insertions(+), 60 deletions(-)

diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp
index 6301b0d7e3..36bce97f88 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp
@@ -198,7 +198,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,12 +238,12 @@ 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;
@@ -304,46 +304,29 @@ namespace MCommon
     {
         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);
     }
 
 
     // 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);
-            }
-        }
-
         // handle the node based AABB
         if (renderSettings.mNodeBasedAABB)
         {
             // 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.mNodeBasedColor);
             }
         }
 
@@ -351,26 +334,26 @@ namespace MCommon
         if (renderSettings.mMeshBasedAABB)
         {
             // 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.mMeshBasedColor);
             }
         }
 
         if (renderSettings.mStaticBasedAABB)
         {
             // 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.mStaticBasedColor);
             }
         }
 
@@ -1639,7 +1622,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 +1632,7 @@ namespace MCommon
                     corners[i] = intersectionPoint;
                 }
 
-                aabb.Encapsulate(corners[i]);
+                aabb.AddPoint(corners[i]);
             }
 
             // set the grid start and end values
@@ -1665,9 +1648,9 @@ 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();
@@ -1685,17 +1668,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;
diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h
index 8b1cd30b6c..5c5d7bbef8 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 
@@ -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.
@@ -152,11 +151,9 @@ namespace MCommon
 
             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. */
         };
 
@@ -168,7 +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);
+        void RenderAabbs(EMotionFX::ActorInstance* actorInstance, const AABBRenderSettings& renderSettings = AABBRenderSettings(), bool directlyRender = false);
 
         /**
          * Render OBB for all enabled nodes inside the actor instance.
@@ -615,7 +612,7 @@ 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
         {
@@ -722,7 +719,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 +732,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.
@@ -831,6 +828,3 @@ namespace MCommon
         static uint32                   mNumMaxTriangleVertices;    /**< The maximum capacity of the triangle vertex buffer */
     };
 } // namespace MCommon
-
-
-#endif

From aab8ab97065b53d874ad9ebbc9251da5ae1f3b2a Mon Sep 17 00:00:00 2001
From: Benjamin Jillich 
Date: Tue, 3 Aug 2021 17:04:26 +0200
Subject: [PATCH 072/251] Removed OBBs from Actor including the node infos

Signed-off-by: Benjamin Jillich 
---
 .../Pipeline/RCExt/Actor/ActorBuilder.cpp     |   2 +-
 .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 115 +-----------------
 Gems/EMotionFX/Code/EMotionFX/Source/Actor.h  |  74 +----------
 .../EMotionFX/Code/Tests/AnimGraphFixture.cpp |   2 +-
 .../Code/Tests/MorphTargetRuntimeTests.cpp    |   2 +-
 .../Code/Tests/UI/CanMorphManyShapes.cpp      |   2 +-
 6 files changed, 6 insertions(+), 191 deletions(-)

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/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp
index c55509e817..62bd8b32cb 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,11 +49,6 @@ namespace EMotionFX
 {
     AZ_CLASS_ALLOCATOR_IMPL(Actor, ActorAllocator, 0)
 
-    Actor::NodeInfo::NodeInfo()
-    {
-        mOBB.Init();
-    }
-
     Actor::LODLevel::LODLevel()
     {
     }
@@ -188,7 +182,6 @@ namespace EMotionFX
         result->mSkeleton = mSkeleton->Clone();
 
         // clone lod data
-        result->mNodeInfos = mNodeInfos;
         const uint32 numNodes = mSkeleton->GetNumNodes();
 
         const size_t numLodLevels = m_meshLodData.m_lodLevels.size();
@@ -998,18 +991,6 @@ namespace EMotionFX
         }
     }
 
-    // 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);
-        }
-    }
-
-
     // remove all node groups
     void Actor::RemoveAllNodeGroups()
     {
@@ -1353,9 +1334,8 @@ namespace EMotionFX
         }
     }
 
-
     // post init
-    void Actor::PostCreateInit(bool makeGeomLodsCompatibleWithSkeletalLODs, bool generateOBBs, bool convertUnitType)
+    void Actor::PostCreateInit(bool makeGeomLodsCompatibleWithSkeletalLODs, bool convertUnitType)
     {
         if (mThreadIndex == MCORE_INVALIDINDEX32)
         {
@@ -1388,11 +1368,6 @@ namespace EMotionFX
         mSkeleton->GetBindPose()->ForceUpdateFullModelSpacePose();
         mSkeleton->GetBindPose()->ZeroMorphWeights();
 
-        if (generateOBBs)
-        {
-            UpdateNodeBindPoseOBBs(0);
-        }
-
         if (!GetHasMirrorInfo())
         {
             AllocateNodeMirrorInfos();
@@ -1883,7 +1858,6 @@ namespace EMotionFX
     void Actor::SetNumNodes(uint32 numNodes)
     {
         mSkeleton->SetNumNodes(numNodes);
-        mNodeInfos.resize(numNodes);
 
         AZStd::vector& lodLevels = m_meshLodData.m_lodLevels;
         for (LODLevel& lodLevel : lodLevels)
@@ -1901,7 +1875,6 @@ namespace EMotionFX
         mSkeleton->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)
         {
@@ -1932,7 +1905,6 @@ namespace EMotionFX
     void Actor::RemoveNode(uint32 nr, bool delMem)
     {
         mSkeleton->RemoveNode(nr, delMem);
-        mNodeInfos.erase(mNodeInfos.begin() + nr);
 
         AZStd::vector& lodLevels = m_meshLodData.m_lodLevels;
         for (LODLevel& lodLevel : lodLevels)
@@ -1944,7 +1916,6 @@ namespace EMotionFX
     void Actor::DeleteAllNodes()
     {
         mSkeleton->RemoveAllNodes();
-        mNodeInfos.clear();
 
         AZStd::vector& lodLevels = m_meshLodData.m_lodLevels;
         for (LODLevel& lodLevel : lodLevels)
@@ -2263,82 +2234,6 @@ 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)
     {
@@ -2411,14 +2306,6 @@ namespace EMotionFX
             mInvBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed();
         }
 
-        // update node obbs
-        for (uint32 i = 0; i < numNodes; ++i)
-        {
-            MCore::OBB& box = GetNodeOBB(i);
-            box.SetExtents(box.GetExtents() * scaleFactor);
-            box.SetCenter(box.GetCenter() * scaleFactor);
-        }
-
         // update static aabb
         m_staticAabb.SetMin(m_staticAabb.GetMin() * scaleFactor);
         m_staticAabb.SetMax(m_staticAabb.GetMax() * scaleFactor);
diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h
index 53cbe7e05a..1c1173a9a2 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h
@@ -24,7 +24,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 
 // include required headers
@@ -564,17 +563,6 @@ namespace EMotionFX
          */
         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);
-
         /**
          * Get the number of node groups inside this actor object.
          * @result The number of node groups.
@@ -758,7 +746,7 @@ 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;
@@ -808,57 +796,6 @@ namespace EMotionFX
         bool CheckIfHasMorphDeformer(uint32 lodLevel, uint32 nodeIndex) const;
         bool CheckIfHasSkinningDeformer(uint32 lodLevel, uint32 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);
-
-        /**
-         * 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);
@@ -917,14 +854,6 @@ 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
         {
@@ -968,7 +897,6 @@ namespace EMotionFX
 
         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. */
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/MorphTargetRuntimeTests.cpp b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp
index 0f022b72ef..24afc7af47 100644
--- a/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp
+++ b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp
@@ -84,7 +84,7 @@ namespace EMotionFX
             // Without this call, the bind pose does not know about newly added
             // morph target (mMorphWeights.GetLength() == 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();
 
diff --git a/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp b/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp
index 978532505b..ba24c501ab 100644
--- a/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp
+++ b/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp
@@ -68,7 +68,7 @@ namespace EMotionFX
 
             // Without this call, the bind pose does not know about newly added morph target (mMorphWeights.GetLength() == 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();
 

From b335285e19aae79fb0535211ab2e4713f739f30a Mon Sep 17 00:00:00 2001
From: Benjamin Jillich 
Date: Tue, 3 Aug 2021 17:13:19 +0200
Subject: [PATCH 073/251] Removed OBB rendering helpers and color options (was
 already hidden from the UI)

Signed-off-by: Benjamin Jillich 
---
 .../EMotionFX/Rendering/Common/RenderUtil.cpp | 71 -------------------
 .../EMotionFX/Rendering/Common/RenderUtil.h   | 12 ----
 Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp |  1 -
 .../Source/RenderPlugin/RenderOptions.cpp     | 23 ------
 .../Source/RenderPlugin/RenderOptions.h       |  6 --
 .../Source/RenderPlugin/RenderPlugin.cpp      |  4 --
 .../RenderPlugin/RenderUpdateCallback.cpp     |  4 --
 .../Source/RenderPlugin/RenderViewWidget.cpp  |  3 -
 .../Source/RenderPlugin/RenderViewWidget.h    |  1 -
 9 files changed, 125 deletions(-)

diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp
index 36bce97f88..8464cb2b2a 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp
@@ -403,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)
     {
diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h
index 5c5d7bbef8..f63d41e812 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h
+++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h
@@ -167,18 +167,6 @@ namespace MCommon
          */
         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);
-
         /**
          * Render a simple line based skeleton for all enabled nodes of the actor instance.
          * @param[in] actorInstance A pointer to the actor instance which will be rendered.
diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp
index 2aa6b796ab..8ab7fa540d 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp
@@ -98,7 +98,6 @@ namespace EMotionFX
         result->mChildIndices       = mChildIndices;
         //result->mImportanceFactor = mImportanceFactor;
         result->mNodeFlags          = mNodeFlags;
-        result->mOBB                = mOBB;
         result->mSemanticNameID     = mSemanticNameID;
 
         // copy the node attributes
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 5e57d64167..274edd36ce 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,7 +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_OBBsColorOptionName = "OBBsColor";
     const char* RenderOptions::s_lineSkeletonColorOptionName = "lineSkeletonColor_v2";
     const char* RenderOptions::s_skeletonColorOptionName = "skeletonColor";
     const char* RenderOptions::s_selectionColorOptionName = "selectionColor";
@@ -107,7 +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_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)
@@ -167,7 +165,6 @@ namespace EMStudio
         SetNodeAABBColor(other.GetNodeAABBColor());
         SetStaticAABBColor(other.GetStaticAABBColor());
         SetMeshAABBColor(other.GetMeshAABBColor());
-        SetOBBsColor(other.GetOBBsColor());
         SetLineSkeletonColor(other.GetLineSkeletonColor());
         SetSkeletonColor(other.GetSkeletonColor());
         SetSelectionColor(other.GetSelectionColor());
@@ -204,7 +201,6 @@ namespace EMStudio
         settings->setValue(s_staticAABBColorOptionName, ColorToString(m_staticAABBColor));
         settings->setValue(s_meshAABBColorOptionName, ColorToString(m_meshAABBColor));
         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));
@@ -272,7 +268,6 @@ namespace EMStudio
         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_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());
@@ -388,7 +383,6 @@ namespace EMStudio
             ->Field(s_nodeAABBColorOptionName, &RenderOptions::m_nodeAABBColor)
             ->Field(s_staticAABBColorOptionName, &RenderOptions::m_staticAABBColor)
             ->Field(s_meshAABBColorOptionName, &RenderOptions::m_meshAABBColor)
-            ->Field(s_OBBsColorOptionName, &RenderOptions::m_OBBsColor)
             ->Field(s_lineSkeletonColorOptionName, &RenderOptions::m_lineSkeletonColor)
             ->Field(s_skeletonColorOptionName, &RenderOptions::m_skeletonColor)
             ->Field(s_selectionColorOptionName, &RenderOptions::m_selectionColor)
@@ -546,9 +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_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)
@@ -894,15 +885,6 @@ namespace EMStudio
         }
     }
 
-    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))
@@ -1240,11 +1222,6 @@ namespace EMStudio
         PluginOptionsNotificationsBus::Event(s_meshAABBColorOptionName, &PluginOptionsNotificationsBus::Events::OnOptionChanged, s_meshAABBColorOptionName);
     }
 
-    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 5e12cf935f..60f7aa1291 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,7 +59,6 @@ namespace EMStudio
         static const char* s_nodeAABBColorOptionName;
         static const char* s_staticAABBColorOptionName;
         static const char* s_meshAABBColorOptionName;
-        static const char* s_OBBsColorOptionName;
         static const char* s_lineSkeletonColorOptionName;
         static const char* s_skeletonColorOptionName;
         static const char* s_selectionColorOptionName;
@@ -190,9 +189,6 @@ namespace EMStudio
         AZ::Color GetMeshAABBColor() const { return m_meshAABBColor; }
         void SetMeshAABBColor(const AZ::Color& meshAABBColor);
 
-        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);
 
@@ -299,7 +295,6 @@ namespace EMStudio
         void OnNodeAABBColorChangedCallback() const;
         void OnStaticAABBColorChangedCallback() const;
         void OnMeshAABBColorChangedCallback() const;
-        void OnOBBsColorChangedCallback() const;
         void OnLineSkeletonColorChangedCallback() const;
         void OnSkeletonColorChangedCallback() const;
         void OnSelectionColorChangedCallback() const;
@@ -356,7 +351,6 @@ namespace EMStudio
         AZ::Color        m_nodeAABBColor;
         AZ::Color        m_staticAABBColor;
         AZ::Color        m_meshAABBColor;
-        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 e4663750ce..ef281b8301 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
@@ -1160,10 +1160,6 @@ namespace EMStudio
             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();
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 fed309d2e5..6de228fa52 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
@@ -174,10 +174,6 @@ namespace EMStudio
             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());
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..55699c165f 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
@@ -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);
@@ -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);
@@ -410,7 +408,6 @@ namespace EMStudio
         }
 
         // Override some settings as we removed those from the menu.
-        SetRenderFlag(RENDER_OBB, false);
         SetRenderFlag(RENDER_COLLISIONMESHES, false);
         SetRenderFlag(RENDER_TEXTURING, false);
 
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..defdb0d2a7 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,

From 8190d61e185ff31ff2d986f4447f5f2bd28d1cc4 Mon Sep 17 00:00:00 2001
From: Benjamin Jillich 
Date: Tue, 3 Aug 2021 17:14:04 +0200
Subject: [PATCH 074/251] Removed MCore::OBB

Signed-off-by: Benjamin Jillich 
---
 Gems/EMotionFX/Code/MCore/Source/OBB.cpp    | 638 --------------------
 Gems/EMotionFX/Code/MCore/Source/OBB.h      | 235 -------
 Gems/EMotionFX/Code/MCore/Source/OBB.inl    |  36 --
 Gems/EMotionFX/Code/MCore/mcore_files.cmake |   3 -
 4 files changed, 912 deletions(-)
 delete mode 100644 Gems/EMotionFX/Code/MCore/Source/OBB.cpp
 delete mode 100644 Gems/EMotionFX/Code/MCore/Source/OBB.h
 delete mode 100644 Gems/EMotionFX/Code/MCore/Source/OBB.inl

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/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index b0d8a67ccd..43a41b4a11 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -101,9 +101,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 From 854e5409505c0a80dc015b67d7455125e1e6d156 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Tue, 3 Aug 2021 12:42:48 -0400 Subject: [PATCH 075/251] Cleanup Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../Debug/MultiplayerDebugByteReporter.cpp | 19 +++-- .../Debug/MultiplayerDebugByteReporter.h | 8 +- .../MultiplayerDebugPerEntityReporter.cpp | 76 ++++++++++--------- .../Debug/MultiplayerDebugPerEntityReporter.h | 18 ++--- .../Debug/MultiplayerDebugSystemComponent.cpp | 15 ++-- .../Debug/MultiplayerDebugSystemComponent.h | 4 +- 6 files changed, 74 insertions(+), 66 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp index 361f9d943d..f69291013a 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -14,6 +14,11 @@ namespace Multiplayer { + MultiplayerDebugByteReporter::MultiplayerDebugByteReporter() + { + MultiplayerDebugByteReporter::Reset(); + } + void MultiplayerDebugByteReporter::ReportBytes(size_t byteSize) { m_count++; @@ -80,9 +85,9 @@ namespace Multiplayer m_lastUpdateTime = now; } - constexpr float k_bitsPerByte = 8.0f; - constexpr int k_bitsPerKilobit = 1024; - return k_bitsPerByte * m_totalBytesLastSecond / k_bitsPerKilobit; + constexpr float bitsPerByte = 8.0f; + constexpr int bitsPerKilobit = 1024; + return bitsPerByte * m_totalBytesLastSecond / bitsPerKilobit; } void MultiplayerDebugByteReporter::Combine(const MultiplayerDebugByteReporter& other) @@ -139,9 +144,9 @@ namespace Multiplayer { MultiplayerDebugByteReporter::Combine(other); - for (const auto& fieldIter : other.m_fieldReports) + for (const auto& fieldIterator : other.m_fieldReports) { - m_fieldReports[fieldIter.first].Combine(fieldIter.second); + m_fieldReports[fieldIterator.first].Combine(fieldIterator.second); } m_componentDirtyBytes.Combine(other.m_componentDirtyBytes); @@ -176,9 +181,9 @@ namespace Multiplayer { MultiplayerDebugByteReporter::Combine(other); - for (const auto& componentIter : other.m_componentReports) + for (const auto& componentIterator : other.m_componentReports) { - m_componentReports[componentIter.first].Combine(componentIter.second); + m_componentReports[componentIterator.first].Combine(componentIterator.second); } SetEntityName(other.GetEntityName()); diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h index 279f7fb360..8f7513d5d4 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.h @@ -18,7 +18,7 @@ namespace Multiplayer class MultiplayerDebugByteReporter { public: - MultiplayerDebugByteReporter() { MultiplayerDebugByteReporter::Reset(); } + MultiplayerDebugByteReporter(); virtual ~MultiplayerDebugByteReporter() = default; void ReportBytes(size_t byteSize); @@ -48,7 +48,8 @@ namespace Multiplayer AZStd::chrono::monotonic_clock::time_point m_lastUpdateTime; }; - class MultiplayerDebugComponentReporter : public MultiplayerDebugByteReporter + class MultiplayerDebugComponentReporter final + : public MultiplayerDebugByteReporter { public: MultiplayerDebugComponentReporter() = default; @@ -66,7 +67,8 @@ namespace Multiplayer MultiplayerDebugByteReporter m_componentDirtyBytes; }; - class MultiplayerDebugEntityReporter : public MultiplayerDebugByteReporter + class MultiplayerDebugEntityReporter final + : public MultiplayerDebugByteReporter { public: MultiplayerDebugEntityReporter() = default; diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index b0bfe097e1..adfef397b6 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -17,16 +17,16 @@ #include #endif -AZ_CVAR(float, net_DebugNetworkEntity_ShowAboveKbps, 1.f, nullptr, AZ::ConsoleFunctorFlags::Null, +AZ_CVAR(float, net_DebugEntities_ShowAboveKbps, 1.f, nullptr, AZ::ConsoleFunctorFlags::Null, "Prints bandwidth on network entities with higher kpbs than this value"); -AZ_CVAR(float, net_DebugNetworkEntity_WarnAboveKbps, 10.f, nullptr, AZ::ConsoleFunctorFlags::Null, +AZ_CVAR(float, net_DebugEntities_WarnAboveKbps, 10.f, nullptr, AZ::ConsoleFunctorFlags::Null, "Prints bandwidth on network entities with higher kpbs than this value"); -AZ_CVAR(AZ::Color, net_DebugNetworkEntity_WarningColor, AZ::Colors::Red, nullptr, AZ::ConsoleFunctorFlags::Null, +AZ_CVAR(AZ::Color, net_DebugEntities_WarningColor, AZ::Colors::Red, nullptr, AZ::ConsoleFunctorFlags::Null, "If true, prints debug text over entities that use a considerable amount of network traffic"); -AZ_CVAR(AZ::Color, net_DebugNetworkEntity_BelowWarningColor, AZ::Colors::Grey, nullptr, AZ::ConsoleFunctorFlags::Null, +AZ_CVAR(AZ::Color, net_DebugEntities_BelowWarningColor, AZ::Colors::Grey, nullptr, AZ::ConsoleFunctorFlags::Null, "If true, prints debug text over entities that use a considerable amount of network traffic"); namespace Multiplayer @@ -133,7 +133,8 @@ namespace Multiplayer { RecordEntitySerializeStart(mode, entityId, entityName); }); - m_eventHandlers.m_componentSerializeEnd = decltype(m_eventHandlers.m_componentSerializeEnd)([this](AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId) + m_eventHandlers.m_componentSerializeEnd = decltype(m_eventHandlers.m_componentSerializeEnd)([this](AzNetworking::SerializerMode mode, + NetComponentId netComponentId) { RecordComponentSerializeEnd(mode, netComponentId); }); @@ -141,19 +142,25 @@ namespace Multiplayer { RecordEntitySerializeStop(mode, entityId, entityName); }); - m_eventHandlers.m_propertySent = decltype(m_eventHandlers.m_propertySent)([this](Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) + m_eventHandlers.m_propertySent = decltype(m_eventHandlers.m_propertySent)([this](NetComponentId netComponentId, + PropertyIndex propertyId, uint32_t totalBytes) { RecordPropertySent(netComponentId, propertyId, totalBytes); }); - m_eventHandlers.m_propertyReceived = decltype(m_eventHandlers.m_propertyReceived)([this](Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes) + m_eventHandlers.m_propertyReceived = decltype(m_eventHandlers.m_propertyReceived)([this](NetComponentId netComponentId, + PropertyIndex propertyId, uint32_t totalBytes) { RecordPropertyReceived(netComponentId, propertyId, totalBytes); }); - m_eventHandlers.m_rpcSent = decltype(m_eventHandlers.m_rpcSent)([this](AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) + m_eventHandlers.m_rpcSent = decltype(m_eventHandlers.m_rpcSent)([this](AZ::EntityId entityId, const char* entityName, + NetComponentId netComponentId, + RpcIndex rpcId, uint32_t totalBytes) { RecordRpcSent(entityId, entityName, netComponentId, rpcId, totalBytes); }); - m_eventHandlers.m_rpcReceived = decltype(m_eventHandlers.m_rpcReceived)([this](AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) + m_eventHandlers.m_rpcReceived = decltype(m_eventHandlers.m_rpcReceived)([this](AZ::EntityId entityId, const char* entityName, + NetComponentId netComponentId, + RpcIndex rpcId, uint32_t totalBytes) { RecordRpcSent(entityId, entityName, netComponentId, rpcId, totalBytes); }); @@ -161,11 +168,6 @@ namespace Multiplayer GetMultiplayer()->GetStats().ConnectHandlers(m_eventHandlers); } - MultiplayerDebugPerEntityReporter::~MultiplayerDebugPerEntityReporter() - { - m_updateDebugOverlay.RemoveFromQueue(); - } - // -------------------------------------------------------------------------------------------- void MultiplayerDebugPerEntityReporter::OnImGuiUpdate() { @@ -228,7 +230,8 @@ namespace Multiplayer } } - void MultiplayerDebugPerEntityReporter::RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, [[maybe_unused]] Multiplayer::NetComponentId netComponentId) + void MultiplayerDebugPerEntityReporter::RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, [[maybe_unused]] NetComponentId + netComponentId) { switch (mode) { @@ -256,11 +259,11 @@ namespace Multiplayer } void MultiplayerDebugPerEntityReporter::RecordPropertySent( - Multiplayer::NetComponentId netComponentId, - Multiplayer::PropertyIndex propertyId, + NetComponentId netComponentId, + PropertyIndex propertyId, uint32_t totalBytes) { - if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + if (const MultiplayerComponentRegistry* componentRegistry = GetMultiplayerComponentRegistry()) { m_currentSendingEntityReport.ReportField(static_cast(netComponentId), componentRegistry->GetComponentName(netComponentId), @@ -269,11 +272,11 @@ namespace Multiplayer } void MultiplayerDebugPerEntityReporter::RecordPropertyReceived( - Multiplayer::NetComponentId netComponentId, - Multiplayer::PropertyIndex propertyId, + NetComponentId netComponentId, + PropertyIndex propertyId, uint32_t totalBytes) { - if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + if (const MultiplayerComponentRegistry* componentRegistry = GetMultiplayerComponentRegistry()) { m_currentReceivingEntityReport.ReportField(static_cast(netComponentId), componentRegistry->GetComponentName(netComponentId), @@ -281,9 +284,10 @@ namespace Multiplayer } } - void MultiplayerDebugPerEntityReporter::RecordRpcSent(AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes) + void MultiplayerDebugPerEntityReporter::RecordRpcSent(AZ::EntityId entityId, const char* entityName, NetComponentId netComponentId, + RpcIndex rpcId, uint32_t totalBytes) { - if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + if (const MultiplayerComponentRegistry* componentRegistry = GetMultiplayerComponentRegistry()) { // MultiplayerDebugByteReporter requires a RecordEntitySerializeStart(AzNetworking::SerializerMode::ReadFromObject, entityId, entityName); @@ -303,7 +307,7 @@ namespace Multiplayer RpcIndex rpcId, uint32_t totalBytes) { - if (const Multiplayer::MultiplayerComponentRegistry* componentRegistry = Multiplayer::GetMultiplayerComponentRegistry()) + if (const MultiplayerComponentRegistry* componentRegistry = GetMultiplayerComponentRegistry()) { RecordEntitySerializeStart(AzNetworking::SerializerMode::WriteToObject, entityId, entityName); @@ -320,19 +324,18 @@ namespace Multiplayer { m_networkEntitiesTraffic.clear(); + // Merging up and down traffic to provide a unified debug text per entity for (AZStd::pair& entityPair : m_receivingEntityReports) { m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); m_networkEntitiesTraffic[entityPair.first].m_down = entityPair.second.GetKbitsPerSecond(); } - for (AZStd::pair& entityPair : m_sendingEntityReports) { m_networkEntitiesTraffic[entityPair.first].m_name = entityPair.second.GetEntityName(); m_networkEntitiesTraffic[entityPair.first].m_up = entityPair.second.GetKbitsPerSecond(); } - //get debug display interface for the viewport if (m_debugDisplay == nullptr) { AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; @@ -342,28 +345,28 @@ namespace Multiplayer const AZ::u32 stateBefore = m_debugDisplay->GetState(); - for (AZStd::pair& networkEntity : m_networkEntitiesTraffic) + for (const AZStd::pair& networkEntity : m_networkEntitiesTraffic) { - if (networkEntity.second.m_down < net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up < net_DebugNetworkEntity_ShowAboveKbps) + if (networkEntity.second.m_down < net_DebugEntities_ShowAboveKbps && networkEntity.second.m_up < net_DebugEntities_ShowAboveKbps) { continue; } - if (networkEntity.second.m_down > net_DebugNetworkEntity_WarnAboveKbps || networkEntity.second.m_up > net_DebugNetworkEntity_WarnAboveKbps) + if (networkEntity.second.m_down > net_DebugEntities_WarnAboveKbps || networkEntity.second.m_up > net_DebugEntities_WarnAboveKbps) { - m_debugDisplay->SetColor(net_DebugNetworkEntity_WarningColor); + m_debugDisplay->SetColor(net_DebugEntities_WarningColor); } else { - m_debugDisplay->SetColor(net_DebugNetworkEntity_BelowWarningColor); + m_debugDisplay->SetColor(net_DebugEntities_BelowWarningColor); } - if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps && networkEntity.second.m_up > net_DebugNetworkEntity_ShowAboveKbps) + if (networkEntity.second.m_down > net_DebugEntities_ShowAboveKbps && networkEntity.second.m_up > net_DebugEntities_ShowAboveKbps) { azsprintf(m_statusBuffer, "[%s] %.0f down / %0.f up (kbps)", networkEntity.second.m_name, networkEntity.second.m_down, networkEntity.second.m_up); } - else if (networkEntity.second.m_down > net_DebugNetworkEntity_ShowAboveKbps) + else if (networkEntity.second.m_down > net_DebugEntities_ShowAboveKbps) { azsprintf(m_statusBuffer, "[%s] %.0f down (kbps)", networkEntity.second.m_name, networkEntity.second.m_down); } @@ -373,9 +376,12 @@ namespace Multiplayer } AZ::Vector3 entityPosition = AZ::Vector3::CreateZero(); - constexpr bool centerText = true; AZ::TransformBus::EventResult(entityPosition, networkEntity.first, &AZ::TransformBus::Events::GetWorldTranslation); - m_debugDisplay->DrawTextLabel(entityPosition, 1.0f, m_statusBuffer, centerText, 0, 0); + if (entityPosition.IsZero() == false) + { + constexpr bool centerText = true; + m_debugDisplay->DrawTextLabel(entityPosition, 1.0f, m_statusBuffer, centerText, 0, 0); + } } m_debugDisplay->SetState(stateBefore); diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h index 8a33bc78ee..8a68110b93 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.h @@ -18,34 +18,34 @@ namespace Multiplayer { /** - * \brief GridMate network live analysis tool via ImGui. + * \brief Multiplayer traffic live analysis tool via ImGui. */ class MultiplayerDebugPerEntityReporter { public: MultiplayerDebugPerEntityReporter(); - ~MultiplayerDebugPerEntityReporter(); - // main update loop + //! main update loop void OnImGuiUpdate(); //! Event handlers // @{ void RecordEntitySerializeStart(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName); - void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, Multiplayer::NetComponentId netComponentId); + void RecordComponentSerializeEnd(AzNetworking::SerializerMode mode, NetComponentId netComponentId); void RecordEntitySerializeStop(AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName); - void RecordPropertySent(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); - void RecordPropertyReceived(Multiplayer::NetComponentId netComponentId, Multiplayer::PropertyIndex propertyId, uint32_t totalBytes); - void RecordRpcSent(AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes); - void RecordRpcReceived(AZ::EntityId entityId, const char* entityName, Multiplayer::NetComponentId netComponentId, Multiplayer::RpcIndex rpcId, uint32_t totalBytes); + void RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); + void RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes); + void RecordRpcSent(AZ::EntityId entityId, const char* entityName, NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); + void RecordRpcReceived(AZ::EntityId entityId, const char* entityName, NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes); // }@ + //! Draws bandwidth text over entities void UpdateDebugOverlay(); private: AZ::ScheduledEvent m_updateDebugOverlay; - Multiplayer::MultiplayerStats::EventHandlers m_eventHandlers; + MultiplayerStats::EventHandlers m_eventHandlers; AZStd::map m_sendingEntityReports{}; MultiplayerDebugEntityReporter m_currentSendingEntityReport; diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index 407b6f5f2d..b6dc9573fa 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -13,9 +13,9 @@ #include #include -void OnDebugNetworkEntity_ShowBandwidth_Changed(const bool& showBandwidth); +void OnDebugEntities_ShowBandwidth_Changed(const bool& showBandwidth); -AZ_CVAR(bool, net_DebugNetworkEntity_ShowBandwidth, false, &OnDebugNetworkEntity_ShowBandwidth_Changed, AZ::ConsoleFunctorFlags::Null, +AZ_CVAR(bool, net_DebugEntities_ShowBandwidth, false, &OnDebugEntities_ShowBandwidth_Changed, AZ::ConsoleFunctorFlags::Null, "If true, prints bandwidth values over entities that use a considerable amount of network traffic"); namespace Multiplayer @@ -458,13 +458,10 @@ namespace Multiplayer { if (ImGui::Begin("Multiplayer Per Entity Stats", &m_displayPerEntityStats, ImGuiWindowFlags_AlwaysAutoResize)) { - if (ImGui::Checkbox("Show Bandwidth over Entities", &m_displayPerEntityBandwidth)) + // This overrides @net_DebugNetworkEntity_ShowBandwidth value + if (m_reporter == nullptr) { - // This overrides @net_DebugNetworkEntity_ShowBandwidth value - if (m_reporter == nullptr) - { - ShowEntityBandwidthDebugOverlay(); - } + ShowEntityBandwidthDebugOverlay(); } if (m_reporter) @@ -477,7 +474,7 @@ namespace Multiplayer #endif } -void OnDebugNetworkEntity_ShowBandwidth_Changed(const bool& showBandwidth) +void OnDebugEntities_ShowBandwidth_Changed(const bool& showBandwidth) { if (showBandwidth) { diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h index 9be53cca02..7555073f10 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h @@ -43,7 +43,7 @@ namespace Multiplayer void Deactivate() override; //! @} - //! IMultiplayerDebugSystem overrides + //! IMultiplayerDebug overrides //! @{ void ShowEntityBandwidthDebugOverlay() override; void HideEntityBandwidthDebugOverlay() override; @@ -62,8 +62,6 @@ namespace Multiplayer bool m_displayMultiplayerStats = false; bool m_displayPerEntityStats = false; - bool m_displayPerEntityBandwidth = false; - AZStd::unique_ptr m_reporter; }; } From 2118ef7a21ad2d5d80979e80d9516e9a6177a443 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Tue, 3 Aug 2021 12:48:36 -0400 Subject: [PATCH 076/251] Preparing for PR Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h | 4 ++-- .../Code/Source/Debug/MultiplayerDebugSystemComponent.cpp | 4 ---- .../Code/Source/Debug/MultiplayerDebugSystemComponent.h | 1 - 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h index 384db66317..e528a44ed9 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerDebug.h @@ -19,10 +19,10 @@ namespace Multiplayer virtual ~IMultiplayerDebug() = default; - //! + //! Enables printing of debug text over entities that have significant amount of traffic. virtual void ShowEntityBandwidthDebugOverlay() = 0; - //! + //! Disables printing of debug text over entities that have significant amount of traffic. virtual void HideEntityBandwidthDebugOverlay() = 0; }; } diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index b6dc9573fa..27a4dff485 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -63,10 +63,6 @@ namespace Multiplayer m_reporter.reset(); } - void MultiplayerDebugSystemComponent::OnImGuiInitialize() - { - } - #ifdef IMGUI_ENABLED void MultiplayerDebugSystemComponent::OnImGuiMainMenuUpdate() { diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h index 7555073f10..7b3c852f58 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.h @@ -52,7 +52,6 @@ namespace Multiplayer #ifdef IMGUI_ENABLED //! ImGui::ImGuiUpdateListenerBus overrides //! @{ - void OnImGuiInitialize() override; void OnImGuiMainMenuUpdate() override; void OnImGuiUpdate() override; //! @} From 72aed355cedf9fe28e24e396c64db93a4b1946a2 Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Tue, 3 Aug 2021 12:54:32 -0400 Subject: [PATCH 077/251] Cleanup Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../Source/NetworkEntity/EntityReplication/EntityReplicator.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 457ed3eed5..4155f8813b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -30,8 +30,6 @@ #include -#pragma optimize("", off) - namespace Multiplayer { EntityReplicator::EntityReplicator From 65704110ad283e031f3ee9bae1d74b340f5e3f80 Mon Sep 17 00:00:00 2001 From: evanchia Date: Tue, 3 Aug 2021 10:28:45 -0700 Subject: [PATCH 078/251] removing pytest skips on smoke tests Signed-off-by: evanchia --- .../PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py | 2 -- .../PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py | 2 -- 2 files changed, 4 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py index 54d7b3eb6f..6522514f2f 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py @@ -13,8 +13,6 @@ 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 import editor_python_test_tools.hydra_test_utils as editor_test_utils from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py index bfce7895e6..7debcab938 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py @@ -13,8 +13,6 @@ 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 import editor_python_test_tools.hydra_test_utils as editor_test_utils from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole From 963cbcaf6184092aade9924475b530ed70523087 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 3 Aug 2021 10:31:43 -0700 Subject: [PATCH 079/251] Remove A version of some fw declarations and macro defines since those are error prone to define, if someone were to include windows.h after that header, it would cause issues Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../AzCore/AzCore/std/parallel/binary_semaphore.h | 4 ++-- .../Common/WinAPI/AzCore/std/parallel/config_WinAPI.h | 8 -------- .../AzCore/std/parallel/internal/semaphore_WinAPI.h | 4 ++-- 3 files changed, 4 insertions(+), 12 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h b/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h index 797de5fceb..f9d0cdbe4d 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h @@ -38,13 +38,13 @@ namespace AZStd binary_semaphore(bool initialState = false) { - m_event = CreateEvent(nullptr, false, initialState, nullptr); + m_event = CreateEventW(nullptr, false, initialState, nullptr); AZ_Assert(m_event != NULL, "CreateEvent error: %d\n", GetLastError()); } binary_semaphore(const char* name, bool initialState = false) { (void)name; // name is used only for debug, if we pass it to the semaphore it will become named semaphore - m_event = CreateEvent(nullptr, false, initialState, nullptr); + m_event = CreateEventW(nullptr, false, initialState, nullptr); AZ_Assert(m_event != NULL, "CreateEvent error: %d\n", GetLastError()); } diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h index fb91e4d503..86117c0539 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h @@ -71,19 +71,11 @@ extern "C" using LPSECURITY_ATTRIBUTES = SECURITY_ATTRIBUTES*; // Semaphore - AZ_DLL_IMPORT HANDLE _stdcall CreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCSTR lpName); AZ_DLL_IMPORT HANDLE _stdcall CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCWSTR lpName); AZ_DLL_IMPORT BOOL _stdcall ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount); - #ifndef CreateSemaphore - #define CreateSemaphore CreateSemaphoreW - #endif // Event - AZ_DLL_IMPORT HANDLE _stdcall CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName); AZ_DLL_IMPORT HANDLE _stdcall CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCWSTR lpName); - #ifndef CreateEvent - #define CreateEvent CreateEventW - #endif AZ_DLL_IMPORT BOOL _stdcall SetEvent(HANDLE); } diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h index cca90787e6..cd6b216057 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h @@ -15,14 +15,14 @@ namespace AZStd { inline semaphore::semaphore(unsigned int initialCount, unsigned int maximumCount) { - m_semaphore = CreateSemaphore(NULL, initialCount, maximumCount, 0); + m_semaphore = CreateSemaphoreW(NULL, initialCount, maximumCount, 0); AZ_Assert(m_semaphore != NULL, "CreateSemaphore error: %d\n", GetLastError()); } inline semaphore::semaphore(const char* name, unsigned int initialCount, unsigned int maximumCount) { (void)name; // name is used only for debug, if we pass it to the semaphore it will become named semaphore - m_semaphore = CreateSemaphore(NULL, initialCount, maximumCount, 0); + m_semaphore = CreateSemaphoreW(NULL, initialCount, maximumCount, 0); AZ_Assert(m_semaphore != NULL, "CreateSemaphore error: %d\n", GetLastError()); } From 928c8ff16c74121c5d80e9de7988fae806f6b483 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 3 Aug 2021 10:50:58 -0700 Subject: [PATCH 080/251] add unit tests Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Framework/AzCore/Tests/AZStd/String.cpp | 21 ++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index 2d2602e456..c0d378bd39 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -686,6 +686,27 @@ namespace UnitTest wstr1 = wstring::format(L"%hs", str.c_str()); AZ_TEST_ASSERT(wstr1 == L"BLABLA 5"); + // wstring to char buffer + char strBuffer[9]; + to_string(strBuffer, 9, wstr1.c_str()); + AZ_TEST_ASSERT(0 == azstricmp(strBuffer, "BLABLA 5")); + + // wchar_t buffer to char buffer + wchar_t wstrBuffer[9] = L"BLABLA 5"; + memset(strBuffer, 0, AZ_ARRAY_SIZE(strBuffer)); + to_string(strBuffer, 9, wstrBuffer); + AZ_TEST_ASSERT(0 == azstricmp(strBuffer, "BLABLA 5")); + + // string to wchar_t buffer + memset(wstrBuffer, 0, AZ_ARRAY_SIZE(wstrBuffer)); + to_wstring(wstrBuffer, 9, str1.c_str()); + AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BlaBla 5")); + + // char buffer to wchar_t buffer + memset(wstrBuffer, 0, AZ_ARRAY_SIZE(wstrBuffer)); + to_wstring(wstrBuffer, 9, strBuffer); + AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BLABLA 5")); + // wchar UTF16/UTF32 to/from Utf8 wstr1 = L"this is a \u20AC \u00A3 test"; // that's a euro and a pound sterling AZStd::to_string(str, wstr1); From 4eacd076da89f7552eae93b47b8534d5538f4026 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Tue, 3 Aug 2021 15:53:20 -0500 Subject: [PATCH 081/251] Fixing ME and ATWindowNotificationBus Signed-off-by: Dayo Lawal --- .../Window/AtomToolsMainWindow.h | 7 +++-- .../AtomToolsMainWindowNotificationBus.h} | 11 ++++---- .../Window/AtomToolsMainWindowRequestBus.h | 3 +++ .../Code/atomtoolsframework_files.cmake | 3 ++- .../Source/Window/MaterialEditorWindow.cpp | 9 ++++--- .../Code/Source/Window/MaterialEditorWindow.h | 7 +++-- .../Window/MaterialEditorWindowComponent.cpp | 26 +++++++++++-------- .../Code/materialeditorwindow_files.cmake | 2 -- ...erManagementConsoleWindowNotificationBus.h | 26 ------------------- .../Window/ShaderManagementConsoleWindow.cpp | 18 +++++++------ .../Window/ShaderManagementConsoleWindow.h | 8 +++--- .../shadermanagementconsolewindow_files.cmake | 1 - 12 files changed, 50 insertions(+), 71 deletions(-) rename Gems/Atom/Tools/{MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowNotificationBus.h => AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h} (62%) delete mode 100644 Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowNotificationBus.h diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h index 6b02bd1c06..8d500c1320 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -7,8 +7,8 @@ */ #pragma once -#include #include +#include #include #include @@ -44,7 +44,7 @@ namespace AtomToolsFramework virtual void RemoveTabForDocumentId(const AZ::Uuid& documentId); virtual void UpdateTabForDocumentId(const AZ::Uuid& documentId); virtual AZ::Uuid GetDocumentIdFromTab(const int tabIndex) const; - + virtual void OpenTabContextMenu(); virtual void SelectPreviousTab(); virtual void SelectNextTab(); @@ -58,6 +58,5 @@ namespace AtomToolsFramework AZStd::unordered_map m_dockWidgets; QMenu* m_menuFile = {}; - //StatusBarWidget* m_statusBar = {}; }; -} +} // 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..cf5c02085d 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 OnAtomToolsMainWindowWindowClosing(){}; }; - using MaterialEditorWindowNotificationBus = AZ::EBus; + using AtomToolsMainWindowNotificationBus = AZ::EBus; -} // namespace MaterialEditor +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h index ee21554844..6edb44bc5c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h @@ -7,7 +7,10 @@ */ #pragma once + +//! Disables "unreferenced formal parameter" warning #pragma warning(disable : 4100) + #include #include #include diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index 0769aac86c..49e641eb9c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -27,6 +27,7 @@ set(FILES 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 @@ -44,4 +45,4 @@ set(FILES 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/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 733a01539e..43d91e9721 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -15,10 +15,10 @@ #include #include -#include #include #include +#include #include #include @@ -185,7 +185,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::OnAtomToolsMainWindowWindowClosing); } void MaterialEditorWindow::OnDocumentOpened(const AZ::Uuid& documentId) @@ -284,7 +285,7 @@ namespace MaterialEditor void MaterialEditorWindow::SetupMenu() { - AtomToolsFramework::AtomToolsMainWindow::SetupMenu(); + Base::SetupMenu(); m_actionNew = m_menuFile->addAction("&New...", [this]() { CreateMaterialDialog createDialog(this); @@ -482,7 +483,7 @@ namespace MaterialEditor void MaterialEditorWindow::SetupTabs() { - AtomToolsFramework::AtomToolsMainWindow::SetupTabs(); + Base::SetupTabs(); // 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 diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 65c13a094d..d865f1170d 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -9,9 +9,9 @@ #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 @@ -19,14 +19,13 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnin #include #include -#include #include -#include #include +#include #include -#include #include +#include AZ_POP_DISABLE_WARNING #endif diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 05641e8e55..88c7c0576f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -18,6 +18,8 @@ #include #include #include +#include + namespace MaterialEditor { @@ -33,25 +35,27 @@ namespace MaterialEditor if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("MaterialEditorWindowFactoryRequestBus") + using FactoryRequestBus = MaterialEditorWindowFactoryRequestBus; + behaviorContext->EBus("MaterialEditorWindowFactoryRequestBus") ->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", &FactoryRequestBus::Events::CreateMaterialEditorWindow) + ->Event("DestroyMaterialEditorWindow", &FactoryRequestBus::Events::DestroyMaterialEditorWindow) ; - behaviorContext->EBus("MaterialEditorWindowRequestBus") + using RequestBus = AtomToolsFramework::AtomToolsMainWindowRequestBus; + 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", &RequestBus::Events::ActivateWindow) + ->Event("SetDockWidgetVisible", &RequestBus::Events::SetDockWidgetVisible) + ->Event("IsDockWidgetVisible", &RequestBus::Events::IsDockWidgetVisible) + ->Event("GetDockWidgetNames", &RequestBus::Events::GetDockWidgetNames) + ->Event("ResizeViewportRenderTarget", &RequestBus::Events::ResizeViewportRenderTarget) + ->Event("LockViewportRenderTargetSize", &RequestBus::Events::LockViewportRenderTargetSize) + ->Event("UnlockViewportRenderTargetSize", &RequestBus::Events::UnlockViewportRenderTargetSize) ; } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake index caef9916f6..34d4bc9a28 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake @@ -9,8 +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 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/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index e02ab83597..825b17fb5e 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -5,6 +5,12 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + +#include +#include + +#include +#include #include @@ -15,11 +21,6 @@ #include #include #include -#include - -#include -#include -#include #include @@ -80,7 +81,8 @@ namespace ShaderManagementConsole return; } - ShaderManagementConsoleWindowNotificationBus::Broadcast(&ShaderManagementConsoleWindowNotifications::OnShaderManagementConsoleWindowClosing); + AtomToolsFramework::AtomToolsMainWindowNotificationBus::Broadcast( + &AtomToolsFramework::AtomToolsMainWindowNotifications::OnAtomToolsMainWindowWindowClosing); } void ShaderManagementConsoleWindow::OnDocumentOpened(const AZ::Uuid& documentId) @@ -159,7 +161,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindow::SetupMenu() { - AtomToolsFramework::AtomToolsMainWindow::SetupMenu(); + Base::SetupMenu(); m_actionOpen = m_menuFile->addAction("&Open...", [this]() { const AZStd::vector assetTypes = { @@ -277,7 +279,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindow::SetupTabs() { - AtomToolsFramework::AtomToolsMainWindow::SetupTabs(); + Base::SetupTabs(); // 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 diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index 8513366ec2..127a777ddd 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -9,11 +9,11 @@ #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 @@ -26,8 +26,8 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnin #include #include -#include #include +#include AZ_POP_DISABLE_WARNING #endif @@ -63,7 +63,7 @@ namespace ShaderManagementConsole void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override; void OnDocumentSaved(const AZ::Uuid& documentId) override; - void SetupMenu() override; + void SetupMenu() override; void SetupTabs() override; void AddTabForDocumentId(const AZ::Uuid& documentId) override; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake index dad4f759d7..056b74e411 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake @@ -8,7 +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 From 259bc3f85e59e0f306d2aa7c3db584eab27384ef Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Tue, 3 Aug 2021 19:24:46 -0500 Subject: [PATCH 082/251] ATWindowNotificationBus and ATFactoryRequestBus Signed-off-by: Dayo Lawal --- .../Application/AtomToolsApplication.h | 12 +++++ .../Window/AtomToolsMainWindow.h | 1 + .../AtomToolsMainWindowFactoryRequestBus.h | 8 ++-- .../AtomToolsMainWindowNotificationBus.h | 2 +- .../Application/AtomToolsApplication.cpp | 23 +++++++++- .../MaterialEditorWindowFactoryRequestBus.h | 31 ------------- .../Code/Source/MaterialEditorApplication.cpp | 46 ++----------------- .../Code/Source/MaterialEditorApplication.h | 14 ------ .../Source/Window/MaterialEditorWindow.cpp | 2 +- .../Code/materialeditorwindow_files.cmake | 1 - .../ShaderManagementConsoleWindowRequestBus.h | 33 ------------- .../ShaderManagementConsoleApplication.cpp | 33 +++---------- .../ShaderManagementConsoleApplication.h | 15 +----- .../Window/ShaderManagementConsoleWindow.cpp | 2 +- ...ShaderManagementConsoleWindowComponent.cpp | 10 ++-- .../ShaderManagementConsoleWindowComponent.h | 4 +- .../shadermanagementconsolewindow_files.cmake | 1 - 17 files changed, 61 insertions(+), 177 deletions(-) delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowFactoryRequestBus.h delete mode 100644 Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowRequestBus.h 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 bceea24aad..ee7c37f7f1 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 index 8d500c1320..f3271123b0 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -8,6 +8,7 @@ #pragma once #include + #include #include diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h index aed0d877db..c93b4ba4b9 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h @@ -19,11 +19,11 @@ namespace AtomToolsFramework static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - /// Creates and shows the AtomToolsMainWindow - virtual void CreateAtomToolsMainWindow() = 0; + /// Creates and shows main window + virtual void CreateMainWindow() = 0; - //! Destroys material editor window and releases all cached assets - virtual void DestroyAtomToolsMainWindow() = 0; + //! Destroys main window and releases all cached assets + virtual void DestroyMainWindow() = 0; }; using AtomToolsMainWindowFactoryRequestBus = AZ::EBus; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h index cf5c02085d..cadd3440d9 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h @@ -18,7 +18,7 @@ namespace AtomToolsFramework static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - virtual void OnAtomToolsMainWindowWindowClosing(){}; + virtual void OnMainWindowClosing(){}; }; using AtomToolsMainWindowNotificationBus = AZ::EBus; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index 3a542db1a4..4094e7a3a0 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -66,6 +67,11 @@ namespace AtomToolsFramework }); } + AtomToolsApplication ::~AtomToolsApplication() + { + AtomToolsMainWindowNotificationBus::Handler::BusDisconnect(); + } + void AtomToolsApplication::CreateReflectionManager() { Base::CreateReflectionManager(); @@ -147,12 +153,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(); } @@ -391,6 +406,10 @@ namespace AtomToolsFramework LoadSettings(); + AtomToolsMainWindowNotificationBus::Handler::BusConnect(); + + AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::CreateMainWindow); + auto editorPythonEventsInterface = AZ::Interface::Get(); if (editorPythonEventsInterface) { @@ -438,6 +457,8 @@ namespace AtomToolsFramework void AtomToolsApplication::Stop() { + AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::DestroyMainWindow); + UnloadSettings(); Base::Stop(); } 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 7b9372e72b..53409d717f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -6,8 +6,6 @@ * */ -#include - #include #include @@ -17,8 +15,9 @@ #include #include -#include -#include + +#include +#include #include #include @@ -84,7 +83,6 @@ namespace MaterialEditor MaterialEditorApplication::~MaterialEditorApplication() { AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); - MaterialEditorWindowNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); } @@ -96,22 +94,6 @@ 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" }); @@ -122,8 +104,8 @@ namespace MaterialEditor const AZStd::string activateWindowSwitchName = "activatewindow"; if (commandLine.HasSwitch(activateWindowSwitchName)) { - MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( - &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); + AtomToolsFramework::AtomToolsMainWindowRequestBus::Broadcast( + &AtomToolsFramework::AtomToolsMainWindowRequestBus::Handler::ActivateWindow); } // Process command line options for opening one or more material documents on startup @@ -138,22 +120,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 b1c742d4dd..2fbab79e41 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -9,7 +9,6 @@ #pragma once #include -#include #include #include @@ -20,7 +19,6 @@ namespace MaterialEditor class MaterialEditorApplication : public AtomToolsFramework::AtomToolsApplication - , private MaterialEditorWindowNotificationBus::Handler { public: AZ_TYPE_INFO(MaterialEditor::MaterialEditorApplication, "{30F90CA5-1253-49B5-8143-19CEE37E22BB}"); @@ -34,21 +32,9 @@ namespace MaterialEditor // 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; //! List of common asset filters for things that need to be compiled to run the material editor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 43d91e9721..8367f30680 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -186,7 +186,7 @@ namespace MaterialEditor windowSettings->m_mainWindowState.assign(windowState.begin(), windowState.end()); AtomToolsFramework::AtomToolsMainWindowNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsMainWindowNotifications::OnAtomToolsMainWindowWindowClosing); + &AtomToolsFramework::AtomToolsMainWindowNotifications::OnMainWindowClosing); } void MaterialEditorWindow::OnDocumentOpened(const AZ::Uuid& documentId) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake index 34d4bc9a28..6294adad88 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake @@ -9,7 +9,6 @@ set(FILES Include/Atom/Window/MaterialEditorWindowModule.h Include/Atom/Window/MaterialEditorWindowSettings.h - Include/Atom/Window/MaterialEditorWindowFactoryRequestBus.h Source/Window/MaterialEditorBrowserInteractions.h Source/Window/MaterialEditorBrowserInteractions.cpp Source/Window/MaterialEditorWindow.h 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 7d2aa02e19..e3b3c6e5aa 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -35,7 +35,6 @@ #include #include -#include #include #include #include @@ -77,28 +76,17 @@ namespace ShaderManagementConsole *AZ::SettingsRegistry::Get(), GetBuildTargetName()); } - void ShaderManagementConsoleApplication::CreateStaticModules(AZStd::vector& outModules) + ShaderManagementConsoleApplication::~ShaderManagementConsoleApplication() { - Base::CreateStaticModules(outModules); - outModules.push_back(aznew ShaderManagementConsoleDocumentModule); - outModules.push_back(aznew ShaderManagementConsoleWindowModule); - } - - void ShaderManagementConsoleApplication::OnShaderManagementConsoleWindowClosing() - { - ExitMainLoop(); - ShaderManagementConsoleWindowNotificationBus::Handler::BusDisconnect(); + AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); } - void ShaderManagementConsoleApplication::Destroy() + void ShaderManagementConsoleApplication::CreateStaticModules(AZStd::vector& outModules) { - // 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(); + Base::CreateStaticModules(outModules); + outModules.push_back(aznew ShaderManagementConsoleDocumentModule); + outModules.push_back(aznew ShaderManagementConsoleWindowModule); } AZStd::vector ShaderManagementConsoleApplication::GetCriticalAssetFilters() const @@ -129,13 +117,4 @@ namespace ShaderManagementConsole ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); } } - - void ShaderManagementConsoleApplication::StartInternal() - { - Base::StartInternal(); - - ShaderManagementConsoleWindowNotificationBus::Handler::BusConnect(); - - ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Broadcast(&ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Handler::CreateShaderManagementConsoleWindow); - } } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index 5d3696fee3..4fad40400c 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -9,7 +9,6 @@ #pragma once #include -#include #include #include @@ -18,7 +17,6 @@ namespace ShaderManagementConsole { class ShaderManagementConsoleApplication : public AtomToolsFramework::AtomToolsApplication - , private ShaderManagementConsoleWindowNotificationBus::Handler { public: AZ_TYPE_INFO(ShaderManagementConsole::ShaderManagementConsoleApplication, "{A31B1AEB-4DA3-49CD-884A-CC998FF7546F}"); @@ -26,7 +24,7 @@ namespace ShaderManagementConsole using Base = AtomToolsFramework::AtomToolsApplication; ShaderManagementConsoleApplication(int* argc, char*** argv); - virtual ~ShaderManagementConsoleApplication() = default; + virtual ~ShaderManagementConsoleApplication(); ////////////////////////////////////////////////////////////////////////// // AzFramework::Application @@ -34,18 +32,7 @@ namespace ShaderManagementConsole const char* GetCurrentConfigurationName() const override; private: - ////////////////////////////////////////////////////////////////////////// - // ShaderManagementConsoleWindowNotificationBus::Handler overrides... - void OnShaderManagementConsoleWindowClosing() override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // AzFramework::Application overrides... - void Destroy() override; - ////////////////////////////////////////////////////////////////////////// - void ProcessCommandLine(); - void StartInternal() override; AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; }; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 825b17fb5e..24acf1eb89 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -82,7 +82,7 @@ namespace ShaderManagementConsole } AtomToolsFramework::AtomToolsMainWindowNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsMainWindowNotifications::OnAtomToolsMainWindowWindowClosing); + &AtomToolsFramework::AtomToolsMainWindowNotifications::OnMainWindowClosing); } void ShaderManagementConsoleWindow::OnDocumentOpened(const AZ::Uuid& documentId) diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp index 06c219f1cc..b93f164323 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", &ShaderManagementConsoleWindowFactoryRequestBus::Events::CreateShaderManagementConsoleWindow) + ->Event("DestroyShaderManagementConsoleWindow", &ShaderManagementConsoleWindowFactoryRequestBus::Events::DestroyShaderManagementConsoleWindow) ; behaviorContext->EBus("ShaderManagementConsoleRequestBus") @@ -87,7 +87,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::Activate() { AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - ShaderManagementConsoleWindowRequestBus::Handler::BusConnect(); + ShaderManagementConsoleWindowFactoryRequestBus::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(); + ShaderManagementConsoleWindowFactoryRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); 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..3d573ec416 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 ShaderManagementConsoleWindowFactoryRequestBus::Handler , private ShaderManagementConsoleRequestBus::Handler , private AzToolsFramework::EditorWindowRequestBus::Handler { diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake index 056b74e411..0d33d990a4 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake @@ -8,7 +8,6 @@ set(FILES Include/Atom/Window/ShaderManagementConsoleWindowModule.h - Include/Atom/Window/ShaderManagementConsoleWindowRequestBus.h Include/Atom/Core/ShaderManagementConsoleRequestBus.h Source/Window/ShaderManagementConsoleBrowserInteractions.h Source/Window/ShaderManagementConsoleBrowserInteractions.cpp From f8c8181b0cc6a7c600b7d3d7464d1a00cde4b0b1 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Tue, 3 Aug 2021 19:47:50 -0500 Subject: [PATCH 083/251] Bug fix (updating WindowComponent) Signed-off-by: Dayo Lawal --- .../Window/MaterialEditorWindowComponent.cpp | 18 +++++++++--------- .../Window/MaterialEditorWindowComponent.h | 10 +++++----- .../ShaderManagementConsoleWindowComponent.cpp | 16 +++++++++------- .../ShaderManagementConsoleWindowComponent.h | 10 +++++----- 4 files changed, 28 insertions(+), 26 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 88c7c0576f..33987df5b6 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -6,7 +6,6 @@ * */ -#include #include #include #include @@ -23,6 +22,9 @@ namespace MaterialEditor { + using FactoryRequestBus = AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus; + using RequestBus = AtomToolsFramework::AtomToolsMainWindowRequestBus; + void MaterialEditorWindowComponent::Reflect(AZ::ReflectContext* context) { MaterialEditorWindowSettings::Reflect(context); @@ -35,16 +37,14 @@ namespace MaterialEditor if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - using FactoryRequestBus = MaterialEditorWindowFactoryRequestBus; behaviorContext->EBus("MaterialEditorWindowFactoryRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "materialeditor") - ->Event("CreateMaterialEditorWindow", &FactoryRequestBus::Events::CreateMaterialEditorWindow) - ->Event("DestroyMaterialEditorWindow", &FactoryRequestBus::Events::DestroyMaterialEditorWindow) + ->Event("CreateMaterialEditorWindow", &FactoryRequestBus::Events::CreateMainWindow) + ->Event("DestroyMaterialEditorWindow", &FactoryRequestBus::Events::DestroyMainWindow) ; - using RequestBus = AtomToolsFramework::AtomToolsMainWindowRequestBus; behaviorContext->EBus("MaterialEditorWindowRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") @@ -84,26 +84,26 @@ namespace MaterialEditor void MaterialEditorWindowComponent::Activate() { AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - MaterialEditorWindowFactoryRequestBus::Handler::BusConnect(); + FactoryRequestBus::Handler::BusConnect(); AzToolsFramework::SourceControlConnectionRequestBus::Broadcast(&AzToolsFramework::SourceControlConnectionRequests::EnableSourceControl, true); } void MaterialEditorWindowComponent::Deactivate() { - MaterialEditorWindowFactoryRequestBus::Handler::BusDisconnect(); + FactoryRequestBus::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/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp index b93f164323..e9dda40a50 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp @@ -34,6 +34,8 @@ AZ_POP_DISABLE_WARNING namespace ShaderManagementConsole { + using FactoryRequestBus = AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus; + void ShaderManagementConsoleWindowComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serialize = azrtti_cast(context)) @@ -44,12 +46,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", &ShaderManagementConsoleWindowFactoryRequestBus::Events::CreateShaderManagementConsoleWindow) - ->Event("DestroyShaderManagementConsoleWindow", &ShaderManagementConsoleWindowFactoryRequestBus::Events::DestroyShaderManagementConsoleWindow) + ->Event("CreateShaderManagementConsoleWindow", &FactoryRequestBus::Events::CreateMainWindow) + ->Event("DestroyShaderManagementConsoleWindow", &FactoryRequestBus::Events::DestroyMainWindow) ; behaviorContext->EBus("ShaderManagementConsoleRequestBus") @@ -87,7 +89,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::Activate() { AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - ShaderManagementConsoleWindowFactoryRequestBus::Handler::BusConnect(); + FactoryRequestBus::Handler::BusConnect(); ShaderManagementConsoleRequestBus::Handler::BusConnect(); AzToolsFramework::SourceControlConnectionRequestBus::Broadcast(&AzToolsFramework::SourceControlConnectionRequests::EnableSourceControl, true); } @@ -95,7 +97,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::Deactivate() { ShaderManagementConsoleRequestBus::Handler::BusDisconnect(); - ShaderManagementConsoleWindowFactoryRequestBus::Handler::BusDisconnect(); + FactoryRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); m_window.reset(); @@ -106,7 +108,7 @@ namespace ShaderManagementConsole return m_window.get(); } - void ShaderManagementConsoleWindowComponent::CreateShaderManagementConsoleWindow() + void ShaderManagementConsoleWindowComponent::CreateMainWindow() { m_assetBrowserInteractions.reset(aznew ShaderManagementConsoleBrowserInteractions); @@ -114,7 +116,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 3d573ec416..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 ShaderManagementConsoleWindowFactoryRequestBus::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; //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// From cbfdf99a9efab15a79cdc7ed790291921afcf706 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 3 Aug 2021 17:59:09 -0700 Subject: [PATCH 084/251] More github cleanup Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../GridMate/GridMate/Carrier/Carrier.cpp | 14 ++++---- .../GridMate/GridMate/Carrier/Carrier.h | 7 ++-- .../GridMate/Carrier/DefaultTrafficControl.h | 2 +- .../GridMate/GridMate/Carrier/Driver.h | 11 +++--- .../GridMate/GridMate/Carrier/Handshake.h | 1 - .../GridMate/Carrier/SecureSocketDriver.cpp | 6 ++-- .../GridMate/Carrier/SecureSocketDriver.h | 6 ++-- .../GridMate/Carrier/SocketDriver.cpp | 27 +++++++------- .../GridMate/GridMate/Carrier/SocketDriver.h | 12 +++---- .../GridMate/Carrier/TrafficControl.h | 1 - .../GridMate/GridMate/Carrier/Utils.h | 4 +-- .../GridMate/Drillers/CarrierDriller.cpp | 2 +- .../GridMate/Drillers/CarrierDriller.h | 2 +- .../GridMate/Drillers/ReplicaDriller.cpp | 1 - .../GridMate/Online/UserServiceTypes.h | 1 - .../GridMate/GridMate/Replica/ReplicaStatus.h | 3 +- .../GridMate/GridMate/Session/LANSession.cpp | 28 +++++++-------- .../GridMate/Session/LANSessionServiceTypes.h | 2 +- .../GridMate/GridMate/Session/Session.cpp | 36 +++++++++---------- .../GridMate/GridMate/Session/Session.h | 20 +++++------ .../GridMate/GridMate/String/StringUtils.h | 10 ------ .../GridMate/GridMate/String/string.h | 26 -------------- .../GridMate/VoiceChat/VoiceChatServiceBus.h | 1 - .../GridMate/GridMate/gridmate_files.cmake | 1 - .../GridMate/Session/LANSession_Android.cpp | 5 ++- .../GridMate/Carrier/Utils_UnixLike.cpp | 4 +-- .../WinAPI/GridMate/Carrier/Utils_WinAPI.cpp | 4 +-- .../GridMate/Session/LANSession_Linux.cpp | 5 ++- .../GridMate/String/StringUtils_Platform.h | 8 ----- .../Mac/GridMate/Session/LANSession_Mac.cpp | 5 ++- .../GridMate/Session/LANSession_Windows.cpp | 6 ++-- .../iOS/GridMate/Session/LANSession_iOS.cpp | 5 ++- Code/Framework/GridMate/Tests/Carrier.cpp | 8 ++--- .../Tests/CarrierStreamSocketDriverTests.cpp | 6 ++-- Code/Framework/GridMate/Tests/Replica.cpp | 4 +-- Code/Framework/GridMate/Tests/Serialize.cpp | 4 +-- .../Framework/GridMate/Tests/TestProfiler.cpp | 20 +++++------ 37 files changed, 125 insertions(+), 183 deletions(-) delete mode 100644 Code/Framework/GridMate/GridMate/String/StringUtils.h delete mode 100644 Code/Framework/GridMate/GridMate/String/string.h delete mode 100644 Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp index 23e967c3fa..0285a7fc02 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp @@ -422,7 +422,7 @@ namespace GridMate CarrierThread* m_threadOwner; ///< Pointer to the carrier thread that operates with this connection. AZStd::atomic m_threadConn; ///< Pointer to a thread connection. You can use it in the main thread only for a reference. - string m_fullAddress; ///< Connection full address. + AZStd::string m_fullAddress; ///< Connection full address. Carrier::ConnectionStates m_state; @@ -604,7 +604,7 @@ namespace GridMate Connection* m_connection; ThreadConnection* m_threadConnection; - string m_newConnectionAddress; + AZStd::string m_newConnectionAddress; CarrierErrorCode m_errorCode; AZ::u32 m_newRateBytesPerSec; ///< new send rate AZStd::vector > m_ackCallbacks; @@ -1007,7 +1007,7 @@ namespace GridMate unsigned int GetMessageMTU() override { return m_maxMsgDataSizeBytes; } - string ConnectionToAddress(ConnectionID id) override; + AZStd::string ConnectionToAddress(ConnectionID id) override; void SendWithCallback(const char* data, unsigned int dataSize, AZStd::unique_ptr ackCallback, ConnectionID target = AllConnections, DataReliability reliability = SEND_RELIABLE, DataPriority priority = PRIORITY_NORMAL, unsigned char channel = 0) override; void Send(const char* data, unsigned int dataSize, ConnectionID target = AllConnections, DataReliability reliability = SEND_RELIABLE, DataPriority priority = PRIORITY_NORMAL, unsigned char channel = 0) override @@ -3902,10 +3902,10 @@ CarrierImpl::DeleteConnection(Connection* conn, CarrierDisconnectReason reason) // Carrier // [9/14/2010] //========================================================================= -string +AZStd::string CarrierImpl::ConnectionToAddress(ConnectionID id) { - string str; + AZStd::string str; AZ_Assert(id != InvalidConnectionID, "Invalid connection id!"); if (id != InvalidConnectionID) { @@ -4911,7 +4911,7 @@ DefaultCarrier::Create(const CarrierDesc& desc, IGridMate* gridMate) // ReasonToString // [4/11/2011] //========================================================================= -string +AZStd::string CarrierEventsBase::ReasonToString(CarrierDisconnectReason reason) { const char* reasonStr = 0; @@ -4951,5 +4951,5 @@ CarrierEventsBase::ReasonToString(CarrierDisconnectReason reason) reasonStr = "Unknown reason"; } - return string(reasonStr); + return AZStd::string(reasonStr); } diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h index 2968582c0d..94c31ed6d2 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h +++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h @@ -9,7 +9,6 @@ #define GM_CARRIER_H #include -#include #include #include #include @@ -100,7 +99,7 @@ namespace GridMate /// Returns maximum message size (with splitting or without). Splitting will make your message reliable, which might not be optimal for Unreliable messages. It's better to send two unreliable. //virtual unsigned int GetMaxMessageSize(bool withSplitting = true) = 0; - virtual string ConnectionToAddress(ConnectionID id) = 0; + virtual AZStd::string ConnectionToAddress(ConnectionID id) = 0; /** * Sends buffer with an ACK callback. When the transport layer recieves an ACK it will run the callback. @@ -401,7 +400,7 @@ namespace GridMate public: virtual ~CarrierEventsBase() {} - string ReasonToString(CarrierDisconnectReason reason); + AZStd::string ReasonToString(CarrierDisconnectReason reason); }; class CarrierEvents @@ -517,7 +516,7 @@ namespace GridMate // Traffic control /// Called every second when you update last second statistics - virtual void OnUpdateStatistics(const GridMate::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) = 0; + virtual void OnUpdateStatistics(const AZStd::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) = 0; // Simulator /// Enable/Disable diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h index 525009b015..1d8a1f6b46 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h +++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h @@ -145,7 +145,7 @@ namespace GridMate StatisticData m_sdEffectiveLastSecond; ///< Last second statistics for effective data. StatisticData m_sdEffectiveCurrentSecond; ///< Elapsing second statistics for effective data. - string m_address; ///< Full address for this connection. (we need for debug only) + AZStd::string m_address; ///< Full address for this connection. (we need for debug only) unsigned int m_recvPacketAllowance; ///< Current allowance for number of incoming packets bool m_canReceiveData; ///< Able to receive data on this connection diff --git a/Code/Framework/GridMate/GridMate/Carrier/Driver.h b/Code/Framework/GridMate/GridMate/Carrier/Driver.h index 2c806be5e0..d6d47fc491 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/Driver.h +++ b/Code/Framework/GridMate/GridMate/Carrier/Driver.h @@ -10,10 +10,9 @@ #include -#include - #include #include +#include namespace GridMate { @@ -139,7 +138,7 @@ namespace GridMate /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data. /// Create address from ip and port. If ip == NULL we will assign a broadcast address. - virtual string IPPortToAddress(const char* ip, unsigned int port) const = 0; + virtual AZStd::string IPPortToAddress(const char* ip, unsigned int port) const = 0; virtual bool AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const = 0; /// @} @@ -188,11 +187,11 @@ namespace GridMate virtual ~DriverAddress() {} - virtual string ToString() const = 0; + virtual AZStd::string ToString() const = 0; - virtual string ToAddress() const = 0; + virtual AZStd::string ToAddress() const = 0; - virtual string GetIP() const = 0; + virtual AZStd::string GetIP() const = 0; virtual unsigned int GetPort() const = 0; diff --git a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h index ffd332b65c..0f825da49b 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h +++ b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h @@ -10,7 +10,6 @@ #include #include -#include namespace GridMate { diff --git a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp index 7d0d5644b3..031e8561ec 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp @@ -1712,7 +1712,7 @@ namespace GridMate } // Calculate HMAC of buffer using the secret and peer address - GridMate::string addrStr = endpoint->ToAddress(); + AZStd::string addrStr = endpoint->ToAddress(); unsigned char result[EVP_MAX_MD_SIZE]; unsigned int resultLen = 0; HMAC(EVP_sha1(), m_cookieSecret.m_currentSecret, sizeof(m_cookieSecret.m_currentSecret), @@ -1745,7 +1745,7 @@ namespace GridMate } // Calculate HMAC of buffer using the secret and peer address - GridMate::string addrStr = endpoint->ToAddress(); + AZStd::string addrStr = endpoint->ToAddress(); unsigned char result[EVP_MAX_MD_SIZE]; unsigned int resultLen = 0; HMAC(EVP_sha1(), m_cookieSecret.m_currentSecret, COOKIE_SECRET_LENGTH, @@ -1809,7 +1809,7 @@ namespace GridMate #ifdef AZ_DebugUseSocketDebugLog if (handshake) { - GridMate::string line = GridMate::string::format("%lld | [%08x] RawRecv %s size %d connection exists\n", AZStd::chrono::system_clock::now().time_since_epoch().count(), this, type, bytesReceived); + AZStd::string line = AZStd::string::format("%lld | [%08x] RawRecv %s size %d connection exists\n", AZStd::chrono::system_clock::now().time_since_epoch().count(), this, type, bytesReceived); connection->m_dbgLog += line; } #endif diff --git a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h index 529ccea408..76b7958085 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h +++ b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h @@ -23,7 +23,7 @@ //#define AZ_DebugSecureSocket AZ_TracePrintf //#define AZ_DebugSecureSocketConnection(window, fmt, ...) \ //{\ -// GridMate::string line = GridMate::string::format(fmt, __VA_ARGS__);\ +// AZStd::string line = AZStd::string::format(fmt, __VA_ARGS__);\ // this->m_dbgLog += line;\ //} @@ -226,7 +226,7 @@ namespace GridMate int m_dbgDgramsReceived; int m_dbgPort; #ifdef AZ_DebugUseSocketDebugLog - GridMate::string m_dbgLog; + AZStd::string m_dbgLog; #endif }; @@ -262,7 +262,7 @@ namespace GridMate AZ::u32 m_maxTempBufferSize; AZStd::queue m_globalInQueue; AZStd::unordered_map m_connections; - AZStd::unordered_map m_ipToNumConnections; + AZStd::unordered_map m_ipToNumConnections; SecureSocketDesc m_desc; AZStd::chrono::system_clock::time_point m_lastTimerCheck; ///Time last timers were checked }; diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp index fc3062062c..6acf778798 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp @@ -18,7 +18,6 @@ //#define AZ_LOG_UNBOUND_SEND_RECEIVE #include -#include #include #include @@ -575,7 +574,7 @@ namespace GridMate return !(*this == rhs); } - string SocketDriverAddress::ToString() const + AZStd::string SocketDriverAddress::ToString() const { char ip[64]; unsigned short port; @@ -590,15 +589,15 @@ namespace GridMate port = ntohs(m_sockAddr.sin_port); } - return string::format("%s|%d", ip, port); + return AZStd::string::format("%s|%d", ip, port); } - string SocketDriverAddress::ToAddress() const + AZStd::string SocketDriverAddress::ToAddress() const { return ToString(); } - string SocketDriverAddress::GetIP() const + AZStd::string SocketDriverAddress::GetIP() const { char ip[64]; if (m_sockAddr.sin_family == AF_INET6) @@ -609,7 +608,7 @@ namespace GridMate { inet_ntop(AF_INET, const_cast(reinterpret_cast(&m_sockAddr.sin_addr)), ip, AZ_ARRAY_SIZE(ip)); } - return string(ip); + return AZStd::string(ip); } unsigned int SocketDriverAddress::GetPort() const @@ -1144,11 +1143,11 @@ namespace GridMate // CreateSocketDriver // [3/4/2013] //========================================================================= - string + AZStd::string SocketDriverCommon::IPPortToAddressString(const char* ip, unsigned int port) { AZ_Assert(ip != nullptr, "Invalid address!"); - return string::format("%s|%d", ip, port); + return AZStd::string::format("%s|%d", ip, port); } //========================================================================= @@ -1159,14 +1158,14 @@ namespace GridMate SocketDriverCommon::AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) { AZStd::size_t pos = address.find('|'); - AZ_Assert(pos != string::npos, "Invalid driver address!"); - if (pos == string::npos) + AZ_Assert(pos != AZStd::string::npos, "Invalid driver address!"); + if (pos == AZStd::string::npos) { return false; } - ip = string(address.begin(), address.begin() + pos); - port = AZStd::stoi(string(address.begin() + pos + 1, address.end())); + ip = AZStd::string(address.begin(), address.begin() + pos); + port = AZStd::stoi(AZStd::string(address.begin() + pos + 1, address.end())); return true; } @@ -1180,12 +1179,12 @@ namespace GridMate { // TODO: We can/should use inet_ntop() to detect the family type AZStd::size_t pos = ip.find("."); - if (pos != string::npos) + if (pos != AZStd::string::npos) { return BSD_AF_INET; } pos = ip.find("::"); - if (pos != string::npos) + if (pos != AZStd::string::npos) { return BSD_AF_INET6; } diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h index 7555c92639..835414b374 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h +++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h @@ -88,9 +88,9 @@ namespace GridMate bool operator==(const SocketDriverAddress& rhs) const; bool operator!=(const SocketDriverAddress& rhs) const; - virtual string ToString() const; - virtual string ToAddress() const; - virtual string GetIP() const; + virtual AZStd::string ToString() const; + virtual AZStd::string ToAddress() const; + virtual AZStd::string GetIP() const; virtual unsigned int GetPort() const; virtual const void* GetTargetAddress(unsigned int& addressSize) const; @@ -163,15 +163,15 @@ namespace GridMate /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data. /// Create address from ip and port. If ip == NULL we will assign a broadcast address. - virtual string IPPortToAddress(const char* ip, unsigned int port) const { return IPPortToAddressString(ip, port); } + virtual AZStd::string IPPortToAddress(const char* ip, unsigned int port) const { return IPPortToAddressString(ip, port); } virtual bool AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const { return AddressStringToIPPort(address, ip, port); } /// Create address for the socket driver from IP and port - static string IPPortToAddressString(const char* ip, unsigned int port); + static AZStd::string IPPortToAddressString(const char* ip, unsigned int port); /// Decompose an address to IP and port static bool AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port); /// Return the family type of the address (AF_INET,AF_INET6 AF_UNSPEC) static BSDSocketFamilyType AddressFamilyType(const AZStd::string& ip); - static BSDSocketFamilyType AddressFamilyType(const char* ip) { return AddressFamilyType(string(ip)); } + static BSDSocketFamilyType AddressFamilyType(const char* ip) { return AddressFamilyType(AZStd::string(ip)); } /// @} virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address) = 0; diff --git a/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h b/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h index 2b49f320b5..7b79124a73 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h +++ b/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h @@ -9,7 +9,6 @@ #define GM_TRAFFIC_CONTROL_H #include -#include #include diff --git a/Code/Framework/GridMate/GridMate/Carrier/Utils.h b/Code/Framework/GridMate/GridMate/Carrier/Utils.h index 2b15696ac2..db58ec979e 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/Utils.h +++ b/Code/Framework/GridMate/GridMate/Carrier/Utils.h @@ -8,14 +8,14 @@ #ifndef GM_CARRIER_UTILS_H #define GM_CARRIER_UTILS_H -#include +#include namespace GridMate { namespace Utils { ///< Returns the machines address(ip) in a string. familyType is platform dependent. - string GetMachineAddress(int familyType = 0); + AZStd::string GetMachineAddress(int familyType = 0); ///< Returns a broadcast address based on a family type. On ipv6 we emulate broadbast using the multicast on the all nodes address (FF02::1). familyType is platform dependent. const char* GetBroadcastAddress(int familyType = 0); } diff --git a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp index 528afa6cce..38f029f0f5 100644 --- a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp +++ b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp @@ -64,7 +64,7 @@ namespace GridMate // OnUpdateStatistics // [4/14/2011] //========================================================================= - void CarrierDriller::OnUpdateStatistics(const GridMate::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) + void CarrierDriller::OnUpdateStatistics(const AZStd::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) { m_output->BeginTag(m_drillerTag); m_output->BeginTag(AZ_CRC("Statistics", 0xe2d38b22)); diff --git a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h index bb3cb1e3b2..b12441e6fa 100644 --- a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h +++ b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h @@ -42,7 +42,7 @@ namespace GridMate ////////////////////////////////////////////////////////////////////////// // Carrier Driller Bus - void OnUpdateStatistics(const GridMate::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) override; + void OnUpdateStatistics(const AZStd::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) override; void OnConnectionStateChanged(Carrier* carrier, ConnectionID id, Carrier::ConnectionStates newState) override; ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp b/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp index e70aceabc9..cb48578255 100644 --- a/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp +++ b/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp @@ -9,7 +9,6 @@ #include #include #include -#include using namespace AZ::Debug; diff --git a/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h b/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h index 2617d98d73..c1753b3bb2 100644 --- a/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h +++ b/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h @@ -9,7 +9,6 @@ #define GM_USER_SERVICE_TYPES_H #include -#include namespace GridMate { diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h index 019a595f6f..aeb5c1b2bb 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h @@ -12,7 +12,6 @@ #include #include #include -#include #include namespace GridMate @@ -102,7 +101,7 @@ namespace GridMate }; AZ::u8 m_flags; - string m_replicaName; + AZStd::string m_replicaName; }; DataSet m_options; // Flags and debug info diff --git a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp index 0127d8fa23..e4e1c9e9b6 100644 --- a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp +++ b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp @@ -52,17 +52,17 @@ namespace GridMate MemberIDCompact GetID() const { return m_id; } - virtual string ToString() const + virtual AZStd::string ToString() const { - return string::format("%x", m_id); + return AZStd::string::format("%x", m_id); } - virtual string ToAddress() const { return m_address; } + virtual AZStd::string ToAddress() const { return m_address; } virtual MemberIDCompact Compact() const { return m_id; } virtual bool IsValid() const { return m_id != 0; } private: MemberIDCompact m_id; - string m_address; + AZStd::string m_address; }; class LANMemberIDMarshaler @@ -141,7 +141,7 @@ namespace GridMate bool MatchMake(const LANSearchParams& sp); - string MakeSessionId(); + AZStd::string MakeSessionId(); Driver* m_driver; ///< Driver for network searches @@ -199,7 +199,7 @@ namespace GridMate : public CtorContextBase { CtorDataSet m_memberId; - CtorDataSet m_memberAddress; ///< As the server/host sees it! + CtorDataSet m_memberAddress; ///< As the server/host sees it! CtorDataSet m_peerMode; CtorDataSet m_isHost; }; @@ -232,7 +232,7 @@ namespace GridMate AZ_Assert(session, "We need to have a valid session!"); LANMember* member; MemberIDCompact memberId = ctorContext.m_memberId.Get(); - string memberAddress = ctorContext.m_memberAddress.Get(); + AZStd::string memberAddress = ctorContext.m_memberAddress.Get(); RemotePeerMode remotePeerMode = ctorContext.m_peerMode.Get(); bool isMemberHost = ctorContext.m_isHost.Get(); @@ -349,7 +349,7 @@ namespace GridMate { namespace Platform { - void AssignExtendedName(GridMate::string& extendedName); + void AssignExtendedName(AZStd::string& extendedName); } } @@ -364,7 +364,7 @@ LANMember::LANMember(const LANMemberID& id, LANSession* session) : GridMember(id.Compact()) , m_memberId(id) { - string extendedName; + AZStd::string extendedName; Platform::AssignExtendedName(extendedName); m_session = session; @@ -741,8 +741,8 @@ LANSession::CreateLocalMember(bool isHost, bool isInvited, RemotePeerMode peerMo { AZ_Assert(m_myMember == nullptr, "We already have added a local member!"); - string ip = Utils::GetMachineAddress(m_carrierDesc.m_familyType); - string address = SocketDriverCommon::IPPortToAddressString(ip.c_str(), m_carrierDesc.m_port); + AZStd::string ip = Utils::GetMachineAddress(m_carrierDesc.m_familyType); + AZStd::string address = SocketDriverCommon::IPPortToAddressString(ip.c_str(), m_carrierDesc.m_port); ///////////////////////////////////////////////////////////////////////////// // TODO: Use the UUID as an ID, we will need to add marshalers and so on AZ::Uuid uuid = AZ::Uuid::CreateRandom(); @@ -881,7 +881,7 @@ LANSession::OnStateHostMigrateSession(AZ::HSM& sm, const AZ::HSM::Event& e) if (m_driver->Initialize(Driver::BSD_AF_INET, nullptr, hostPort, true) != Driver::EC_OK) { // check the output for more info - string errorMsg = string::format("Failed to initialize socket at port %d!", hostPort); + AZStd::string errorMsg = AZStd::string::format("Failed to initialize socket at port %d!", hostPort); EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnSessionError, this, errorMsg); EBUS_EVENT_ID(m_gridMate, SessionEventBus, OnSessionError, this, errorMsg); // We can't be a real host if we failed to provide matching services. @@ -899,7 +899,7 @@ LANSession::OnStateHostMigrateSession(AZ::HSM& sm, const AZ::HSM::Event& e) // MakeSessionId // [3/7/2013] //========================================================================= -string +AZStd::string LANSession::MakeSessionId() { char temp[64]; @@ -990,7 +990,7 @@ LANSearch::Update() wb.Write(m_searchParams.m_params[i].m_type); } - string serverAddress = m_searchParams.m_serverAddress; + AZStd::string serverAddress = m_searchParams.m_serverAddress; if (serverAddress.empty()) { serverAddress = Utils::GetBroadcastAddress(m_searchParams.m_familyType); diff --git a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h index 20ade42a6e..42524e034a 100644 --- a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h +++ b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h @@ -20,7 +20,7 @@ namespace GridMate : m_port (0) // by default session can't be found (searched for) {} - string m_address; /// empty to accept any address otherwise you can provide a specific bind address. + AZStd::string m_address; /// empty to accept any address otherwise you can provide a specific bind address. /** * Use 0 if you don't want you session to be searchable (default) * Port on which we will register the LAN session (it will be used for session communication and should be different than the game/carrier one). diff --git a/Code/Framework/GridMate/GridMate/Session/Session.cpp b/Code/Framework/GridMate/GridMate/Session/Session.cpp index 8a9bdea273..471e21127c 100644 --- a/Code/Framework/GridMate/GridMate/Session/Session.cpp +++ b/Code/Framework/GridMate/GridMate/Session/Session.cpp @@ -60,7 +60,7 @@ namespace GridMate typedef vector NewConnectionsType; typedef vector UserDataBufferType; - typedef unordered_set AddressSetType; + typedef unordered_set AddressSetType; GridSessionHandshake(unsigned int handshakeTimeoutMS, const VersionType& version); virtual ~GridSessionHandshake() {} @@ -99,12 +99,12 @@ namespace GridMate virtual unsigned int GetHandshakeTimeOutMS() const { return m_handshakeTimeOutMS; } ////////////////////////////////////////////////////////////////////////// - void BanAddress(string address); + void BanAddress(AZStd::string address); void SetHost(bool isHost); void SetInvited(bool isInvited); void SetHostMigration(bool isMigrating); void SetUserData(const void* data, size_t dataSize); - void SetSessionId(string sessionId); + void SetSessionId(AZStd::string sessionId); bool IsNewConnections() { return !m_newConnections.empty(); } NewConnectionsType& AcquireNewConnections(); void ReleaseNewConnections(); @@ -117,7 +117,7 @@ namespace GridMate NewConnectionsType m_newConnections; AddressSetType m_banList; UserDataBufferType m_userData; - string m_sessionId; + AZStd::string m_sessionId; RemotePeerMode m_peerMode; VersionType m_version; @@ -165,7 +165,7 @@ void GridSessionParam::SetValue(AZ::s32* values, size_t numElements) if (numElements > 0) { AZ_Assert(values != nullptr, "Invalid values pointer!"); - string temp; + AZStd::string temp; for (size_t i = 0; i < numElements; ++i) { AZStd::to_string(temp, values[i]); @@ -183,7 +183,7 @@ void GridSessionParam::SetValue(AZ::s64* values, size_t numElements) if (numElements > 0) { AZ_Assert(values != nullptr, "Invalid values pointer!"); - string temp; + AZStd::string temp; for (size_t i = 0; i < numElements; ++i) { AZStd::to_string(temp, values[i]); @@ -201,7 +201,7 @@ void GridSessionParam::SetValue(float* values, size_t numElements) if (numElements > 0) { AZ_Assert(values != nullptr, "Invalid values pointer!"); - string temp; + AZStd::string temp; for (size_t i = 0; i < numElements; ++i) { AZStd::to_string(temp, values[i]); @@ -219,7 +219,7 @@ void GridSessionParam::SetValue(double* values, size_t numElements) if (numElements > 0) { AZ_Assert(values != nullptr, "Invalid values pointer!"); - string temp; + AZStd::string temp; for (size_t i = 0; i < numElements; ++i) { AZStd::to_string(temp, values[i]); @@ -726,7 +726,7 @@ GridSession::RemoveParam(unsigned int index) { const GridSessionReplica::ParamContainer& curParams = m_state->m_params.Get(); const GridSessionParam& foundParam = curParams.at(index); - string paramId = foundParam.m_id; + AZStd::string paramId = foundParam.m_id; m_state->m_params.Modify([=](Internal::GridSessionReplica::ParamContainer& params) { params.erase(¶ms.at(index)); @@ -1220,7 +1220,7 @@ GridSession::OnDriverError(Carrier* carrier, ConnectionID id, const DriverError& return; // not for us } uintptr_t idInt = reinterpret_cast(static_cast(id)); - string errorMsg = string::format("Carrier driver error ConnectionID: %" PRIuPTR "ErrorCode: 0x%08x", idInt, error.m_errorCode); + AZStd::string errorMsg = AZStd::string::format("Carrier driver error ConnectionID: %" PRIuPTR "ErrorCode: 0x%08x", idInt, error.m_errorCode); EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnSessionError, this, errorMsg); EBUS_EVENT_ID(m_gridMate, SessionEventBus, OnSessionError, this, errorMsg); @@ -1248,7 +1248,7 @@ GridSession::OnSecurityError(Carrier* carrier, ConnectionID id, const SecurityEr return; // not for us } uintptr_t idInt = reinterpret_cast(static_cast(id)); - string errorMsg = string::format("Carrier security error ConnectionID: %" PRIuPTR " ErrorCode: 0x%08x", idInt, error.m_errorCode); + AZStd::string errorMsg = AZStd::string::format("Carrier security error ConnectionID: %" PRIuPTR " ErrorCode: 0x%08x", idInt, error.m_errorCode); EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnSessionError, this, errorMsg); } @@ -1976,7 +1976,7 @@ GridMember::GetNatType() const //========================================================================= // GetName //========================================================================= -string +AZStd::string GridMember::GetName() const { return m_clientState ? m_clientState->m_name.Get().c_str() : "Unknown"; @@ -2244,7 +2244,7 @@ GridMember::GetProcessId() const //========================================================================= // GetMachineName //========================================================================= -string +AZStd::string GridMember::GetMachineName() const { if (m_clientState) @@ -2253,7 +2253,7 @@ GridMember::GetMachineName() const } else { - return string(); + return AZStd::string(); } } @@ -2688,7 +2688,7 @@ HandshakeErrorCode GridSessionHandshake::OnReceiveRequest(ConnectionID id, ReadB { (void)id; AZStd::lock_guard l(m_dataLock); - string sessionId; + AZStd::string sessionId; bool isInvited = false; RemotePeerMode peerMode; VersionType version; @@ -2761,7 +2761,7 @@ bool GridSessionHandshake::OnConfirmRequest(ConnectionID id, ReadBuffer& rb) (void)id; AZStd::lock_guard l(m_dataLock); - string sessionId; + AZStd::string sessionId; if (!rb.Read(sessionId)) { return false; @@ -2818,7 +2818,7 @@ void GridSessionHandshake::OnDisconnect(ConnectionID id) //========================================================================= // BanAddress //========================================================================= -void GridSessionHandshake::BanAddress(string address) +void GridSessionHandshake::BanAddress(AZStd::string address) { AZStd::lock_guard l(m_dataLock); m_banList.insert(address); @@ -2864,7 +2864,7 @@ void GridSessionHandshake::SetUserData(const void* data, size_t dataSize) //========================================================================= // SetSessionId //========================================================================= -void GridSessionHandshake::SetSessionId(string sessionId) +void GridSessionHandshake::SetSessionId(AZStd::string sessionId) { AZStd::lock_guard l(m_dataLock); m_sessionId = sessionId; diff --git a/Code/Framework/GridMate/GridMate/Session/Session.h b/Code/Framework/GridMate/GridMate/Session/Session.h index 03556756ba..5080570373 100644 --- a/Code/Framework/GridMate/GridMate/Session/Session.h +++ b/Code/Framework/GridMate/GridMate/Session/Session.h @@ -39,8 +39,8 @@ namespace GridMate struct MemberID { virtual ~MemberID() {} - virtual string ToString() const = 0; - virtual string ToAddress() const = 0; + virtual AZStd::string ToString() const = 0; + virtual AZStd::string ToAddress() const = 0; virtual MemberIDCompact Compact() const = 0; virtual bool IsValid() const = 0; @@ -50,7 +50,7 @@ namespace GridMate AZ_FORCE_INLINE bool operator!=(const MemberIDCompact& rhs) const { return Compact() != rhs; } }; - typedef string SessionID; + typedef AZStd::string SessionID; struct SearchInfo; @@ -87,8 +87,8 @@ namespace GridMate void SetValue(float* values, size_t numElements); void SetValue(double* values, size_t numElements); - string m_id; - string m_value; + AZStd::string m_id; + AZStd::string m_value; AZ::u8 m_type; AZ_FORCE_INLINE bool operator==(const GridSessionParam& rhs) const { return m_type == rhs.m_type && m_id == rhs.m_id && m_value == rhs.m_value; } @@ -303,7 +303,7 @@ namespace GridMate virtual const PlayerId* GetPlayerId() const = 0; NatType GetNatType() const; - string GetName() const; + AZStd::string GetName() const; GridSession* GetSession() const { return m_session; } @@ -353,7 +353,7 @@ namespace GridMate //@{ Platform information AZ::PlatformID GetPlatformId() const; AZ::u32 GetProcessId() const; - string GetMachineName() const; + AZStd::string GetMachineName() const; //@} protected: @@ -568,7 +568,7 @@ namespace GridMate Internal::GridSessionHandshake* m_handshake; typedef unordered_set ConnectionIDSet; ConnectionIDSet m_connections; - string m_hostAddress; + AZStd::string m_hostAddress; bool m_isShutdown; GridMember* m_myMember; ///< Created with the session and bound when the server replica arrives. @@ -923,14 +923,14 @@ namespace GridMate DataSet m_numConnections; DataSet m_natType; - DataSet m_name; + DataSet m_name; DataSet m_memberId; DataSet m_newHostVote; ///< Used when in host migration, to cast machine's vote. MuteDataSetType m_muteList; ///< List of all players we have muted. // Platform and application informational data DataSet > m_platformId; - DataSet m_machineName; + DataSet m_machineName; DataSet m_processId; DataSet m_isInvited; }; diff --git a/Code/Framework/GridMate/GridMate/String/StringUtils.h b/Code/Framework/GridMate/GridMate/String/StringUtils.h deleted file mode 100644 index 6f1ca89b0b..0000000000 --- a/Code/Framework/GridMate/GridMate/String/StringUtils.h +++ /dev/null @@ -1,10 +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 diff --git a/Code/Framework/GridMate/GridMate/String/string.h b/Code/Framework/GridMate/GridMate/String/string.h deleted file mode 100644 index 779f5034c5..0000000000 --- a/Code/Framework/GridMate/GridMate/String/string.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 - * - */ -#ifndef GM_CONTAINERS_STRING_H -#define GM_CONTAINERS_STRING_H - -#include -#include -#include // for getting from string->wstring and backwards - -namespace GridMate -{ - /** - * All libs should use specialized allocators - */ - typedef AZStd::basic_string, SysContAlloc > string; - typedef AZStd::basic_string, SysContAlloc > wstring; - - typedef AZStd::basic_string, GridMateStdAlloc > gridmate_string; - typedef AZStd::basic_string, GridMateStdAlloc > gridmate_wstring; -} -#endif // GM_CONTAINERS_STRING_H diff --git a/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h b/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h index 98fcd48b85..b5c09a411a 100644 --- a/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h +++ b/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h @@ -10,7 +10,6 @@ #include #include -#include namespace GridMate { diff --git a/Code/Framework/GridMate/GridMate/gridmate_files.cmake b/Code/Framework/GridMate/GridMate/gridmate_files.cmake index 8c94fe80ad..e318a8adcd 100644 --- a/Code/Framework/GridMate/GridMate/gridmate_files.cmake +++ b/Code/Framework/GridMate/GridMate/gridmate_files.cmake @@ -120,6 +120,5 @@ set(FILES Session/Session.cpp Session/Session.h Session/SessionServiceBus.h - String/string.h VoiceChat/VoiceChatServiceBus.h ) diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp index e70e839d42..05fb56dfc1 100644 --- a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp +++ b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp @@ -6,19 +6,18 @@ * */ -#include #include namespace GridMate { namespace Platform { - void AssignExtendedName(GridMate::string& extendedName) + void AssignExtendedName(AZStd::string& extendedName) { char hostName[64]; gethostname(hostName, AZ_ARRAY_SIZE(hostName)); - extendedName = GridMate::string::format("%s", hostName); + extendedName = AZStd::string::format("%s", hostName); } } } diff --git a/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp b/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp index ea824e7564..7d04ff640b 100644 --- a/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp +++ b/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp @@ -18,9 +18,9 @@ namespace GridMate { - string Utils::GetMachineAddress(int familyType) + AZStd::string Utils::GetMachineAddress(int familyType) { - string machineName; + AZStd::string machineName; struct ifaddrs* ifAddrStruct = nullptr; struct ifaddrs* ifa = nullptr; diff --git a/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp b/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp index dd9b737180..095f8ba6c7 100644 --- a/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp +++ b/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp @@ -16,9 +16,9 @@ namespace GridMate { - string Utils::GetMachineAddress(int familyType) + AZStd::string Utils::GetMachineAddress(int familyType) { - string machineName; + AZStd::string machineName; char name[MAX_PATH]; int result = gethostname(name, sizeof(name)); AZ_Error("GridMate", result == 0, "Failed in gethostname with result=%d, WSAGetLastError=%d!", result, WSAGetLastError()); diff --git a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp index e70e839d42..05fb56dfc1 100644 --- a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp +++ b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp @@ -6,19 +6,18 @@ * */ -#include #include namespace GridMate { namespace Platform { - void AssignExtendedName(GridMate::string& extendedName) + void AssignExtendedName(AZStd::string& extendedName) { char hostName[64]; gethostname(hostName, AZ_ARRAY_SIZE(hostName)); - extendedName = GridMate::string::format("%s", hostName); + extendedName = AZStd::string::format("%s", hostName); } } } diff --git a/Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h b/Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h deleted file mode 100644 index 03320d1dd8..0000000000 --- a/Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h +++ /dev/null @@ -1,8 +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 diff --git a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp index e70e839d42..05fb56dfc1 100644 --- a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp +++ b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp @@ -6,19 +6,18 @@ * */ -#include #include namespace GridMate { namespace Platform { - void AssignExtendedName(GridMate::string& extendedName) + void AssignExtendedName(AZStd::string& extendedName) { char hostName[64]; gethostname(hostName, AZ_ARRAY_SIZE(hostName)); - extendedName = GridMate::string::format("%s", hostName); + extendedName = AZStd::string::format("%s", hostName); } } } diff --git a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp index 59a1c65781..8925746a79 100644 --- a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp +++ b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp @@ -6,15 +6,15 @@ * */ -#include #include #include +#include namespace GridMate { namespace Platform { - void AssignExtendedName(GridMate::string& extendedName) + void AssignExtendedName(AZStd::string& extendedName) { char hostName[64]; gethostname(hostName, AZ_ARRAY_SIZE(hostName)); @@ -31,7 +31,7 @@ namespace GridMate azsnprintf(procName, AZ_ARRAY_SIZE(procName), "Unknown"); } - extendedName = GridMate::string::format("%s::%s", hostName, procName); + extendedName = AZStd::string::format("%s::%s", hostName, procName); } } } diff --git a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp index e70e839d42..05fb56dfc1 100644 --- a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp +++ b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp @@ -6,19 +6,18 @@ * */ -#include #include namespace GridMate { namespace Platform { - void AssignExtendedName(GridMate::string& extendedName) + void AssignExtendedName(AZStd::string& extendedName) { char hostName[64]; gethostname(hostName, AZ_ARRAY_SIZE(hostName)); - extendedName = GridMate::string::format("%s", hostName); + extendedName = AZStd::string::format("%s", hostName); } } } diff --git a/Code/Framework/GridMate/Tests/Carrier.cpp b/Code/Framework/GridMate/Tests/Carrier.cpp index 45cb16dbb2..8d3ec4eef6 100644 --- a/Code/Framework/GridMate/Tests/Carrier.cpp +++ b/Code/Framework/GridMate/Tests/Carrier.cpp @@ -193,7 +193,7 @@ namespace UnitTest CarrierCallbacksHandler clientCB, serverCB; TestCarrierDesc serverCarrierDesc, clientCarrierDesc; - string str("Hello this is a carrier test!"); + AZStd::string str("Hello this is a carrier test!"); const char* targetAddress = "127.0.0.1"; @@ -377,7 +377,7 @@ namespace UnitTest CarrierCallbacksHandler clientCB, serverCB; TestCarrierDesc serverCarrierDesc, clientCarrierDesc; - string str("Hello this is a carrier test!"); + AZStd::string str("Hello this is a carrier test!"); clientCarrierDesc.m_driver = SocketProvider::CreateDriverForJoin(); serverCarrierDesc.m_driver = SocketProvider::CreateDriverForHost(); @@ -469,7 +469,7 @@ namespace UnitTest CarrierCallbacksHandler clientCB, serverCB; TestCarrierDesc serverCarrierDesc, clientCarrierDesc; - string str("Hello this is a carrier stress test!"); + AZStd::string str("Hello this is a carrier stress test!"); clientCarrierDesc.m_enableDisconnectDetection = false; serverCarrierDesc.m_enableDisconnectDetection = false; @@ -1401,7 +1401,7 @@ namespace UnitTest CarrierCallbacksHandler clientCB, serverCB; CarrierDesc serverCarrierDesc, clientCarrierDesc; - string str("Hello this is a carrier test!"); + AZStd::string str("Hello this is a carrier test!"); const char* targetAddress = "127.0.0.1"; diff --git a/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp b/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp index aac15562df..6af6a6ab87 100644 --- a/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp +++ b/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp @@ -188,7 +188,7 @@ namespace UnitTest CarrierStreamCallbacksHandler clientCB, serverCB; TestCarrierDesc serverCarrierDesc, clientCarrierDesc; - string str("Hello this is a carrier test!"); + AZStd::string str("Hello this is a carrier test!"); const char* targetAddress = "127.0.0.1"; @@ -374,7 +374,7 @@ namespace UnitTest CarrierStreamCallbacksHandler clientCB, serverCB; TestCarrierDesc serverCarrierDesc, clientCarrierDesc; - string str("Hello this is a carrier test!"); + AZStd::string str("Hello this is a carrier test!"); clientCarrierDesc.m_driver = CreateDriverForJoin(clientCarrierDesc); serverCarrierDesc.m_driver = CreateDriverForHost(serverCarrierDesc); @@ -475,7 +475,7 @@ namespace UnitTest CarrierStreamCallbacksHandler clientCB, serverCB; UnitTest::TestCarrierDesc serverCarrierDesc, clientCarrierDesc; - string str("Hello this is a carrier stress test!"); + AZStd::string str("Hello this is a carrier stress test!"); clientCarrierDesc.m_enableDisconnectDetection = /*false*/ true; serverCarrierDesc.m_enableDisconnectDetection = /*false*/ true; diff --git a/Code/Framework/GridMate/Tests/Replica.cpp b/Code/Framework/GridMate/Tests/Replica.cpp index 0b8fab10ce..83a3a1f5a1 100644 --- a/Code/Framework/GridMate/Tests/Replica.cpp +++ b/Code/Framework/GridMate/Tests/Replica.cpp @@ -3687,7 +3687,7 @@ public: void Touch() { - string randomStr; + AZStd::string randomStr; for (unsigned i = 0; i < k_strSize; ++i) { randomStr += 'a' + (rand() % 26); @@ -3698,7 +3698,7 @@ public: bool IsReplicaMigratable() override { return false; } static const unsigned k_strSize = 64; - DataSet m_value; + DataSet m_value; }; void run() diff --git a/Code/Framework/GridMate/Tests/Serialize.cpp b/Code/Framework/GridMate/Tests/Serialize.cpp index 4c74e9526a..9a681dc018 100644 --- a/Code/Framework/GridMate/Tests/Serialize.cpp +++ b/Code/Framework/GridMate/Tests/Serialize.cpp @@ -471,12 +471,12 @@ namespace UnitTest // ------------------------------------ // String { - string s = "hello"; + AZStd::string s = "hello"; wb.Write(s); AZ_TEST_ASSERT(wb.Size() == s.length() + sizeof(AZ::u16)); - string rs; + AZStd::string rs; rb = ReadBuffer(wb.GetEndianType(), wb.Get(), wb.Size()); rb.Read(rs); AZ_TEST_ASSERT(rs == s); diff --git a/Code/Framework/GridMate/Tests/TestProfiler.cpp b/Code/Framework/GridMate/Tests/TestProfiler.cpp index 9f79d5a9fe..26e9312ecf 100644 --- a/Code/Framework/GridMate/Tests/TestProfiler.cpp +++ b/Code/Framework/GridMate/Tests/TestProfiler.cpp @@ -34,15 +34,15 @@ static bool CollectPerformanceCounters(const AZ::Debug::ProfilerRegister& reg, c return true; } -static string FormatString(const AZStd::string& pre, const AZStd::string& name, const AZStd::string& post, AZ::u64 time, AZ::u64 calls) +static AZStd::string FormatString(const AZStd::string& pre, const AZStd::string& name, const AZStd::string& post, AZ::u64 time, AZ::u64 calls) { - string units = "us"; + AZStd::string units = "us"; if (AZ::u64 divtime = time / 1000) { time = divtime; units = "ms"; } - return string::format("%s%s %s %10llu%s (%llu calls)\n", pre.c_str(), name.c_str(), post.c_str(), time, units.c_str(), calls); + return AZStd::string::format("%s%s %s %10llu%s (%llu calls)\n", pre.c_str(), name.c_str(), post.c_str(), time, units.c_str(), calls); } struct TotalSortContainer @@ -56,28 +56,28 @@ struct TotalSortContainer { if (m_self && level >= 0) { - string levelIndent; + AZStd::string levelIndent; for (AZ::s32 i = 0; i < level; i++) { levelIndent += (i == level - 1) ? "+---" : "| "; } - string name = m_self->m_name ? m_self->m_name : m_self->m_function; - string outputTotal = FormatString(levelIndent, name, " Total:", m_self->m_timeData.m_time, m_self->m_timeData.m_calls); + AZStd::string name = m_self->m_name ? m_self->m_name : m_self->m_function; + AZStd::string outputTotal = FormatString(levelIndent, name, " Total:", m_self->m_timeData.m_time, m_self->m_timeData.m_calls); AZ_Printf(systemId, outputTotal.c_str()); if (m_self->m_timeData.m_childrenTime || m_self->m_timeData.m_childrenCalls) { - string childIndent = levelIndent; + AZStd::string childIndent = levelIndent; for (auto i = name.begin(); i != name.end(); ++i) { childIndent += " "; } childIndent[level * 4] = '|'; - string outputChild = FormatString(childIndent, "", "Child:", m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_childrenCalls); + AZStd::string outputChild = FormatString(childIndent, "", "Child:", m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_childrenCalls); AZ_Printf(systemId, outputChild.c_str()); - string outputSelf = FormatString(childIndent, "", "Self :", m_self->m_timeData.m_time - m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_calls); + AZStd::string outputSelf = FormatString(childIndent, "", "Self :", m_self->m_timeData.m_time - m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_calls); AZ_Printf(systemId, outputSelf.c_str()); } } @@ -237,7 +237,7 @@ void TestProfiler::PrintProfilingSelf(const char* systemId) AZ_Printf(systemId, "Profiling timers by exclusive execution time:\n"); for (auto profiler : selfSorted) { - string str = FormatString("", profiler->m_name ? profiler->m_name : profiler->m_function, "Self Time:", + AZStd::string str = FormatString("", profiler->m_name ? profiler->m_name : profiler->m_function, "Self Time:", profiler->m_timeData.m_time - profiler->m_timeData.m_childrenTime, profiler->m_timeData.m_calls); AZ_Printf(systemId, str.c_str()); } From e28602dbbb4a09a389f0519ed680fc051a5d59cb Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 3 Aug 2021 17:59:35 -0700 Subject: [PATCH 085/251] linux fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Export/ExportManager.cpp | 6 +- Code/Editor/TrackView/CommentNodeAnimator.cpp | 2 +- .../TrackView/TrackViewDopeSheetBase.cpp | 6 +- Code/Editor/TrackView/TrackViewNodes.cpp | 2 +- Code/Editor/Util/FileUtil.cpp | 9 +- Code/Editor/Util/PathUtil.cpp | 13 +-- Code/Editor/Util/PathUtil.h | 4 +- Code/Editor/Util/StringHelpers.cpp | 2 +- Code/Editor/Util/StringHelpers.h | 3 + Code/Framework/AzCore/AzCore/base.h | 108 +++++++++--------- .../AzCore/AzCore/std/string/conversions.h | 34 +----- .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp | 7 +- .../AzFramework/IO/LocalFileIO_WinAPI.cpp | 6 +- Code/Legacy/CryCommon/CryFile.h | 8 +- Code/Legacy/CryCommon/CryListenerSet.h | 2 +- Code/Legacy/CryCommon/CryName.h | 8 +- Code/Legacy/CryCommon/CryPath.h | 2 +- Code/Legacy/CryCommon/ISerialize.h | 4 +- Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 4 +- Code/Legacy/CryCommon/WinBase.cpp | 57 ++++----- Code/Legacy/CrySystem/DebugCallStack.cpp | 22 ++-- Code/Legacy/CrySystem/IDebugCallStack.cpp | 2 +- Code/Legacy/CrySystem/IDebugCallStack.h | 6 +- .../CrySystem/LevelSystem/LevelSystem.cpp | 2 +- .../CrySystem/LocalizedStringManager.cpp | 4 +- Code/Legacy/CrySystem/Log.cpp | 8 +- Code/Legacy/CrySystem/SystemWin32.cpp | 2 +- Code/Legacy/CrySystem/XConsole.cpp | 16 +-- Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp | 2 +- Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp | 2 +- Code/Tools/GridHub/GridHub/gridhub.cpp | 4 +- Code/Tools/GridHub/GridHub/gridhub.hxx | 2 +- .../Process/TestImpactWin32_Process.cpp | 7 +- .../Animation/UiAnimViewDopeSheetBase.cpp | 6 +- .../UiClipboard_Unimplemented.cpp | 7 +- .../Code/Source/Cinematics/CaptureTrack.cpp | 2 +- .../Code/Source/Cinematics/CommentTrack.cpp | 2 +- .../Source/Cinematics/CompoundSplineTrack.cpp | 10 +- .../Code/Source/Cinematics/EventTrack.cpp | 6 +- .../Code/Source/Cinematics/SceneNode.cpp | 4 +- .../Source/Cinematics/ScreenFaderTrack.cpp | 2 +- .../Source/Cinematics/TrackEventTrack.cpp | 6 +- 42 files changed, 186 insertions(+), 225 deletions(-) diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index 5ba250c960..981e38c029 100644 --- a/Code/Editor/Export/ExportManager.cpp +++ b/Code/Editor/Export/ExportManager.cpp @@ -46,7 +46,7 @@ namespace SEfResTexture* pTex = pRes->GetTextureResource(nSlot); if (pTex) { - azstrcat(outName, Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data()); + azstrcat(outName, AZ_ARRAY_SIZE(outName), Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data()); } } @@ -88,7 +88,7 @@ Export::CObject::CObject(const char* pName) nParent = -1; - azstrcpy(name, pName); + azstrcpy(name, AZ_ARRAY_SIZE(name), pName); materialName[0] = '\0'; @@ -102,7 +102,7 @@ Export::CObject::CObject(const char* pName) void Export::CObject::SetMaterialName(const char* pName) { - azstrcpy(materialName, pName); + azstrcpy(materialName, AZ_ARRAY_SIZE(materialName), pName); } diff --git a/Code/Editor/TrackView/CommentNodeAnimator.cpp b/Code/Editor/TrackView/CommentNodeAnimator.cpp index 579bba00ef..cc3e7da972 100644 --- a/Code/Editor/TrackView/CommentNodeAnimator.cpp +++ b/Code/Editor/TrackView/CommentNodeAnimator.cpp @@ -92,7 +92,7 @@ void CCommentNodeAnimator::AnimateCommentTextTrack(CTrackViewTrack* pTrack, cons if (commentKey.m_duration > 0 && ac.time < keyHandle.GetTime() + commentKey.m_duration) { m_commentContext.m_strComment = commentKey.m_strComment; - azstrcpy(m_commentContext.m_strFont, commentKey.m_strFont.c_str()); + azstrcpy(m_commentContext.m_strFont, AZ_ARRAY_SIZE(m_commentContext.m_strFont), commentKey.m_strFont.c_str()); m_commentContext.m_color = commentKey.m_color; m_commentContext.m_align = commentKey.m_align; m_commentContext.m_size = commentKey.m_size; diff --git a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp index f66bb19bf3..bf2e39e64d 100644 --- a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp +++ b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp @@ -2808,10 +2808,10 @@ void CTrackViewDopeSheetBase::DrawKeys(CTrackViewTrack* pTrack, QPainter* painte } else { - azstrcpy(keydesc, "{"); + azstrcpy(keydesc, AZ_ARRAY_SIZE(keydesc), "{"); } - azstrcat(keydesc, pDescription); - azstrcat(keydesc, "}"); + azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), pDescription); + azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), "}"); // Draw key description text. // Find next key. const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom())); diff --git a/Code/Editor/TrackView/TrackViewNodes.cpp b/Code/Editor/TrackView/TrackViewNodes.cpp index 000bdf21d0..9652de51ef 100644 --- a/Code/Editor/TrackView/TrackViewNodes.cpp +++ b/Code/Editor/TrackView/TrackViewNodes.cpp @@ -2516,7 +2516,7 @@ int CTrackViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, cons if (const char* pCh = strstr(nodeName, ".[")) { char matPath[MAX_PATH]; - azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName)); + azstrncpy(matPath, AZ_ARRAY_SIZE(matPath), nodeName, (size_t)(pCh - nodeName)); matName = matPath; pCh += 2; if ((*pCh) != 0) diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp index f5535f5590..3157a04bd8 100644 --- a/Code/Editor/Util/FileUtil.cpp +++ b/Code/Editor/Util/FileUtil.cpp @@ -2217,15 +2217,14 @@ uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*= return SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK; } - AZStd::wstring fileW; - AZStd::to_wstring(fileW, file.GetAdjustedFilename()); - DWORD dwAttrib = ::GetFileAttributesW(fileW.c_str()); - if (dwAttrib == INVALID_FILE_ATTRIBUTES) + + const char* adjustedFile = file.GetAdjustedFilename(); + if (!AZ::IO::SystemFile::Exists(adjustedFile)) { return SCC_FILE_ATTRIBUTE_INVALID; } - if (dwAttrib & FILE_ATTRIBUTE_READONLY) + if (!AZ::IO::SystemFile::IsWritable(adjustedFile)) { return SCC_FILE_ATTRIBUTE_NORMAL | SCC_FILE_ATTRIBUTE_READONLY; } diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp index e91d85e4d2..2f99f42188 100644 --- a/Code/Editor/Util/PathUtil.cpp +++ b/Code/Editor/Util/PathUtil.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include @@ -203,16 +204,7 @@ namespace Path bool IsFolder(const char* pPath) { - AZStd::wstring pPathW; - AZStd::to_wstring(pPathW, pPath); - DWORD attrs = GetFileAttributes(pPathW.c_str()); - - if (attrs == FILE_ATTRIBUTE_DIRECTORY) - { - return true; - } - - return false; + return AZ::IO::FileIOBase::GetInstance()->IsDirectory(pPath); } ////////////////////////////////////////////////////////////////////////// @@ -256,7 +248,6 @@ namespace Path static AZStd::string s_currentModName; // query the editor root. The bus exists in case we want tools to be able to override this. - if (s_currentModName.empty()) { return GetGameAssetsFolder(); diff --git a/Code/Editor/Util/PathUtil.h b/Code/Editor/Util/PathUtil.h index 30887e698b..4ea30d1f74 100644 --- a/Code/Editor/Util/PathUtil.h +++ b/Code/Editor/Util/PathUtil.h @@ -106,7 +106,7 @@ namespace Path path = path_buffer; _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), 0, 0, fname, ext); #else - _splitpath(filepath, drive, dir, fname, ext); + _splitpath(filepath.c_str(), drive, dir, fname, ext); _makepath(path_buffer, drive, dir, 0, 0); path = path_buffer; _makepath(path_buffer, 0, 0, fname, ext); @@ -148,7 +148,7 @@ namespace Path _splitpath_s(filepath.c_str(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), fname, AZ_ARRAY_SIZE(fname), ext, AZ_ARRAY_SIZE(ext)); _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, 0, 0); #else - _splitpath(filepath, drive, dir, fname, ext); + _splitpath(filepath.c_str(), drive, dir, fname, ext); _makepath(path_buffer, drive, dir, 0, 0); #endif path = path_buffer; diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp index a1e2b4ae08..6c819270bd 100644 --- a/Code/Editor/Util/StringHelpers.cpp +++ b/Code/Editor/Util/StringHelpers.cpp @@ -15,7 +15,7 @@ int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1) { const size_t minLength = Util::getMin(str0.length(), str1.length()); - const int result = azmemicmp(str0.c_str(), str1.c_str(), minLength); + const int result = azstrnicmp(str0.c_str(), str1.c_str(), minLength); if (result) { return result; diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h index 0e393e92dd..b5c84d7fe3 100644 --- a/Code/Editor/Util/StringHelpers.h +++ b/Code/Editor/Util/StringHelpers.h @@ -11,6 +11,9 @@ #define CRYINCLUDE_CRYCOMMONTOOLS_STRINGHELPERS_H #pragma once +#include +#include + namespace StringHelpers { // compares two strings to see if they are the same or different, case is ignored diff --git a/Code/Framework/AzCore/AzCore/base.h b/Code/Framework/AzCore/AzCore/base.h index 252133e781..00fdbf515e 100644 --- a/Code/Framework/AzCore/AzCore/base.h +++ b/Code/Framework/AzCore/AzCore/base.h @@ -51,74 +51,72 @@ # define azvscprintf(_format, _va_list) _vscprintf(_format, _va_list) # define azscwprintf _scwprintf # define azvscwprintf _vscwprintf -# define azstrtok(_buffer, _size, _delim, _context) strtok_s(_buffer, _delim, _context) -# define azstrcat strcat_s -# define azstrncat strncat_s -# define strtoll _strtoi64 -# define strtoull _strtoui64 -# define azsscanf sscanf_s -# define azstrcpy strcpy_s -# define azstrncpy strncpy_s -# define azstricmp _stricmp -# define azstrnicmp _strnicmp -# define azisfinite _finite -# define azltoa _ltoa_s -# define azitoa _itoa_s -# define azui64toa _ui64toa_s -# define azswscanf swscanf_s -# define azwcsicmp _wcsicmp -# define azwcsnicmp _wcsnicmp -# define azmemicmp _memicmp +# define azstrtok(_buffer, _size, _delim, _context) strtok_s(_buffer, _delim, _context) +# define azstrcat(_dest, _destSize, _src) strcat_s(_dest, _destSize, _src) +# define azstrncat(_dest, _destSize, _src, _count) strncat_s(_dest, _destSize, _src, _count) +# define strtoll _strtoi64 +# define strtoull _strtoui64 +# define azsscanf sscanf_s +# define azstrcpy(_dest, _destSize, _src) strcpy_s(_dest, _destSize, _src) +# define azstrncpy(_dest, _destSize, _src, _count) strncpy_s(_dest, _destSize, _src, _count) +# define azstricmp _stricmp +# define azstrnicmp _strnicmp +# define azisfinite _finite +# define azltoa _ltoa_s +# define azitoa _itoa_s +# define azui64toa _ui64toa_s +# define azswscanf swscanf_s +# define azwcsicmp _wcsicmp +# define azwcsnicmp _wcsnicmp // note: for cross-platform compatibility, do not use the return value of azfopen. On Windows, it's an errno_t and 0 indicates success. On other platforms, the return value is a FILE*, and a 0 value indicates failure. -# define azfopen fopen_s +# define azfopen(_fp, _filename, _attrib) fopen_s(_fp, _filename, _attrib) # define azfscanf fscanf_s -# define azsprintf(_buffer, ...) sprintf_s(_buffer, AZ_ARRAY_SIZE(_buffer), __VA_ARGS__) -# define azstrlwr _strlwr_s -# define azvsprintf vsprintf_s -# define azwcscpy wcscpy_s -# define azstrtime _strtime_s -# define azstrdate _strdate_s -# define azlocaltime(time, result) localtime_s(result, time) +# define azsprintf(_buffer, ...) sprintf_s(_buffer, AZ_ARRAY_SIZE(_buffer), __VA_ARGS__) +# define azstrlwr _strlwr_s +# define azvsprintf vsprintf_s +# define azwcscpy wcscpy_s +# define azstrtime _strtime_s +# define azstrdate _strdate_s +# define azlocaltime(time, result) localtime_s(result, time) #else -# define azsnprintf snprintf -# define azvsnprintf vsnprintf +# define azsnprintf snprintf +# define azvsnprintf vsnprintf # if AZ_TRAIT_COMPILER_DEFINE_AZSWNPRINTF_AS_SWPRINTF -# define azsnwprintf swprintf -# define azvsnwprintf vswprintf +# define azsnwprintf swprintf +# define azvsnwprintf vswprintf # else -# define azsnwprintf snwprintf -# define azvsnwprintf vsnwprintf +# define azsnwprintf snwprintf +# define azvsnwprintf vsnwprintf # endif -# define azscprintf(...) azsnprintf(nullptr, static_cast(0), __VA_ARGS__); -# define azvscprintf(_format, _va_list) azvsnprintf(nullptr, static_cast(0), _format, _va_list); -# define azscwprintf(...) azsnwprintf(nullptr, static_cast(0), __VA_ARGS__); -# define azvscwprintf(_format, _va_list) azvsnwprintf(nullptr, static_cast(0), _format, _va_list); -# define azstrtok(_buffer, _size, _delim, _context) strtok(_buffer, _delim) -# define azstrcat(_dest, _destSize, _src) strcat(_dest, _src) -# define azstrncat(_dest, _destSize, _src, _count) strncat(_dest, _src, _count) -# define azsscanf sscanf -# define azstrcpy(_dest, _destSize, _src) strcpy(_dest, _src) -# define azstrncpy(_dest, _destSize, _src, _count) strncpy(_dest, _src, _count) -# define azstricmp strcasecmp -# define azstrnicmp strncasecmp +# define azscprintf(...) azsnprintf(nullptr, static_cast(0), __VA_ARGS__); +# define azvscprintf(_format, _va_list) azvsnprintf(nullptr, static_cast(0), _format, _va_list); +# define azscwprintf(...) azsnwprintf(nullptr, static_cast(0), __VA_ARGS__); +# define azvscwprintf(_format, _va_list) azvsnwprintf(nullptr, static_cast(0), _format, _va_list); +# define azstrtok(_buffer, _size, _delim, _context) strtok(_buffer, _delim) +# define azstrcat(_dest, _destSize, _src) strcat(_dest, _src) +# define azstrncat(_dest, _destSize, _src, _count) strncat(_dest, _src, _count) +# define azsscanf sscanf +# define azstrcpy(_dest, _destSize, _src) strcpy(_dest, _src) +# define azstrncpy(_dest, _destSize, _src, _count) strncpy(_dest, _src, _count) +# define azstricmp strcasecmp +# define azstrnicmp strncasecmp # if defined(NDK_REV_MAJOR) && NDK_REV_MAJOR < 16 -# define azisfinite __isfinitef +# define azisfinite __isfinitef # else -# define azisfinite isfinite +# define azisfinite isfinite # endif -# define azltoa(_value, _buffer, _size, _radix) ltoa(_value, _buffer, _radix) -# define azitoa(_value, _buffer, _size, _radix) itoa(_value, _buffer, _radix) -# define azui64toa(_value, _buffer, _size, _radix) _ui64toa(_value, _buffer, _radix) -# define azswscanf swscanf -# define azwcsicmp wcsicmp -# define azwcsnicmp wcsnicmp -# define azmemicmp memicmp +# define azltoa(_value, _buffer, _size, _radix) ltoa(_value, _buffer, _radix) +# define azitoa(_value, _buffer, _size, _radix) itoa(_value, _buffer, _radix) +# define azui64toa(_value, _buffer, _size, _radix) _ui64toa(_value, _buffer, _radix) +# define azswscanf swscanf +# define azwcsicmp wcscasecmp +# define azwcsnicmp wcsnicmp // note: for cross-platform compatibility, do not use the return value of azfopen. On Windows, it's an errno_t and 0 indicates success. On other platforms, the return value is a FILE*, and a 0 value indicates failure. -# define azfopen(_fp, _filename, _attrib) *(_fp) = fopen(_filename, _attrib) -# define azfscanf fscanf +# define azfopen(_fp, _filename, _attrib) *(_fp) = fopen(_filename, _attrib) +# define azfscanf fscanf # define azsprintf sprintf # define azstrlwr(_buffer, _size) strlwr(_buffer) diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index fcfe82ba5f..91af1029b4 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -30,6 +30,8 @@ namespace AZStd template struct WCharTPlatformConverter { + static_assert(Size == size_t{ 2 } || Size == size_t{ 4 }, "only wchar_t types of size 2 or 4 can be converted to utf8"); + template static inline void to_string(AZStd::basic_string& dest, const wchar_t* first, const wchar_t* last) { @@ -41,12 +43,6 @@ namespace AZStd { Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size()); } - else - { - // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter - using StringType = AZStd::basic_string; - static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8"); - } } template @@ -60,12 +56,6 @@ namespace AZStd { Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size()); } - else - { - // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter - using StringType = AZStd::basic_string; - static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8"); - } } static inline void to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last) @@ -78,10 +68,6 @@ namespace AZStd { Utf8::Unchecked::utf32to8(first, last, dest, destSize); } - else - { - static_assert(false, "only wchar_t types of size 2 or 4 can be converted to utf8"); - } } template @@ -95,12 +81,6 @@ namespace AZStd { Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size()); } - else - { - // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter - using StringType = AZStd::basic_string; - static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4"); - } } template @@ -114,12 +94,6 @@ namespace AZStd { Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size()); } - else - { - // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter - using StringType = AZStd::basic_string; - static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4"); - } } static inline void to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last) @@ -132,10 +106,6 @@ namespace AZStd { Utf8::Unchecked::utf8to32(first, last, dest, destSize); } - else - { - static_assert(false, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4"); - } } }; } diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp index c57f2b31f6..a4af19a2a4 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp @@ -30,9 +30,8 @@ namespace AZ result.m_pathIncludesFilename = true; // Platform specific get exe path: http://stackoverflow.com/a/1024937 // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea - AZStd::wstring pathBuffer; - pathBuffer.resize(exeStorageSize); - const DWORD pathLen = GetModuleFileName(nullptr, pathBuffer.data(), static_cast(exeStorageSize)); + wchar_t pathBufferW[AZ_MAX_PATH_LEN] = { 0 }; + const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(exeStorageSize)); const DWORD errorCode = GetLastError(); if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER) { @@ -44,7 +43,7 @@ namespace AZ } else { - AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBuffer.c_str()); + AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBufferW); } return result; diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp index 58afebfb90..61957fced0 100644 --- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp +++ b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp @@ -20,7 +20,9 @@ namespace AZ char resolvedPath[AZ_MAX_PATH_LEN]; ResolvePath(filePath, resolvedPath, AZ_MAX_PATH_LEN); - DWORD fileAttributes = GetFileAttributesA(resolvedPath); + wchar_t resolvedPathW[AZ_MAX_PATH_LEN]; + AZStd::to_wstring(resolvedPathW, AZ_MAX_PATH_LEN, resolvedPath); + DWORD fileAttributes = GetFileAttributesW(resolvedPathW); if (fileAttributes == INVALID_FILE_ATTRIBUTES) { return false; @@ -174,7 +176,7 @@ namespace AZ bool LocalFileIO::IsAbsolutePath(const char* path) const { - char drive[16]; + char drive[16] = { 0 }; _splitpath_s(path, drive, 16, nullptr, 0, nullptr, 0, nullptr, 0); return strlen(drive) > 0; } diff --git a/Code/Legacy/CryCommon/CryFile.h b/Code/Legacy/CryCommon/CryFile.h index 0888216f9c..0d2dac7c16 100644 --- a/Code/Legacy/CryCommon/CryFile.h +++ b/Code/Legacy/CryCommon/CryFile.h @@ -221,7 +221,7 @@ inline CCryFile::~CCryFile() inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlagsEx) { char tempfilename[CRYFILE_MAX_PATH] = ""; - azstrcpy(tempfilename, filename); + azstrcpy(tempfilename, CRYFILE_MAX_PATH, filename); #if !defined (_RELEASE) if (gEnv && gEnv->IsEditor() && gEnv->pConsole) @@ -233,7 +233,7 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag if (lowercasePaths) { const AZStd::string lowerString = PathUtil::ToLower(tempfilename); - azstrcpy(tempfilename, lowerString.c_str()); + azstrcpy(tempfilename, CRYFILE_MAX_PATH, lowerString.c_str()); } } } @@ -242,7 +242,7 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag { Close(); } - azstrcpy(m_filename, tempfilename); + azstrcpy(m_filename, CRYFILE_MAX_PATH, tempfilename); if (m_pIArchive) { @@ -429,7 +429,7 @@ inline const char* CCryFile::GetAdjustedFilename() const // Returns standard path otherwise. if (gameUrl != &szAdjustedFile[0]) { - azstrcpy(szAdjustedFile, gameUrl); + azstrcpy(szAdjustedFile, AZ::IO::IArchive::MaxPath, gameUrl); } return szAdjustedFile; } diff --git a/Code/Legacy/CryCommon/CryListenerSet.h b/Code/Legacy/CryCommon/CryListenerSet.h index 6857cf7e5d..e5be89aa9f 100644 --- a/Code/Legacy/CryCommon/CryListenerSet.h +++ b/Code/Legacy/CryCommon/CryListenerSet.h @@ -418,7 +418,7 @@ inline size_t CListenerSet::MemSize() const size += sizeof(typename TAllocatedNameVec::value_type); for (typename TAllocatedNameVec::const_iterator iter(m_allocatedNames.begin()); iter != m_allocatedNames.end(); ++iter) { - size += iter->GetAllocatedMemory(); + size += iter->capacity() * sizeof(char) + sizeof(AZStd::string); } #endif diff --git a/Code/Legacy/CryCommon/CryName.h b/Code/Legacy/CryCommon/CryName.h index 8e62a52517..552391419a 100644 --- a/Code/Legacy/CryCommon/CryName.h +++ b/Code/Legacy/CryCommon/CryName.h @@ -397,11 +397,11 @@ inline bool CCryName::operator>(const CCryName& n) const inline bool operator==(const AZStd::string& s, const CCryName& n) { - return s == n; + return s == n.c_str(); } inline bool operator!=(const AZStd::string& s, const CCryName& n) { - return s != n; + return s != n.c_str(); } inline bool operator==(const char* s, const CCryName& n) @@ -545,11 +545,11 @@ inline bool CCryNameCRC::operator>(const CCryNameCRC& n) const inline bool operator==(const AZStd::string& s, const CCryNameCRC& n) { - return s == n; + return n == s.c_str(); } inline bool operator!=(const AZStd::string& s, const CCryNameCRC& n) { - return s != n; + return n != s.c_str(); } inline bool operator==(const char* s, const CCryNameCRC& n) diff --git a/Code/Legacy/CryCommon/CryPath.h b/Code/Legacy/CryCommon/CryPath.h index e01e7a2e4b..046006f738 100644 --- a/Code/Legacy/CryCommon/CryPath.h +++ b/Code/Legacy/CryCommon/CryPath.h @@ -419,7 +419,7 @@ namespace PathUtil //! Makes a fully specified file path from path and file name. inline stack_string Make(const stack_string& dir, const stack_string& filename, const stack_string& ext) { - AZStd::string path = filename; + AZStd::string path = filename.c_str(); AZ::StringFunc::Path::ReplaceExtension(path, ext.c_str()); path = AddSlash(dir.c_str()) + path; return stack_string(path.c_str()); diff --git a/Code/Legacy/CryCommon/ISerialize.h b/Code/Legacy/CryCommon/ISerialize.h index 84e665850f..d427e222bb 100644 --- a/Code/Legacy/CryCommon/ISerialize.h +++ b/Code/Legacy/CryCommon/ISerialize.h @@ -387,7 +387,7 @@ public: bool ValueChar(const char* name, char* buffer, int len) { - string temp; + AZStd::string temp; if (IsReading()) { Value(name, temp); @@ -400,7 +400,7 @@ public: } else { - temp = string(buffer, buffer + len); + temp = AZStd::string(buffer, buffer + len); Value(name, temp); } return true; diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index e47d16d1bc..6507d7c8ee 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -14,6 +14,8 @@ #include #include #include +#include + /* Memory block identification */ #define _FREE_BLOCK 0 #define _NORMAL_BLOCK 1 @@ -344,7 +346,7 @@ private: char m_DirectoryName[260]; //!< directory name, needed when getting file attributes on the fly char m_ToMatch[260]; //!< pattern to match with DIR* m_Dir; //!< directory handle - std::vector m_Entries; //!< all file entries in the current directories + std::vector m_Entries; //!< all file entries in the current directories public: inline __finddata64_t() diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index fe9c539569..74d383b88d 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #ifdef APPLE #include @@ -77,8 +78,6 @@ unsigned int g_EnableMultipleAssert = 0;//set to something else than 0 if to ena #include #endif -#include "StringUtils.h" - #if AZ_TRAIT_COMPILER_DEFINE_FS_ERRNO_TYPE typedef int FS_ERRNO_TYPE; #if AZ_TRAIT_COMPILER_DEFINE_FS_STAT_TYPE @@ -349,23 +348,23 @@ void _makepath(char* path, const char* drive, const char* dir, const char* filen } if (dir && dir[0]) { - azstrcat(tmp, dir); + azstrcat(tmp, MAX_PATH, dir); ch = tmp[strlen(tmp) - 1]; if (ch != '/' && ch != '\\') { - azstrcat(tmp, "\\"); + azstrcat(tmp, MAX_PATH, "\\"); } } if (filename && filename[0]) { - azstrcat(tmp, filename); + azstrcat(tmp, MAX_PATH, filename); if (ext && ext[0]) { if (ext[0] != '.') { - azstrcat(tmp, "."); + azstrcat(tmp, MAX_PATH, "."); } - azstrcat(tmp, ext); + azstrcat(tmp, MAX_PATH, ext); } } azstrcpy(path, strlen(tmp) + 1, tmp); @@ -489,9 +488,9 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext typedef AZStd::fixed_string path_stack_string; const path_stack_string inPath(inpath); - string::size_type s = inPath.rfind('/', inPath.size());//position of last / + AZStd::string::size_type s = inPath.rfind('/', inPath.size());//position of last / path_stack_string fName; - if (s == string::npos) + if (s == AZStd::string::npos) { if (dir) { @@ -503,9 +502,9 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext { if (dir) { - azstrcpy(dir, AZ_MAX_PATH_LEN, (inPath.substr((string::size_type)0, (string::size_type)(s + 1))).c_str()); //assign directory + azstrcpy(dir, AZ_MAX_PATH_LEN, (inPath.substr((AZStd::string::size_type)0, (AZStd::string::size_type)(s + 1))).c_str()); //assign directory } - fName = inPath.substr((string::size_type)(s + 1)); //assign remaining string as rest + fName = inPath.substr((AZStd::string::size_type)(s + 1)); //assign remaining string as rest } if (fName.size() == 0) { @@ -521,8 +520,8 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext else { //dir and drive are now set - s = fName.find(".", (string::size_type)0);//position of first . - if (s == string::npos) + s = fName.find(".", (AZStd::string::size_type)0);//position of first . + if (s == AZStd::string::npos) { if (ext) { @@ -547,7 +546,7 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext } else { - azstrcpy(fname, AZ_MAX_PATH_LEN, (fName.substr((string::size_type)0, s)).c_str()); //assign filename + azstrcpy(fname, AZ_MAX_PATH_LEN, (fName.substr((AZStd::string::size_type)0, s)).c_str()); //assign filename } } } @@ -779,17 +778,17 @@ BOOL SystemTimeToFileTime(const SYSTEMTIME* syst, LPFILETIME ft) return TRUE; } -void adaptFilenameToLinux(string& rAdjustedFilename) +void adaptFilenameToLinux(AZStd::string& rAdjustedFilename) { //first replace all \\ by / - string::size_type loc = 0; - while ((loc = rAdjustedFilename.find("\\", loc)) != string::npos) + AZStd::string::size_type loc = 0; + while ((loc = rAdjustedFilename.find("\\", loc)) != AZStd::string::npos) { rAdjustedFilename.replace(loc, 1, "/"); } loc = 0; //remove /./ - while ((loc = rAdjustedFilename.find("/./", loc)) != string::npos) + while ((loc = rAdjustedFilename.find("/./", loc)) != AZStd::string::npos) { rAdjustedFilename.replace(loc, 3, "/"); } @@ -798,16 +797,16 @@ void adaptFilenameToLinux(string& rAdjustedFilename) void replaceDoublePathFilename(char* szFileName) { //replace "\.\" by "\" - string s(szFileName); - string::size_type loc = 0; + AZStd::string s(szFileName); + AZStd::string::size_type loc = 0; //remove /./ - while ((loc = s.find("/./", loc)) != string::npos) + while ((loc = s.find("/./", loc)) != AZStd::string::npos) { s.replace(loc, 3, "/"); } loc = 0; //remove "\.\" - while ((loc = s.find("\\.\\", loc)) != string::npos) + while ((loc = s.find("\\.\\", loc)) != AZStd::string::npos) { s.replace(loc, 3, "\\"); } @@ -817,8 +816,8 @@ void replaceDoublePathFilename(char* szFileName) const int comparePathNames(const char* cpFirst, const char* cpSecond, unsigned int len) { //create two strings and replace the \\ by / and /./ by / - string first(cpFirst); - string second(cpSecond); + AZStd::string first(cpFirst); + AZStd::string second(cpSecond); adaptFilenameToLinux(first); adaptFilenameToLinux(second); if (strlen(cpFirst) < len || strlen(cpSecond) < len) @@ -1618,14 +1617,16 @@ const bool GetFilenameNoCase return true; } -DWORD GetFileAttributes(LPCSTR lpFileName) +DWORD GetFileAttributes(LPCWSTR lpFileNameW) { + AZStd::string lpFileName; + AZStd::to_string(lpFileName, lpFileNameW); struct stat fileStats; - const int success = stat(lpFileName, &fileStats); + const int success = stat(lpFileName.c_str(), &fileStats); if (success == -1) { char adjustedFilename[MAX_PATH]; - GetFilenameNoCase(lpFileName, adjustedFilename); + GetFilenameNoCase(lpFileName.c_str(), adjustedFilename); if (stat(adjustedFilename, &fileStats) == -1) { return (DWORD)INVALID_FILE_ATTRIBUTES; @@ -1648,7 +1649,7 @@ DWORD GetFileAttributes(LPCSTR lpFileName) uint32 CryGetFileAttributes(const char* lpFileName) { - string fn = lpFileName; + AZStd::string fn = lpFileName; adaptFilenameToLinux(fn); const char* buffer = fn.c_str(); return GetFileAttributes(buffer); diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp index 289d4070ff..c0923341ad 100644 --- a/Code/Legacy/CrySystem/DebugCallStack.cpp +++ b/Code/Legacy/CrySystem/DebugCallStack.cpp @@ -435,18 +435,18 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) { const char* const szMessage = m_bIsFatalError ? s_szFatalErrorCode : m_szBugMessage; excName = szMessage; - azstrcpy(excCode, szMessage); - azstrcpy(excAddr, ""); - azstrcpy(desc, ""); - azstrcpy(m_excModule, ""); - azstrcpy(excDesc, szMessage); + azstrcpy(excCode, AZ_ARRAY_SIZE(excCode), szMessage); + azstrcpy(excAddr, AZ_ARRAY_SIZE(excAddr), ""); + azstrcpy(desc, AZ_ARRAY_SIZE(desc), ""); + azstrcpy(m_excModule, AZ_ARRAY_SIZE(m_excModule), ""); + azstrcpy(excDesc, AZ_ARRAY_SIZE(excDesc), szMessage); } else { sprintf_s(excAddr, "0x%04X:0x%p", pex->ContextRecord->SegCs, pex->ExceptionRecord->ExceptionAddress); sprintf_s(excCode, "0x%08X", pex->ExceptionRecord->ExceptionCode); excName = TranslateExceptionCode(pex->ExceptionRecord->ExceptionCode); - azstrcpy(desc, ""); + azstrcpy(desc, AZ_ARRAY_SIZE(desc), ""); sprintf_s(excDesc, "%s\r\n%s", excName, desc); @@ -476,9 +476,9 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) WriteLineToLog("Exception Description: %s", desc); - azstrcpy(m_excDesc, excDesc); - azstrcpy(m_excAddr, excAddr); - azstrcpy(m_excCode, excCode); + azstrcpy(m_excDesc, AZ_ARRAY_SIZE(m_excDesc), excDesc); + azstrcpy(m_excAddr, AZ_ARRAY_SIZE(m_excAddr), excAddr); + azstrcpy(m_excCode, AZ_ARRAY_SIZE(m_excCode), excCode); char errs[32768]; @@ -504,7 +504,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) dumpCallStack(funcs); // Fill call stack. char str[s_iCallStackSize]; - azstrcpy(str, ""); + azstrcpy(str, AZ_ARRAY_SIZE(str), ""); for (unsigned int i = 0; i < funcs.size(); i++) { char temp[s_iCallStackSize]; @@ -514,7 +514,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) azstrcat(errs, temp); azstrcat(errs, "\n"); } - azstrcpy(m_excCallstack, str); + azstrcpy(m_excCallstack, AZ_ARRAY_SIZE(m_excCallstack), str); } azstrcat(errorString, errs); diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp index bee43b237b..1176c15f0e 100644 --- a/Code/Legacy/CrySystem/IDebugCallStack.cpp +++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp @@ -237,7 +237,7 @@ void IDebugCallStack::WriteLineToLog(const char* format, ...) char szBuffer[MAX_WARNING_LENGTH]; va_start(ArgList, format); vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, ArgList); - azstrcat(szBuffer, "\n"); + azstrcat(szBuffer, MAX_WARNING_LENGTH, "\n"); szBuffer[sizeof(szBuffer) - 1] = '\0'; va_end(ArgList); diff --git a/Code/Legacy/CrySystem/IDebugCallStack.h b/Code/Legacy/CrySystem/IDebugCallStack.h index a2c1d3f5e2..1a65fbbdb7 100644 --- a/Code/Legacy/CrySystem/IDebugCallStack.h +++ b/Code/Legacy/CrySystem/IDebugCallStack.h @@ -41,11 +41,7 @@ public: filename = "[unknown]"; line = 0; baseAddr = addr; -#if defined(PLATFORM_64BIT) - procName = AZStd::string::format("[%016llX]", addr); -#else - procName = AZStd::string::format("[%08X]", addr); -#endif + procName = AZStd::string::format("[%p]", addr); } // returns current filename diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index 3e6432a721..d21fff3dd3 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -567,7 +567,7 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) INDENT_LOG_DURING_SCOPE(); char levelName[256]; - azstrcpy(levelName, _levelName); + azstrcpy(levelName, AZ_ARRAY_SIZE(levelName), _levelName); // Not remove a scope!!! { diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp index 42bdb3afef..cffe1c38c6 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp +++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp @@ -2762,7 +2762,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool const size_t bufSize = sizeof(buf) / sizeof(buf[0]); wcsftime(buf, bufSize, bShowSeconds ? L"%#X" : L"%X", &theTime); buf[bufSize - 1] = 0; - Unicode::Convert(outTimeString, buf); + AZStd::to_string(outTimeString, buf); } void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString) @@ -2790,7 +2790,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool const wchar_t* format = bShort ? (bIncludeWeekday ? L"%a %x" : L"%x") : L"%#x"; // long format always contains Weekday name wcsftime(buf, bufSize, format, &theTime); buf[bufSize - 1] = 0; - Unicode::Convert(outDateString, buf); + AZStd::to_string(outDateString, buf); } diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index 6ee6af6c22..0385ff8eb3 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -508,7 +508,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo stack_string s = szBuffer; s += "\t "; s += sAssetScope; - azstrcpy(szBuffer, s.c_str()); + azstrcpy(szBuffer, AZ_ARRAY_SIZE(szBuffer), s.c_str()); } } @@ -531,7 +531,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo } } i = m_iLastHistoryItem = m_iLastHistoryItem + 1 & sz - 1; - azstrcpy(m_history[i].str, m_history[i].ptr = szSpamCheck); + azstrcpy(m_history[i].str, AZ_ARRAY_SIZE(m_history[i].str), m_history[i].ptr = szSpamCheck); m_history[i].type = type; m_history[i].time = time; } @@ -862,7 +862,7 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL { // When logging from other thread then main, push all log strings to queue. SLogMsg msg; - azstrcpy(msg.msg, szString); + azstrcpy(msg.msg, AZ_ARRAY_SIZE(msg.msg), szString); msg.bAdd = bAdd; msg.destination = destination; msg.logType = logType; @@ -1277,7 +1277,7 @@ void CLog::CreateBackupFile() const AZStd::string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt); fileSystem->CreatePath(LOG_BACKUP_PATH); - azstrcpy(m_sBackupFilename, bakdest.c_str()); + azstrcpy(m_sBackupFilename, AZ_ARRAY_SIZE(m_sBackupFilename), bakdest.c_str()); // Remove any existing backup file with the same name first since the copy will fail otherwise. fileSystem->Remove(m_sBackupFilename); fileSystem->Copy(m_szFilename, bakdest.c_str()); diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index 9fd01f1905..66be2a2ca5 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -282,7 +282,7 @@ static const char* GetLastSystemErrorMessage() 0, NULL)) { - azstrcpy(szBuffer, (char*)lpMsgBuf); + azstrcpy(szBuffer, AZ_ARRAY_SIZE(szBuffer), (char*)lpMsgBuf); LocalFree(lpMsgBuf); } else diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index 252ab8137d..6da42420f8 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -1547,31 +1547,31 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags) // hiding this makes it a bit more difficult for cheaters // if(dwFlags&VF_CHEAT) azstrcat( sFlags,"CHEAT, "); - azstrcpy(sFlags, ""); + azstrcpy(sFlags, AZ_ARRAY_SIZE(sFlags), ""); if (dwFlags & VF_READONLY) { - azstrcat(sFlags, "READONLY, "); + azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "READONLY, "); } if (dwFlags & VF_DEPRECATED) { - azstrcat(sFlags, "DEPRECATED, "); + azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "DEPRECATED, "); } if (dwFlags & VF_DUMPTODISK) { - azstrcat(sFlags, "DUMPTODISK, "); + azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "DUMPTODISK, "); } if (dwFlags & VF_REQUIRE_LEVEL_RELOAD) { - azstrcat(sFlags, "REQUIRE_LEVEL_RELOAD, "); + azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "REQUIRE_LEVEL_RELOAD, "); } if (dwFlags & VF_REQUIRE_APP_RESTART) { - azstrcat(sFlags, "REQUIRE_APP_RESTART, "); + azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "REQUIRE_APP_RESTART, "); } if (dwFlags & VF_RESTRICTEDMODE) { - azstrcat(sFlags, "RESTRICTEDMODE, "); + azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "RESTRICTEDMODE, "); } if (sFlags[0] != 0) @@ -3325,7 +3325,7 @@ const char* CXConsole::AutoComplete(const char* substr) const char* szCmd = cmds[i]; size_t cmdlen = strlen(szCmd); - if (cmdlen >= substrLen && azmemicmp(szCmd, substr, substrLen) == 0) + if (cmdlen >= substrLen && azstrnicmp(szCmd, substr, substrLen) == 0) { if (substrLen == cmdlen) { diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp index e59f6b8969..c86c0691a9 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp @@ -32,7 +32,7 @@ const char* XMLBinary::XMLBinaryReader::GetErrorDescription() const void XMLBinary::XMLBinaryReader::SetErrorDescription(const char* text) { - azstrcpy(m_errorDescription, text); + azstrcpy(m_errorDescription, AZ_ARRAY_SIZE(m_errorDescription), text); } diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp index 81994b26e0..7fd9df30c9 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp @@ -99,7 +99,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, static const uint nMaxNodeCount = (NodeIndex) ~0; if (m_nodes.size() > nMaxNodeCount) { - error = AZStd::string::format("XMLBinary: Too many nodes: %d (max is %i)", m_nodes.size(), nMaxNodeCount); + error = AZStd::string::format("XMLBinary: Too many nodes: %zu (max is %i)", m_nodes.size(), nMaxNodeCount); return false; } diff --git a/Code/Tools/GridHub/GridHub/gridhub.cpp b/Code/Tools/GridHub/GridHub/gridhub.cpp index 978589ab74..24dd440411 100644 --- a/Code/Tools/GridHub/GridHub/gridhub.cpp +++ b/Code/Tools/GridHub/GridHub/gridhub.cpp @@ -543,7 +543,7 @@ GridHubComponent::OnMemberJoined([[maybe_unused]] GridMate::GridSession* session case AZ::PlatformID::PLATFORM_WINDOWS_64: case AZ::PlatformID::PLATFORM_APPLE_MAC: { - GridMate::string localMachineName = GridMate::Utils::GetMachineAddress(); + AZStd::string localMachineName = GridMate::Utils::GetMachineAddress(); if( member->GetMachineName() == localMachineName ) { ExternalProcessMonitor mi; @@ -629,7 +629,7 @@ bool GridHubComponent::StartSession(bool isRestarting) AZ_Assert(GridMate::HasGridMateService(m_gridMate), "Failed to start multiplayer service for LAN!"); // if we get an address 169.X.X.X (AZCP is NOT ready) or 127.0.0.1 when network is not ready - GridMate::string machineIP = GridMate::Utils::GetMachineAddress(); + AZStd::string machineIP = GridMate::Utils::GetMachineAddress(); if( machineIP == "127.0.0.1" || machineIP.compare(0,4,"169.") == 0 ) { AZ_Warning("GridHub", false, "\nCurrent IP %s might be invalid.\n",machineIP.c_str()); diff --git a/Code/Tools/GridHub/GridHub/gridhub.hxx b/Code/Tools/GridHub/GridHub/gridhub.hxx index 468cf525a0..849dbb92e1 100644 --- a/Code/Tools/GridHub/GridHub/gridhub.hxx +++ b/Code/Tools/GridHub/GridHub/gridhub.hxx @@ -141,7 +141,7 @@ public: /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns. void OnSessionDelete(GridMate::GridSession* session) override; /// Called when a session error occurs. - void OnSessionError(GridMate::GridSession* session, const GridMate::string& errorMsg ) { (void)session; (void)errorMsg; } + void OnSessionError(GridMate::GridSession* session, const AZStd::string& errorMsg ) { (void)session; (void)errorMsg; } /// Called when the actual game(match) starts void OnSessionStart(GridMate::GridSession* session) { (void)session; } /// Called when the actual game(match) ends diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp index 2630a63bee..dd65722560 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp @@ -11,6 +11,7 @@ #include #include +#include namespace TestImpact { @@ -55,9 +56,11 @@ namespace TestImpact CreatePipes(sa, si); - if (!CreateProcess( + AZStd::wstring argsW; + AZStd::to_wstring(argsW, args.c_str()); + if (!CreateProcessW( NULL, - &args[0], + argsW.c_str(), NULL, NULL, IsPiping(), diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp index ae0880e98e..a38736ff67 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp @@ -2362,10 +2362,10 @@ void CUiAnimViewDopeSheetBase::DrawKeys(CUiAnimViewTrack* pTrack, QPainter* pain } else { - azstrcpy(keydesc, "{"); + azstrcpy(keydesc, AZ_ARRAY_SIZE(keydesc), "{"); } - azstrcat(keydesc, pDescription); - azstrcat(keydesc, "}"); + azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), pDescription); + azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), "}"); // Draw key description text. // Find next key. const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom())); diff --git a/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp b/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp index 744cb65ac8..9175c7b2be 100644 --- a/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp +++ b/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp @@ -8,16 +8,13 @@ // UiClipboard is responsible setting and getting clipboard data for the UI elements in a platform-independent way. #include "UiClipboard.h" -#include -bool UiClipboard::SetText(const AZStd::string& text) +bool UiClipboard::SetText([[maybe_unused]] const AZStd::string& text) { - AZ_UNUSED(text); return false; } AZStd::string UiClipboard::GetText() { - AZStd::string outText; - return outText; + return {}; } diff --git a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp index 60d578d1f8..f4faf4dbeb 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp @@ -52,7 +52,7 @@ void CCaptureTrack::GetKeyInfo(int key, const char*& description, float& duratio char prefix[64] = "Frame"; if (!m_keys[key].prefix.empty()) { - azstrcpy(prefix, m_keys[key].prefix.c_str()); + azstrcpy(prefix, AZ_ARRAY_SIZE(prefix), m_keys[key].prefix.c_str()); } description = buffer; if (!m_keys[key].folder.empty()) diff --git a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp index 1dd72de567..8c1baf4684 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp @@ -25,7 +25,7 @@ void CCommentTrack::GetKeyInfo(int key, const char*& description, float& duratio description = 0; duration = m_keys[key].m_duration; - azstrcpy(desc, m_keys[key].m_strComment.c_str()); + azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].m_strComment.c_str()); description = desc; } diff --git a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp index 62de2dfdf5..884a90b200 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp @@ -457,31 +457,31 @@ void CCompoundSplineTrack::GetKeyInfo(int key, const char*& description, float& { float dummy; m_subTracks[0]->GetKeyInfo(m, subDesc, dummy); - azstrcat(str, subDesc); + azstrcat(str, AZ_ARRAY_SIZE(str), subDesc); break; } } if (m == m_subTracks[0]->GetNumKeys()) { - azstrcat(str, m_subTrackNames[0].c_str()); + azstrcat(str, AZ_ARRAY_SIZE(str), m_subTrackNames[0].c_str()); } // Tail cases for (int i = 1; i < GetSubTrackCount(); ++i) { - azstrcat(str, ","); + azstrcat(str, AZ_ARRAY_SIZE(str), ","); for (m = 0; m < m_subTracks[i]->GetNumKeys(); ++m) { if (m_subTracks[i]->GetKeyTime(m) == time) { float dummy; m_subTracks[i]->GetKeyInfo(m, subDesc, dummy); - azstrcat(str, subDesc); + azstrcat(str, AZ_ARRAY_SIZE(str), subDesc); break; } } if (m == m_subTracks[i]->GetNumKeys()) { - azstrcat(str, m_subTrackNames[i].c_str()); + azstrcat(str, AZ_ARRAY_SIZE(str), m_subTrackNames[i].c_str()); } } } diff --git a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp index 36d468e36d..4d32a4a4a1 100644 --- a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp @@ -69,11 +69,11 @@ void CEventTrack::GetKeyInfo(int key, const char*& description, float& duration) CheckValid(); description = 0; duration = 0; - azstrcpy(desc, m_keys[key].event.c_str()); + azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].event.c_str()); if (!m_keys[key].eventValue.empty()) { - azstrcat(desc, ", "); - azstrcat(desc, m_keys[key].eventValue.c_str()); + azstrcat(desc, AZ_ARRAY_SIZE(desc), ", "); + azstrcat(desc, AZ_ARRAY_SIZE(desc), m_keys[key].eventValue.c_str()); } description = desc; diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp index 799747eb12..be6d18eeb2 100644 --- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp @@ -916,8 +916,8 @@ void CAnimSceneNode::ApplyCameraKey(ISelectKey& key, SAnimContext& ec) void CAnimSceneNode::ApplyEventKey(IEventKey& key, [[maybe_unused]] SAnimContext& ec) { char funcName[1024]; - azstrcpy(funcName, "Event_"); - azstrcat(funcName, key.event.c_str()); + azstrcpy(funcName, AZ_ARRAY_SIZE(funcName), "Event_"); + azstrcat(funcName, AZ_ARRAY_SIZE(funcName), key.event.c_str()); gEnv->pMovieSystem->SendGlobalEvent(funcName); } diff --git a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp index 3541fe718e..9ac19f91ea 100644 --- a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp @@ -32,7 +32,7 @@ void CScreenFaderTrack::GetKeyInfo(int key, const char*& description, float& dur CheckValid(); description = 0; duration = m_keys[key].m_fadeTime; - azstrcpy(desc, m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out"); + azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out"); description = desc; } diff --git a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp index 25d709bcdc..83b141cfb2 100644 --- a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp @@ -143,11 +143,11 @@ void CTrackEventTrack::GetKeyInfo(int key, const char*& description, float& dura CheckValid(); description = 0; duration = 0; - azstrcpy(desc, m_keys[key].event.c_str()); + azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].event.c_str()); if (!m_keys[key].eventValue.empty()) { - azstrcat(desc, ", "); - azstrcat(desc, m_keys[key].eventValue.c_str()); + azstrcat(desc, AZ_ARRAY_SIZE(desc), ", "); + azstrcat(desc, AZ_ARRAY_SIZE(desc), m_keys[key].eventValue.c_str()); } description = desc; From 82c5f80fbd163317d823f4d700befc971562a1ea Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 3 Aug 2021 18:56:46 -0700 Subject: [PATCH 086/251] More windows/linux fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/base.h | 20 +++++++++---------- Code/Framework/AzCore/Tests/Debug.cpp | 4 ++-- Code/Legacy/CryCommon/platform_impl.cpp | 2 +- Code/Legacy/CrySystem/DebugCallStack.cpp | 16 +++++++-------- .../Code/Editor/Animation/UiAnimViewNodes.cpp | 2 +- 5 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/base.h b/Code/Framework/AzCore/AzCore/base.h index 00fdbf515e..20f5c17b27 100644 --- a/Code/Framework/AzCore/AzCore/base.h +++ b/Code/Framework/AzCore/AzCore/base.h @@ -71,7 +71,7 @@ // note: for cross-platform compatibility, do not use the return value of azfopen. On Windows, it's an errno_t and 0 indicates success. On other platforms, the return value is a FILE*, and a 0 value indicates failure. # define azfopen(_fp, _filename, _attrib) fopen_s(_fp, _filename, _attrib) -# define azfscanf fscanf_s +# define azfscanf fscanf_s # define azsprintf(_buffer, ...) sprintf_s(_buffer, AZ_ARRAY_SIZE(_buffer), __VA_ARGS__) # define azstrlwr _strlwr_s @@ -118,19 +118,19 @@ # define azfopen(_fp, _filename, _attrib) *(_fp) = fopen(_filename, _attrib) # define azfscanf fscanf -# define azsprintf sprintf -# define azstrlwr(_buffer, _size) strlwr(_buffer) -# define azvsprintf vsprintf -# define azwcscpy(_dest, _size, _buffer) wcscpy(_dest, _buffer) -# define azstrtime _strtime -# define azstrdate _strdate -# define azlocaltime localtime_r +# define azsprintf sprintf +# define azstrlwr(_buffer, _size) strlwr(_buffer) +# define azvsprintf vsprintf +# define azwcscpy(_dest, _size, _buffer) wcscpy(_dest, _buffer) +# define azstrtime _strtime +# define azstrdate _strdate +# define azlocaltime localtime_r #endif #if AZ_TRAIT_USE_POSIX_STRERROR_R -# define azstrerror_s(_dst, _num, _err) strerror_r(_err, _dst, _num) +# define azstrerror_s(_dst, _num, _err) strerror_r(_err, _dst, _num) #else -# define azstrerror_s strerror_s +# define azstrerror_s strerror_s #endif #define AZ_INVALID_POINTER reinterpret_cast(0x0badf00dul) diff --git a/Code/Framework/AzCore/Tests/Debug.cpp b/Code/Framework/AzCore/Tests/Debug.cpp index 3d214ffc68..6181823737 100644 --- a/Code/Framework/AzCore/Tests/Debug.cpp +++ b/Code/Framework/AzCore/Tests/Debug.cpp @@ -56,7 +56,7 @@ namespace UnitTest int isFoundModule = 0; char expectedNameBuffer[AZ_ARRAY_SIZE(SymbolStorage::ModuleInfo::m_modName)]; #if defined(AZCORETEST_DLL_NAME) - azstrncpy(expectedNameBuffer, AZCORETEST_DLL_NAME, AZ_ARRAY_SIZE(expectedNameBuffer)); + azstrncpy(expectedNameBuffer, AZ_ARRAY_SIZE(expectedNameBuffer), AZCORETEST_DLL_NAME, AZ_ARRAY_SIZE(expectedNameBuffer)); #else azstrncpy(expectedNameBuffer, "azcoretests.dll", AZ_ARRAY_SIZE(expectedNameBuffer)); #endif @@ -65,7 +65,7 @@ namespace UnitTest for (u32 i = 0; i < SymbolStorage::GetNumLoadedModules(); ++i) { char nameBuffer[AZ_ARRAY_SIZE(SymbolStorage::ModuleInfo::m_modName)]; - azstrncpy(nameBuffer, SymbolStorage::GetModuleInfo(i)->m_fileName, AZ_ARRAY_SIZE(nameBuffer)); + azstrncpy(nameBuffer, AZ_ARRAY_SIZE(nameBuffer), SymbolStorage::GetModuleInfo(i)->m_fileName, AZ_ARRAY_SIZE(nameBuffer)); AZStd::to_lower(nameBuffer, nameBuffer + AZ_ARRAY_SIZE(nameBuffer)); if (strstr(nameBuffer, expectedNameBuffer)) diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 1523622538..3d7b2180fc 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -288,7 +288,7 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], uint firstIteration = false; } // Check if the engineroot exists - azstrcat(szPath, "\\engine.json"); + azstrcat(szPath, AZ_ARRAY_SIZE(szPath), "\\engine.json"); WIN32_FILE_ATTRIBUTE_DATA data; AZStd::wstring szPathW; AZStd::to_wstring(szPathW, szPath); diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp index c0923341ad..ef27ef2c59 100644 --- a/Code/Legacy/CrySystem/DebugCallStack.cpp +++ b/Code/Legacy/CrySystem/DebugCallStack.cpp @@ -419,8 +419,8 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) char versionbuf[1024]; azstrcpy(versionbuf, AZ_ARRAY_SIZE(versionbuf), ""); PutVersion(versionbuf, AZ_ARRAY_SIZE(versionbuf)); - azstrcat(errorString, versionbuf); - azstrcat(errorString, "\n"); + azstrcat(errorString, AZ_ARRAY_SIZE(errorString), versionbuf); + azstrcat(errorString, AZ_ARRAY_SIZE(errorString), "\n"); char excCode[MAX_WARNING_LENGTH]; char excAddr[80]; @@ -486,7 +486,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) excCode, excAddr, m_excModule, excName, desc); - azstrcat(errs, "\nCall Stack Trace:\n"); + azstrcat(errs, AZ_ARRAY_SIZE(errs), "\nCall Stack Trace:\n"); std::vector funcs; { @@ -509,15 +509,15 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) { char temp[s_iCallStackSize]; sprintf_s(temp, "%2zd) %s", funcs.size() - i, (const char*)funcs[i].c_str()); - azstrcat(str, temp); - azstrcat(str, "\r\n"); - azstrcat(errs, temp); - azstrcat(errs, "\n"); + azstrcat(str, AZ_ARRAY_SIZE(str), temp); + azstrcat(str, AZ_ARRAY_SIZE(str), "\r\n"); + azstrcat(errs, AZ_ARRAY_SIZE(errs), temp); + azstrcat(errs, AZ_ARRAY_SIZE(errs), "\n"); } azstrcpy(m_excCallstack, AZ_ARRAY_SIZE(m_excCallstack), str); } - azstrcat(errorString, errs); + azstrcat(errorString, AZ_ARRAY_SIZE(errorString), errs); if (f) { diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp index 67fd542c3f..679477e3d3 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp @@ -1512,7 +1512,7 @@ int CUiAnimViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, con if (const char* pCh = strstr(nodeName, ".[")) { char matPath[MAX_PATH]; - azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName)); + azstrncpy(matPath, AZ_ARRAY_SIZE(matPath), nodeName, (size_t)(pCh - nodeName)); matName = matPath; pCh += 2; if ((*pCh) != 0) From eeed7df429f0d25917e42e5217b460bfcc41c2eb Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 3 Aug 2021 20:24:36 -0700 Subject: [PATCH 087/251] fixing no unity builds Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../ProjectSettingsContainer.cpp | 1 + .../GridMate/Carrier/DefaultHandshake.h | 1 + .../Carrier/DefaultTrafficControl.cpp | 1 + .../GridMate/Carrier/DefaultTrafficControl.h | 2 ++ .../GridMate/GridMate/Carrier/Handshake.h | 1 + Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 2 +- Code/Legacy/CryCommon/WinBase.cpp | 25 +++++++++++++++++-- .../Code/Source/Animation/AnimSequence.cpp | 2 ++ .../Code/Source/SystemComponent.cpp | 1 + 9 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp b/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp index a7a238d241..772469808b 100644 --- a/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp +++ b/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp @@ -8,6 +8,7 @@ #include "ProjectSettingsContainer.h" +#include #include #include #include diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h index 8f456e4649..9225cca8d7 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h +++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h @@ -9,6 +9,7 @@ #define GM_DEFAULT_HANDSHAKE_H #include +#include namespace GridMate { diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp index 5da3c784ff..f9280d9918 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp @@ -12,6 +12,7 @@ #include #include +#include using namespace GridMate; diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h index 1d8a1f6b46..259c619f53 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h +++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h @@ -12,6 +12,8 @@ #include +#include + namespace GridMate { /** diff --git a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h index 0f825da49b..5f67b6637c 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h +++ b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h @@ -10,6 +10,7 @@ #include #include +#include namespace GridMate { diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 6507d7c8ee..912546cb7b 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -378,7 +378,7 @@ typedef struct _finddata_t extern int _findnext64(intptr_t last, __finddata64_t* pFindData); extern intptr_t _findfirst64(const char* pFileName, __finddata64_t* pFindData); -extern DWORD GetFileAttributes(LPCSTR lpFileName); +extern DWORD GetFileAttributesW(LPCWSTR lpFileName); extern const bool GetFilenameNoCase(const char* file, char*, const bool cCreateNew = false); diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 74d383b88d..64e9d9b066 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -1648,12 +1648,33 @@ DWORD GetFileAttributes(LPCWSTR lpFileNameW) uint32 CryGetFileAttributes(const char* lpFileName) { - AZStd::string fn = lpFileName; adaptFilenameToLinux(fn); const char* buffer = fn.c_str(); - return GetFileAttributes(buffer); + struct stat fileStats; + const int success = stat(buffer, &fileStats); + if (success == -1) + { + char adjustedFilename[MAX_PATH]; + GetFilenameNoCase(buffer, adjustedFilename); + if (stat(adjustedFilename, &fileStats) == -1) + { + return (DWORD)INVALID_FILE_ATTRIBUTES; + } + } + DWORD ret = 0; + + const int acc = (fileStats.st_mode & S_IWRITE); + + if (acc != 0) + { + if (S_ISDIR(fileStats.st_mode) != 0) + { + ret |= FILE_ATTRIBUTE_DIRECTORY; + } + } + return (ret == 0) ? FILE_ATTRIBUTE_NORMAL : ret;//return file attribute normal as the default value, must only be set if no other attributes have been found } __finddata64_t::~__finddata64_t() diff --git a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp index 43a80d5002..0b19c4a06a 100644 --- a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp +++ b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp @@ -594,6 +594,8 @@ void CUiAnimSequence::Activate() } } +typedef AZStd::fixed_string<512> stack_string; + ////////////////////////////////////////////////////////////////////////// void CUiAnimSequence::Deactivate() { diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 4944626d77..f46c8e229a 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -30,6 +30,7 @@ #include #include +#include #include From 9bab6761096d1490f487f296ed32efb728707686 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 3 Aug 2021 20:25:21 -0700 Subject: [PATCH 088/251] enabling test impact framework tool build and fixed it Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Tools/TestImpactFramework/CMakeLists.txt | 6 ++---- .../Platform/Windows/Process/TestImpactWin32_Process.cpp | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Code/Tools/TestImpactFramework/CMakeLists.txt b/Code/Tools/TestImpactFramework/CMakeLists.txt index 04cbee98dc..1cdf02d101 100644 --- a/Code/Tools/TestImpactFramework/CMakeLists.txt +++ b/Code/Tools/TestImpactFramework/CMakeLists.txt @@ -11,8 +11,6 @@ ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Platf include(${pal_source_dir}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) if(PAL_TRAIT_TEST_IMPACT_FRAMEWORK_SUPPORTED) - if(LY_TEST_IMPACT_INSTRUMENTATION_BIN) - add_subdirectory(Runtime) - add_subdirectory(Frontend) - endif() + add_subdirectory(Runtime) + add_subdirectory(Frontend) endif() diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp index dd65722560..7ba061f932 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp @@ -60,7 +60,7 @@ namespace TestImpact AZStd::to_wstring(argsW, args.c_str()); if (!CreateProcessW( NULL, - argsW.c_str(), + argsW.data(), NULL, NULL, IsPiping(), From 1b002dcc82ca4fbb8e466c2d569d5e1c0fc9566a Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Wed, 4 Aug 2021 11:48:16 +0200 Subject: [PATCH 089/251] Saving node chunk v2 and adapting the chunk processor and importer to it Signed-off-by: Benjamin Jillich --- .../ExporterLib/Exporter/NodeExport.cpp | 50 +++--------------- .../Source/Importer/ActorFileFormat.h | 8 +-- .../Source/Importer/ChunkProcessors.cpp | 52 ++----------------- .../Source/Importer/ChunkProcessors.h | 3 +- .../EMotionFX/Source/Importer/Importer.cpp | 4 +- 5 files changed, 18 insertions(+), 99 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp index c66c3ca8ef..79861be4b8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp @@ -18,21 +18,6 @@ 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); @@ -47,7 +32,7 @@ namespace ExporterLib const uint32 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::Quaternion rotation = transform.mRotation.GetNormalized(); #ifndef EMFX_SCALE_DISABLED AZ::PackedVector3f scale = AZ::PackedVector3f(transform.mScale); @@ -56,14 +41,13 @@ namespace ExporterLib #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); - //nodeChunk.mImportanceFactor = FLT_MAX;//importance; nodeChunk.mNumChilds = numChilds; nodeChunk.mParentIndex = parentIndex; @@ -98,10 +82,6 @@ namespace ExporterLib nodeChunk.mNodeFlags &= ~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) @@ -140,19 +120,13 @@ namespace ExporterLib ConvertUnsignedInt(&nodeChunk.mNumChilds, targetEndianType); ConvertUnsignedInt(&nodeChunk.mSkeletalLODs, targetEndianType); - for (uint32 j = 0; j < 16; ++j) - { - ConvertFloat(&nodeChunk.mOBB[j], 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; @@ -167,10 +141,10 @@ namespace ExporterLib // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODES; - chunkHeader.mVersion = 1; + chunkHeader.mVersion = 2; // get the nodes chunk size - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Nodes) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node); + chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Nodes2) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node2); for (i = 0; i < numNodes; i++) { chunkHeader.mSizeInBytes += GetStringChunkSize(actor->GetSkeleton()->GetNode(i)->GetName()); @@ -181,23 +155,15 @@ namespace ExporterLib file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); // nodes chunk - EMotionFX::FileFormat::Actor_Nodes nodesChunk; + EMotionFX::FileFormat::Actor_Nodes2 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(); // endian conversion and write it ConvertUnsignedInt(&nodesChunk.mNumNodes, targetEndianType); ConvertUnsignedInt(&nodesChunk.mNumRootNodes, targetEndianType); - ConvertFileVector3(&nodesChunk.mStaticBoxMin, targetEndianType); - ConvertFileVector3(&nodesChunk.mStaticBoxMax, 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++) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h index b8a5cc9616..402c70c8a1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h @@ -108,7 +108,7 @@ 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) @@ -117,7 +117,6 @@ namespace EMotionFX 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]; // followed by: // string : node name (the unique name of the node) @@ -200,14 +199,11 @@ namespace EMotionFX // uint16 [mNumNodes] }; - // (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) }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp index 7e7a9ae1c2..ddb240841b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp @@ -355,12 +355,9 @@ namespace EMotionFX return mLoggingActive; } - //================================================================================================= - - // 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; @@ -369,28 +366,12 @@ namespace EMotionFX 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); // pre-allocate space for the nodes actor->SetNumNodes(nodesHeader.mNumNodes); @@ -410,8 +391,8 @@ namespace EMotionFX for (uint32 n = 0; n < nodesHeader.mNumNodes; ++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); @@ -420,7 +401,6 @@ namespace EMotionFX 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); // show the name of the node, the parent and the number of children if (GetLogging()) @@ -453,11 +433,6 @@ namespace EMotionFX 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; @@ -503,23 +478,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", diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h index 306e4af0c8..56822c6940 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h @@ -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..82da9ccd86 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp @@ -352,7 +352,7 @@ namespace EMotionFX } // post create init - actor->PostCreateInit(actorSettings.mMakeGeomLODsCompatibleWithSkeletalLODs, false, actorSettings.mUnitTypeConvert); + actor->PostCreateInit(actorSettings.mMakeGeomLODsCompatibleWithSkeletalLODs, actorSettings.mUnitTypeConvert); } // close the file and return a pointer to the actor we loaded @@ -846,7 +846,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()); From a550827e978d97abb83c1bb4a03aaca4aa5ffdfd Mon Sep 17 00:00:00 2001 From: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> Date: Wed, 4 Aug 2021 14:32:15 -0400 Subject: [PATCH 090/251] Addressing PR Signed-off-by: AMZN-Olex <5432499+AMZN-Olex@users.noreply.github.com> --- .../Code/Source/Debug/MultiplayerDebugByteReporter.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp index f69291013a..45305e3b39 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -43,7 +43,6 @@ namespace Multiplayer { if (m_count == 0) { - AZ_Warning("MultiplayerDebugByteReporter", m_totalBytes == 0, "Attempted to average bytes with a zero count."); return 0.0f; } @@ -158,7 +157,7 @@ namespace Multiplayer if (m_currentComponentReport == nullptr) { std::stringstream component; - component << "[" << std::setw(2) << std::setfill('0') << static_cast(index) << "]" << " " << componentName; + component << "[" << std::setw(2) << std::setfill('0') << aznumeric_cast(index) << "]" << " " << componentName; m_currentComponentReport = &m_componentReports[component.str().c_str()]; } From 4b817a6483560691a5f95a34355c87c8972b05ab Mon Sep 17 00:00:00 2001 From: Shirang Jia Date: Wed, 4 Aug 2021 17:57:47 -0700 Subject: [PATCH 091/251] Include build failure root cause in email notification (#2491) Signed-off-by: shiranj --- scripts/build/Jenkins/Jenkinsfile | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 70618fea78..e693168af0 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -577,13 +577,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) { } From c979ab03385f19970e1a422b23a6d2d9e09d888f Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Wed, 4 Aug 2021 18:26:43 -0700 Subject: [PATCH 092/251] Keep the mutex locked while processing pending notifies. Signed-off-by: dmcdiar --- .../RHI/Code/Include/Atom/RHI/ObjectCollector.h | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h index d79a86afea..3f9fed056f 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h @@ -179,7 +179,6 @@ namespace AZ { m_pendingGarbage.push_back({ AZStd::move(m_pendingObjects), m_currentIteration }); } - m_mutex.unlock(); if (m_pendingNotifies.size()) { @@ -200,25 +199,19 @@ namespace AZ } latestGarbage.m_notifies.insert(latestGarbage.m_notifies.end(), m_pendingNotifies.begin(), m_pendingNotifies.end()); - - m_mutex.lock(); - m_pendingNotifies.clear(); - m_mutex.unlock(); - } else { // garbage queue is empty, notify now - m_mutex.lock(); for (auto& notifyFunction : m_pendingNotifies) { notifyFunction(); } - - m_pendingNotifies.clear(); - m_mutex.unlock(); } + + m_pendingNotifies.clear(); } + m_mutex.unlock(); size_t objectCount = 0; size_t i = 0; From d134deee1dccdfe4f4af64fcafe289377fe02316 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Thu, 5 Aug 2021 15:07:14 +0200 Subject: [PATCH 093/251] Add bounding volume expansion to the actor instance Signed-off-by: Benjamin Jillich --- .../Code/EMotionFX/Source/ActorInstance.cpp | 341 ++++-------------- .../Code/EMotionFX/Source/ActorInstance.h | 84 ++--- 2 files changed, 94 insertions(+), 331 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index b2091f967f..162d826ca4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -67,7 +67,7 @@ namespace EMotionFX mMotionSamplingTimer = 0.0f; mTrajectoryDelta.IdentityWithZeroScale(); - mStaticAABB.Init(); + m_staticAabb = AZ::Aabb::CreateNull(); mAnimGraphInstance = nullptr; @@ -137,15 +137,15 @@ namespace EMotionFX UpdateDependencies(); // update the static based AABB dimensions - mStaticAABB = mActor->GetStaticAABB(); - if (mStaticAABB.CheckIfIsValid() == false) + m_staticAabb = mActor->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, mBoundsUpdateType); // register it GetActorManager().RegisterActorInstance(this); @@ -254,12 +254,12 @@ 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) { - UpdateBounds(mLODLevel, BOUNDS_NODE_BASED, mBoundsUpdateItemFreq); + UpdateBounds(mLODLevel, mBoundsUpdateType, mBoundsUpdateItemFreq); mBoundsUpdatePassedTime = 0.0f; } } @@ -354,7 +354,7 @@ namespace EMotionFX } // update the bounds when needed - if (GetBoundsUpdateEnabled() && mBoundsUpdateType != BOUNDS_MESH_BASED) + if (GetBoundsUpdateEnabled()) { mBoundsUpdatePassedTime += timePassedInSeconds; if (mBoundsUpdatePassedTime >= mBoundsUpdateFrequency) @@ -407,18 +407,6 @@ namespace EMotionFX 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. @@ -439,18 +427,6 @@ namespace EMotionFX 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) @@ -639,118 +615,40 @@ namespace EMotionFX { // 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) + // Expand the bounding volume by a tolerance area in case set. + if (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 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) - { - 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(); @@ -763,16 +661,15 @@ namespace EMotionFX nodeNr = GetEnabledNode(i); if (skeleton->GetNode(nodeNr)->GetIncludeInBoundsCalc()) { - outResult->Encapsulate(pose->GetWorldSpaceTransform(nodeNr).mPosition); + outResult->AddPoint(pose->GetWorldSpaceTransform(nodeNr).mPosition); } } } // 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(uint32 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(); @@ -800,52 +697,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); - } - } - - 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); - if (mesh == nullptr) - { - continue; - } - - if (mesh->GetIsCollisionMesh() == false) - { - 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); + AZ::Aabb meshBox; + mesh->CalcAabb(&meshBox, worldTransform, vertexFrequency); + outResult->AddAabb(meshBox); } } @@ -1567,111 +1421,45 @@ namespace EMotionFX } // 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 (mActor->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; } // calculate the moved static based aabb - void ActorInstance::CalcStaticBasedAABB(MCore::AABB* outResult) + void ActorInstance::CalcStaticBasedAabb(AZ::Aabb* outResult) { if (GetIsSkinAttachment()) { - mSelfAttachment->GetAttachToActorInstance()->CalcStaticBasedAABB(outResult); + mSelfAttachment->GetAttachToActorInstance()->CalcStaticBasedAabb(outResult); return; } - *outResult = mStaticAABB; + *outResult = m_staticAabb; EMFX_SCALECODE( - outResult->SetMin(mStaticAABB.GetMin() * mWorldTransform.mScale); - outResult->SetMax(mStaticAABB.GetMax() * mWorldTransform.mScale);) + outResult->SetMin(m_staticAabb.GetMin() * mWorldTransform.mScale); + outResult->SetMax(m_staticAabb.GetMax() * mWorldTransform.mScale);) outResult->Translate(mWorldTransform.mPosition); } - // adjust the animgraph instance + // adjust the anim graph instance void ActorInstance::SetAnimGraphInstance(AnimGraphInstance* instance) { mAnimGraphInstance = instance; @@ -1774,29 +1562,29 @@ 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 @@ -2018,23 +1806,20 @@ namespace EMotionFX mVisualizeScale = 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; + mVisualizeScale = MCore::Max(mVisualizeScale, 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; + mVisualizeScale = MCore::Max(mVisualizeScale, boxRadius); } mVisualizeScale *= 0.01f; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h index 3567175d6d..4488a1386f 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. */ }; @@ -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. @@ -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(uint32 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); //------------------------------------------------------------------------------------------- @@ -887,8 +864,8 @@ namespace EMotionFX 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. */ + 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 mLocalTransform = Transform::CreateIdentity(); Transform mWorldTransform = Transform::CreateIdentity(); @@ -907,7 +884,7 @@ namespace EMotionFX 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. */ AZStd::unique_ptr m_ragdollInstance; - MCore::Mutex mLock; /**< The multithread lock. */ + MCore::Mutex mLock; /**< The multi-thread lock. */ void* mCustomData; /**< 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. */ @@ -920,7 +897,8 @@ namespace EMotionFX 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). */ + EBoundsType mBoundsUpdateType; /**< 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 mNumAttachmentRefs; /**< Specifies how many actor instances use this actor instance as attachment. */ uint8 mBoolFlags; /**< Boolean flags. */ From 60fa18ec279ba9d39487692ff6a1d943eb920179 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Thu, 5 Aug 2021 15:09:00 +0200 Subject: [PATCH 094/251] Added box expansion percentage to the (editor)actor components Signed-off-by: Benjamin Jillich --- .../Integration/Components/ActorComponent.cpp | 39 ++++++++++--- .../Integration/Components/ActorComponent.h | 21 ++++--- .../Components/EditorActorComponent.cpp | 55 ++++++++++--------- 3 files changed, 71 insertions(+), 44 deletions(-) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index 74133997e4..b033e46a87 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) { diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 0f36846a50..2bf85692be 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; }; /** diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index efc5cbd9a2..ed5333da9c 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 (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, 0.0f) + ->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") From f65bf1a06bc67ca0f425eb15a277876ca56e114e Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Thu, 5 Aug 2021 15:10:16 +0200 Subject: [PATCH 095/251] Increased version in the actor group exporter to automatically reprocess all actors to use the new node chunks Signed-off-by: Benjamin Jillich --- .../EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp index bf79fbf05c..ba8168476c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp @@ -48,7 +48,10 @@ 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. + // Version history: + // v3: Introduced Actor_Nodes2 (replaced Actor_Nodes) and Actor_Node2 (replaced Actor_Node) + serializeContext->Class()->Version(3); } } From 73fee0c57e4206f5b2194b768fcc5d51a5628c72 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 10:39:57 -0400 Subject: [PATCH 096/251] Camera Component, Editor Viewport Widget refactoring. - Handle changing of active camera entirely inside CameraComponentController - Remove a LOT of legacy Cry things related to cameras - Add a CameraSystemComponent to handle ActiveCameraRequestBus and CameraSystemRequestBus Signed-off-by: Yuriy Toporovskyy --- Code/Editor/2DViewport.cpp | 2 +- Code/Editor/AnimationContext.cpp | 9 - Code/Editor/CryEdit.cpp | 117 +- Code/Editor/CryEditDoc.cpp | 2 + Code/Editor/EditorViewportWidget.cpp | 901 ++-- Code/Editor/EditorViewportWidget.h | 577 +-- Code/Editor/Export/ExportManager.cpp | 10 +- Code/Editor/GameEngine.cpp | 9 - Code/Editor/Objects/ObjectManager.cpp | 14 +- Code/Editor/RenderViewport.cpp | 4142 ----------------- Code/Editor/RenderViewport.h | 595 --- Code/Editor/Settings.cpp | 1 + Code/Editor/TrackView/CommentNodeAnimator.cpp | 23 +- .../TrackView/SequenceBatchRenderDialog.cpp | 12 +- Code/Editor/TrackView/TrackViewAnimNode.cpp | 1 + Code/Editor/UndoViewRotation.cpp | 18 +- Code/Editor/UndoViewRotation.h | 2 + Code/Editor/ViewManager.cpp | 11 +- Code/Editor/ViewPane.cpp | 18 - Code/Editor/Viewport.cpp | 1 - Code/Editor/Viewport.h | 14 +- Code/Editor/ViewportTitleDlg.cpp | 32 +- .../AzCore/AzCore/Math/MatrixUtils.cpp | 16 + .../AzCore/AzCore/Math/MatrixUtils.h | 4 + .../AzFramework/Components/CameraBus.h | 3 + Code/Legacy/CryCommon/ISystem.h | 3 - .../CrySystem/LevelSystem/LevelSystem.cpp | 10 +- .../LevelSystem/SpawnableLevelSystem.cpp | 6 +- Code/Legacy/CrySystem/System.h | 4 - .../CrySystem/ViewSystem/DebugCamera.cpp | 16 +- Code/Legacy/CrySystem/ViewSystem/View.cpp | 144 +- .../CrySystem/ViewSystem/ViewSystem.cpp | 39 +- .../Component/DebugCamera/CameraComponent.h | 1 + .../Code/Source/CameraComponent.cpp | 5 + .../Editor/AudioControlsEditorPlugin.cpp | 11 +- Gems/Camera/Code/Source/CameraComponent.cpp | 1 + .../Code/Source/CameraComponentController.cpp | 29 +- .../Code/Source/CameraComponentController.h | 7 +- Gems/Camera/Code/Source/CameraGem.cpp | 3 + .../Code/Source/CameraSystemComponent.cpp | 128 + .../Code/Source/CameraSystemComponent.h | 60 + .../Code/Source/EditorCameraComponent.cpp | 39 +- .../Code/Source/EditorCameraComponent.h | 5 - .../Source/ViewportCameraSelectorWindow.cpp | 95 +- .../ViewportCameraSelectorWindow_Internals.h | 7 +- Gems/Camera/Code/camera_files.cmake | 7 +- .../Code/Source/SystemComponent.cpp | 18 +- 47 files changed, 1126 insertions(+), 6046 deletions(-) create mode 100644 Gems/Camera/Code/Source/CameraSystemComponent.cpp create mode 100644 Gems/Camera/Code/Source/CameraSystemComponent.h diff --git a/Code/Editor/2DViewport.cpp b/Code/Editor/2DViewport.cpp index 56f2e7bdf5..e231792329 100644 --- a/Code/Editor/2DViewport.cpp +++ b/Code/Editor/2DViewport.cpp @@ -952,7 +952,7 @@ void Q2DViewport::DrawViewerMarker(DisplayContext& dc) dc.SetColor(QColor(0, 0, 255)); // blue dc.DrawWireBox(-dim * noScale, dim * noScale); - float fov = GetIEditor()->GetSystem()->GetViewCamera().GetFov(); + float fov = 60; // GetIEditor()->GetSystem()->GetViewCamera().GetFov(); Vec3 q[4]; float dist = 30; diff --git a/Code/Editor/AnimationContext.cpp b/Code/Editor/AnimationContext.cpp index debe5e3b01..b67e9e602e 100644 --- a/Code/Editor/AnimationContext.cpp +++ b/Code/Editor/AnimationContext.cpp @@ -61,15 +61,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. diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 4bfc6a319d..ec2df83ba7 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -3728,24 +3728,24 @@ void CCryEditApp::OnToolsPreferences() ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToDefaultCamera() { - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetDefaultCamera(); - } + //CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); + //if (CRenderViewport* rvp = viewport_cast(vp)) + //{ + // rvp->SetDefaultCamera(); + //} } ////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action) +void CCryEditApp::OnUpdateSwitchToDefaultCamera([[maybe_unused]] 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 + //CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); + //if (false) // (CRenderViewport* rvp = viewport_cast(pViewport)) + //{ + // action->setEnabled(true); + // action->setChecked(rvp->IsDefaultCamera()); + //} + //else { action->setEnabled(false); } @@ -3754,11 +3754,11 @@ void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToSequenceCamera() { - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetSequenceCamera(); - } + //CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); + //if (CRenderViewport* rvp = viewport_cast(vp)) + //{ + // rvp->SetSequenceCamera(); + //} } ////////////////////////////////////////////////////////////////////////// @@ -3766,27 +3766,27 @@ void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action) { Q_ASSERT(action->isCheckable()); - CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); + //CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(pViewport)) - { - bool enableAction = false; + //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()) - { + // // 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); + // AZ::EBusAggregateResults componentCameras; + // Camera::CameraBus::BroadcastResult(componentCameras, &Camera::CameraRequests::GetCameras); - const int numCameras = componentCameras.values.size(); - enableAction = (numCameras > 0); - } + // const int numCameras = componentCameras.values.size(); + // enableAction = (numCameras > 0); + // } - action->setEnabled(enableAction); - action->setChecked(rvp->IsSequenceCamera()); - } - else + // action->setEnabled(enableAction); + // action->setChecked(rvp->IsSequenceCamera()); + //} + //else { action->setEnabled(false); } @@ -3795,31 +3795,32 @@ void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToSelectedcamera() { - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetSelectedCamera(); - } + //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 + (void)action; + //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); } @@ -3828,11 +3829,11 @@ void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchcameraNext() { - CViewport* vp = GetIEditor()->GetActiveView(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->CycleCamera(); - } + //CViewport* vp = GetIEditor()->GetActiveView(); + //if (CRenderViewport* rvp = viewport_cast(vp)) + //{ + // rvp->CycleCamera(); + //} } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp index 43f599b191..feafeec4f5 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 diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 4ea36728ad..c77ef2ef3f 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); @@ -714,7 +620,7 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (m_renderViewport) { - m_renderViewport->SetInputProcessingEnabled(false); + m_renderViewport->GetControllerList()->SetEnabled(false); } } break; @@ -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(); } @@ -1460,13 +1260,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) @@ -1675,7 +1473,6 @@ bool EditorViewportWidget::AddCameraMenuItems(QMenu* menu) menu->addSeparator(); } - AZ::ViewportHelpers::AddCheckbox(menu, "Lock Camera Movement", &m_bLockCameraMovement); menu->addSeparator(); // Camera Sub menu @@ -1692,13 +1489,7 @@ bool EditorViewportWidget::AddCameraMenuItems(QMenu* menu) 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); + //bool enableSequenceCameraMenu = (GetIEditor()->GetAnimation()->GetSequence() && numCameras); QVector additionalCameras; additionalCameras.reserve(getCameraResults.values.size()); @@ -1733,28 +1524,33 @@ 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(); - } - }); + // should this functionality be supported? You can already look through a camera entity + // in multiple different ways, and this additional method of doing so seems unneccessary and confusing + // (since it would select some arbitrary camera entity if there are multiple selected) + + //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; } @@ -1783,28 +1579,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() { @@ -1858,155 +1632,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; +}; + +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 + ); - QtViewport::SetViewTM(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." + ); + } - m_Camera.SetMatrix(camMatrix); + return m_viewEntityId; } ////////////////////////////////////////////////////////////////////////// @@ -2412,14 +2174,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) @@ -2429,12 +2187,6 @@ float EditorViewportWidget::GetScreenScaleFactor(const CCamera& camera, const Ve return dist; } -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::OnDestroy() -{ - DestroyRenderContext(); -} - ////////////////////////////////////////////////////////////////////////// bool EditorViewportWidget::CheckRespondToInput() const { @@ -2454,7 +2206,7 @@ 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); } @@ -2462,8 +2214,12 @@ bool EditorViewportWidget::HitTest(const QPoint& point, HitContext& hitInfo) ////////////////////////////////////////////////////////////////////////// bool EditorViewportWidget::IsBoundsVisible(const AABB& box) const { + AZ_Assert(false, "Not supported"); + (void)box; + return false; + // If at least part of bbox is visible then its visible. - return m_Camera.IsAABBVisible_F(AABB(box.min, box.max)); + //return m_Camera.IsAABBVisible_F(AABB(box.min, box.max)); } ////////////////////////////////////////////////////////////////////////// @@ -2508,11 +2264,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() @@ -2562,130 +2318,123 @@ 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; // AZ::RadToDeg(m_camFOV); + 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) + auto atomViewportRequests = AZ::Interface::Get(); + if (atomViewportRequests) { - // Reset if we were checked before - SetDefaultCamera(); + const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName(); + return atomViewportRequests->GetCurrentView(contextName); } 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() @@ -2733,7 +2482,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()) { @@ -2755,17 +2504,17 @@ 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::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; @@ -2784,12 +2533,12 @@ void EditorViewportWidget::CycleCamera() SetDefaultCamera(); break; } - case EditorViewportWidget::ViewSourceType::AZ_Entity: - { - // we may decide to have this iterate over just selected entities - SetDefaultCamera(); - break; - } + //case EditorViewportWidget::ViewSourceType::AZ_Entity: + //{ + // // we may decide to have this iterate over just selected entities + // SetDefaultCamera(); + // break; + //} default: { SetDefaultCamera(); @@ -2803,11 +2552,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) { - SetEntityAsCamera(entityId, lockCameraMovement); + 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()) + { + EBUS_EVENT_ID(entityId, Camera::CameraRequestBus, MakeActiveView); + } + else + { + // The default camera + SetDefaultCamera(); } } @@ -2822,7 +2588,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; @@ -2836,17 +2602,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( @@ -2859,20 +2634,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(); } ////////////////////////////////////////////////////////////////////////// @@ -2905,11 +2674,6 @@ void EditorViewportWidget::ShowCursor() m_bCursorHidden = false; } -bool EditorViewportWidget::IsKeyDown(Qt::Key key) const -{ - return m_keyDown.contains(key); -} - ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::PushDisableRendering() { @@ -2947,6 +2711,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() { @@ -2960,12 +2735,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; @@ -3041,7 +2810,8 @@ void EditorViewportWidget::RestoreViewportAfterGameMode() } else { - SetViewTM(m_gameTM); + AZ_Error("CryLegacy", false, "Not restoring the editor viewport camera is currently unsupported"); + SetViewTM(preGameModeViewTM); } } @@ -3060,12 +2830,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(); @@ -3125,7 +2889,7 @@ float EditorViewportSettings::AngleStep() const AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once); -bool EditorViewportWidget::ShouldPreviewFullscreen() const +bool EditorViewportWidget::ShouldPreviewFullscreen() { CLayoutWnd* layout = GetIEditor()->GetViewManager()->GetLayout(); if (!layout) @@ -3134,25 +2898,16 @@ bool EditorViewportWidget::ShouldPreviewFullscreen() const return false; } - // Doesn't work with split layout - if (layout->GetLayout() != EViewLayout::ET_Layout0) - { - return false; - } + // Doesn't work with split layout (TODO: figure out why and make it work) + if (layout->GetLayout() != EViewLayout::ET_Layout0) { return false; } // Not supported in VR - if (gSettings.bEnableGameModeVR) - { - return false; - } + if (gSettings.bEnableGameModeVR) { return false; } // If level not loaded, don't preview in fullscreen (preview shouldn't work at all without a level, but it does) if (auto ge = GetIEditor()->GetGameEngine()) { - if (!ge->IsLevelLoaded()) - { - return false; - } + if (!ge->IsLevelLoaded()) { return false; } } // Check 'ed_previewGameInFullscreen_once' @@ -3169,12 +2924,12 @@ bool EditorViewportWidget::ShouldPreviewFullscreen() const void EditorViewportWidget::StartFullscreenPreview() { - AZ_Assert(!m_inFullscreenPreview, "EditorViewportWidget::StartFullscreenPreview called when already in full screen preview"); + AZ_Assert(!m_inFullscreenPreview, AZ_FUNCTION_SIGNATURE " - called when already in full screen preview"); m_inFullscreenPreview = true; // Pick the screen on which the main window lies to use as the screen for the full screen preview - const QScreen* screen = MainWindow::instance()->screen(); - const QRect screenGeometry = screen->geometry(); + QScreen* screen = MainWindow::instance()->screen(); + QRect screenGeometry = screen->geometry(); // Unparent this and show it, which turns it into a free floating window // Also set style to frameless and disable resizing by user diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index 1829995d02..d17a8acb52 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -34,6 +34,7 @@ #include #include #include +#include #endif #include @@ -65,130 +66,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 +195,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 = m_arrAnimatedCharacterPath.size(); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrAnimatedCharacterPath[i] = Vec3(ZERO); - } - - numSample6 = m_arrSmoothEntityPath.size(); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrSmoothEntityPath[i] = Vec3(ZERO); - } - - uint32 numSample7 = 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 +221,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; + double WidgetToViewportFactor() const; - enum class ViewSourceType - { - None, - SequenceCamera, - LegacyCamera, - CameraComponent, - AZ_Entity, - ViewSourceTypesCount, - }; - void ResetToViewSourceType(const ViewSourceType& viewSourType); - - bool ShouldPreviewFullscreen() const; + bool ShouldPreviewFullscreen(); 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/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index 682dcf3980..f1ef96c8f8 100644 --- a/Code/Editor/Export/ExportManager.cpp +++ b/Code/Editor/Export/ExportManager.cpp @@ -662,11 +662,11 @@ bool CExportManager::ProcessObjectsForExport() GetIEditor()->GetAnimation()->SetRecording(false); GetIEditor()->GetAnimation()->SetPlaying(false); - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetSequenceCamera(); - } + //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 dff6476ff9..bb0b1d4547 100644 --- a/Code/Editor/GameEngine.cpp +++ b/Code/Editor/GameEngine.cpp @@ -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) { diff --git a/Code/Editor/Objects/ObjectManager.cpp b/Code/Editor/Objects/ObjectManager.cpp index 58cd016e22..928a864cfb 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. @@ -1327,7 +1331,7 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] pDispayedViewObjects->SetSerialNumber(m_visibilitySerialNumber); // update viewport to be latest serial number - const CCamera& camera = GetIEditor()->GetSystem()->GetViewCamera(); + //const CCamera& camera = GetIEditor()->GetSystem()->GetViewCamera(); AABB bbox; bbox.min.zero(); bbox.max.zero(); @@ -1376,11 +1380,11 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] { CBaseObject* obj = m_visibleObjects[i]; - if (obj && obj->IsInCameraView(camera)) + if (obj /* && obj->IsInCameraView(camera)*/) { // Check if object is too far. - float visRatio = obj->GetCameraVisRatio(camera); - if (visRatio > m_maxObjectViewDistRatio || (dc.flags & DISPLAY_SELECTION_HELPERS) || obj->IsSelected()) + // float visRatio = obj->GetCameraVisRatio(camera); + if (/*visRatio > m_maxObjectViewDistRatio || */ (dc.flags & DISPLAY_SELECTION_HELPERS) || obj->IsSelected()) { pDispayedViewObjects->AddObject(obj); } diff --git a/Code/Editor/RenderViewport.cpp b/Code/Editor/RenderViewport.cpp index d268a57684..e69de29bb2 100644 --- a/Code/Editor/RenderViewport.cpp +++ b/Code/Editor/RenderViewport.cpp @@ -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 = 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(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], 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 index c66d56176e..8f5e19f93d 100644 --- a/Code/Editor/RenderViewport.h +++ b/Code/Editor/RenderViewport.h @@ -51,599 +51,4 @@ 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 = m_arrAnimatedCharacterPath.size(); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrAnimatedCharacterPath[i] = Vec3(ZERO); - } - - numSample6 = m_arrSmoothEntityPath.size(); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrSmoothEntityPath[i] = Vec3(ZERO); - } - - uint32 numSample7 = 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 8f86c74b25..8226081bd6 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -26,6 +26,7 @@ // AzFramework #include +#include // AzToolsFramework #include diff --git a/Code/Editor/TrackView/CommentNodeAnimator.cpp b/Code/Editor/TrackView/CommentNodeAnimator.cpp index 47f4c5d9ae..f01cbc84b4 100644 --- a/Code/Editor/TrackView/CommentNodeAnimator.cpp +++ b/Code/Editor/TrackView/CommentNodeAnimator.cpp @@ -161,16 +161,19 @@ void CCommentNodeAnimator::Render(CTrackViewAnimNode* pNode, [[maybe_unused]] co Vec2 CCommentNodeAnimator::GetScreenPosFromNormalizedPos(const Vec2& unitPos) { - 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); + (void)unitPos; + AZ_Error("CryLegacy", false, "CCommentNodeAnimator::GetScreenPosFromNormalizedPos not supported"); + return Vec2(0, 0); + //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); } 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 7b08b3e614..4f06e3cc84 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 }; @@ -1067,6 +1072,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. @@ -1186,7 +1195,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 c66ea5635c..8696faf516 100644 --- a/Code/Editor/TrackView/TrackViewAnimNode.cpp +++ b/Code/Editor/TrackView/TrackViewAnimNode.cpp @@ -27,6 +27,7 @@ #include #include #include +#include // Editor #include "AnimationContext.h" diff --git a/Code/Editor/UndoViewRotation.cpp b/Code/Editor/UndoViewRotation.cpp index d226a516d1..c3c6f4253a 100644 --- a/Code/Editor/UndoViewRotation.cpp +++ b/Code/Editor/UndoViewRotation.cpp @@ -17,10 +17,24 @@ // Editor #include "ViewManager.h" +#include +#include +#include +#include + +Ang3 CUndoViewRotation::GetActiveCameraRotation() +{ + AZ::Transform activeCameraTm = AZ::Transform::CreateIdentity(); + EBUS_EVENT_RESULT(activeCameraTm, Camera::ActiveCameraRequestBus, 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 +54,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/ViewManager.cpp b/Code/Editor/ViewManager.cpp index 5a3e92a525..88c4823249 100644 --- a/Code/Editor/ViewManager.cpp +++ b/Code/Editor/ViewManager.cpp @@ -80,7 +80,8 @@ CViewManager::CViewManager() } else { - RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); + AZ_Assert(false, "Non-Atom viewport no longer supported"); + //RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); } viewportOptions.viewportType = ET_ViewportMap; @@ -251,10 +252,10 @@ void CViewManager::SelectViewport(CViewport* pViewport) ////////////////////////////////////////////////////////////////////////// CViewport* CViewManager::GetGameViewport() const { - if (CRenderViewport::GetPrimaryViewport()) - { - return CRenderViewport::GetPrimaryViewport(); - } + //if (CRenderViewport::GetPrimaryViewport()) + //{ + // return CRenderViewport::GetPrimaryViewport(); + //} return GetViewport(ET_ViewportCamera);; } diff --git a/Code/Editor/ViewPane.cpp b/Code/Editor/ViewPane.cpp index 19b653b865..b4af87775c 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 906a60ac47..ba310cb52d 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 = 0; diff --git a/Code/Editor/Viewport.h b/Code/Editor/Viewport.h index c94a77b06e..5b4f23fd2b 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 4d27506929..6d2d91f546 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/Framework/AzCore/AzCore/Math/MatrixUtils.cpp b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp index a578640d0d..c5b76cbab7 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 * 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/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/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/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index e8cc4d484c..27dead077c 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -620,9 +620,9 @@ 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); + //CCamera defaultCam; + //defaultCam.SetPosition(Vec3(1.0f)); + //m_pSystem->SetViewCamera(defaultCam); m_pLoadingLevelInfo = pLevelInfo; OnLoadingStart(levelName); @@ -953,8 +953,8 @@ void CLevelSystem::UnloadLevel() 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); + //CCamera defaultCam; + //m_pSystem->SetViewCamera(defaultCam); OnUnloadComplete(m_lastLevelName.c_str()); diff --git a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 103d5999f7..962469532d 100644 --- a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -272,7 +272,7 @@ namespace LegacyLevelSystem // 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_pSystem->SetViewCamera(defaultCam); OnLoadingStart(levelName); @@ -588,8 +588,8 @@ namespace LegacyLevelSystem 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); + //CCamera defaultCam; + //m_pSystem->SetViewCamera(defaultCam); OnUnloadComplete(m_lastLevelName.c_str()); 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/ViewSystem/DebugCamera.cpp b/Code/Legacy/CrySystem/ViewSystem/DebugCamera.cpp index e8d21c961f..8bf5c4eee3 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; // gEnv->pSystem->GetViewCamera().GetPosition(); m_moveInput = Vec3_Zero; - Ang3 cameraAngles = Ang3(gEnv->pSystem->GetViewCamera().GetMatrix()); + Ang3 cameraAngles = Ang3(ZERO); // Ang3(gEnv->pSystem->GetViewCamera().GetMatrix()); 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,13 @@ void DebugCamera::Update() /////////////////////////////////////////////////////////////////////////////// void DebugCamera::PostUpdate() { - if (m_cameraMode == DebugCamera::ModeOff) - { - return; - } + //if (m_cameraMode == DebugCamera::ModeOff) + //{ + // return; + //} - CCamera& camera = gEnv->pSystem->GetViewCamera(); - camera.SetMatrix(Matrix34(m_view, m_position)); + //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 ef9f2591c4..26f75ced76 100644 --- a/Code/Legacy/CrySystem/ViewSystem/View.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/View.cpp @@ -57,77 +57,79 @@ void CView::Release() //------------------------------------------------------------------------ void CView::Update(float frameTime, 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); - } + (void)(frameTime, isActive); + AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CView::Update)"); + ////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); + //} } //----------------------------------------------------------------------- diff --git a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp index a82e78c08c..575c373dcd 100644 --- a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp @@ -253,7 +253,8 @@ void CViewSystem::Update(float frameTime) } } - m_pSystem->SetViewCamera(rCamera); + AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CViewSystem::Update)"); + //m_pSystem->SetViewCamera(rCamera); } } @@ -557,23 +558,25 @@ 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)"); + + //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()); + // } + //} } ////////////////////////////////////////////////////////////////// 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/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp index b318cea128..2a97bdfb92 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,21 @@ 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(); + EBUS_EVENT_RESULT(activeCameraTm, Camera::ActiveCameraRequestBus, 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/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..a81ef1c9ae 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") @@ -130,6 +131,11 @@ namespace Camera void CameraComponentController::DeactivateAtomView() { + if (!IsActiveView()) + { + return; + } + auto atomViewportRequests = AZ::Interface::Get(); if (atomViewportRequests) { @@ -413,6 +419,11 @@ namespace Camera void CameraComponentController::MakeActiveView() { + if (IsActiveView()) + { + return; + } + // Set Legacy Cry view, if it exists if (m_viewSystem) { @@ -433,6 +444,11 @@ namespace Camera CameraNotificationBus::Broadcast(&CameraNotificationBus::Events::OnActiveViewChanged, m_entityId); } + bool CameraComponentController::IsActiveView() + { + return AZ::RPI::ViewportContextNotificationBus::Handler::BusIsConnected(); + } + void CameraComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) { if (m_updatingTransformFromEntity) @@ -459,6 +475,17 @@ namespace Camera UpdateCamera(); } + void CameraComponentController::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) + { + if (m_atomCamera != view) + { + // Note that when disconnected from this bus, this signals that we are not the active view + // There is nothing else to do here: leave our view on the viewport context stack, don't need + // to update properties. The viewport context system should handle it all! + AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(); + } + } + AZ::RPI::ViewPtr CameraComponentController::GetView() const { return m_atomCamera; diff --git a/Gems/Camera/Code/Source/CameraComponentController.h b/Gems/Camera/Code/Source/CameraComponentController.h index c004dbe6ec..3d7844e6ac 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); 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..1202e29e20 --- /dev/null +++ b/Gems/Camera/Code/Source/CameraSystemComponent.cpp @@ -0,0 +1,128 @@ +/* + * 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 + +namespace Camera +{ + void CameraSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ; + } + } + + void CameraSystemComponent::Activate() + { + CameraSystemRequestBus::Handler::BusConnect(); + ActiveCameraRequestBus::Handler::BusConnect(); + CameraNotificationBus::Handler::BusConnect(); + } + + void CameraSystemComponent::Deactivate() + { + CameraSystemRequestBus::Handler::BusDisconnect(); + ActiveCameraRequestBus::Handler::BusDisconnect(); + CameraNotificationBus::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())) + { + const auto& viewToClip = view->GetViewToClipMatrix(); + cfg.m_fovRadians = AZ::GetPerspectiveMatrixFOV(viewToClip); + + // A = f / (n - f) + // B = n * f / (n - f) + // Then... + // B / A + // = (n * f / (n - f)) / (f / (n - f)) + // = (n * f) / (f) + // = n + // and... + // n * f / (n - f) = B + // n * ((n - f) / f)^-1 = B + // n * (n/f - 1)^-1 = B + // (n/f - 1)^-1 = B/n + // n/f - 1 = n/B + // f = n/(n/B + 1) + const float A = viewToClip.GetElement(2, 2); + const float B = viewToClip.GetElement(2, 3); + cfg.m_nearClipDistance = B / A; + cfg.m_farClipDistance = cfg.m_nearClipDistance / (cfg.m_nearClipDistance / B + 1.f); + + // NB: assumes reversed depth! + AZStd::swap(cfg.m_farClipDistance, cfg.m_nearClipDistance); + + // 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..726975ff9d --- /dev/null +++ b/Gems/Camera/Code/Source/CameraSystemComponent.h @@ -0,0 +1,60 @@ +/* + * 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; + }; +} 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 9644aa76f9..0a12ec60e0 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 { @@ -83,8 +84,8 @@ namespace Camera return m_cameraId < rhs.m_cameraId; } - CameraListModel::CameraListModel(QObject* myParent) - : QAbstractListModel(myParent) + CameraListModel::CameraListModel(ViewportCameraSelectorWindow* myParent) + : QAbstractListModel(myParent), m_parent(myParent) { m_cameraItems.push_back(AZ::EntityId()); CameraNotificationBus::Handler::BusConnect(); @@ -120,6 +121,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(); @@ -143,38 +156,38 @@ namespace Camera ////////////////////////////////////////////////////////////////////////// /// Maestro::EditorSequenceNotificationBus::Handler - void CameraListModel::OnSequenceSelected(const AZ::EntityId& sequenceEntityId) + void CameraListModel::OnSequenceSelected(const AZ::EntityId& ) { // 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(); - } + //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) @@ -191,7 +204,7 @@ namespace Camera return index(row, 0); } - const char* CameraListModel::m_sequenceCameraName = "Sequence camera"; + //const char* CameraListModel::m_sequenceCameraName = "Sequence camera"; ViewportCameraSelectorWindow::ViewportCameraSelectorWindow(QWidget* parent) : m_ignoreViewportViewEntityChanged(false) @@ -242,8 +255,9 @@ 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); + //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(); @@ -298,14 +312,15 @@ namespace Camera 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); - } + AZ_UNUSED(newCameraEntityId); + + //// 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 diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h index a681d049c3..74a7b292f3 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h @@ -46,6 +46,8 @@ namespace Camera AZ::EntityId m_sequenceId; }; + struct ViewportCameraSelectorWindow; + // holds a list of camera items struct CameraListModel : public QAbstractListModel @@ -54,9 +56,9 @@ namespace Camera { public: - static const char* m_sequenceCameraName; + //static const char* m_sequenceCameraName; - CameraListModel(QObject* myParent); + CameraListModel(ViewportCameraSelectorWindow* myParent); ~CameraListModel(); // QAbstractItemModel interface @@ -76,6 +78,7 @@ namespace Camera AZStd::vector m_cameraItems; AZ::EntityId m_sequenceCameraEntityId; bool m_sequenceCameraSelected; + ViewportCameraSelectorWindow* m_parent; }; struct ViewportCameraSelectorWindow diff --git a/Gems/Camera/Code/camera_files.cmake b/Gems/Camera/Code/camera_files.cmake index 295589e453..4848653121 100644 --- a/Gems/Camera/Code/camera_files.cmake +++ b/Gems/Camera/Code/camera_files.cmake @@ -1,7 +1,6 @@ # -# 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. -# +# 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 # # @@ -9,6 +8,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/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 96da22480d..97cb4f33d3 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 namespace Camera; + + 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())) { From 2079b274c32eb7414327146bd27a5a5521564d8c Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 16:16:17 -0400 Subject: [PATCH 097/251] Fixup merge errors Signed-off-by: Yuriy Toporovskyy --- Code/Editor/EditorViewportWidget.cpp | 23 ++++++++++++++++------- Code/Editor/EditorViewportWidget.h | 2 +- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index c77ef2ef3f..b4e844adb4 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -2898,16 +2898,25 @@ bool EditorViewportWidget::ShouldPreviewFullscreen() return false; } - // Doesn't work with split layout (TODO: figure out why and make it work) - if (layout->GetLayout() != EViewLayout::ET_Layout0) { return false; } + // Doesn't work with split layout + if (layout->GetLayout() != EViewLayout::ET_Layout0) + { + return false; + } // Not supported in VR - if (gSettings.bEnableGameModeVR) { return false; } + if (gSettings.bEnableGameModeVR) + { + return false; + } // If level not loaded, don't preview in fullscreen (preview shouldn't work at all without a level, but it does) if (auto ge = GetIEditor()->GetGameEngine()) { - if (!ge->IsLevelLoaded()) { return false; } + if (!ge->IsLevelLoaded()) + { + return false; + } } // Check 'ed_previewGameInFullscreen_once' @@ -2924,12 +2933,12 @@ bool EditorViewportWidget::ShouldPreviewFullscreen() void EditorViewportWidget::StartFullscreenPreview() { - AZ_Assert(!m_inFullscreenPreview, AZ_FUNCTION_SIGNATURE " - called when already in full screen preview"); + AZ_Assert(!m_inFullscreenPreview, "EditorViewportWidget::StartFullscreenPreview called when already in full screen preview"); m_inFullscreenPreview = true; // Pick the screen on which the main window lies to use as the screen for the full screen preview - QScreen* screen = MainWindow::instance()->screen(); - QRect screenGeometry = screen->geometry(); + const QScreen* screen = MainWindow::instance()->screen(); + const QRect screenGeometry = screen->geometry(); // Unparent this and show it, which turns it into a free floating window // Also set style to frameless and disable resizing by user diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index d17a8acb52..dabbbe95f6 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -232,7 +232,7 @@ private: double WidgetToViewportFactor() const; - bool ShouldPreviewFullscreen(); + bool ShouldPreviewFullscreen() const; void StartFullscreenPreview(); void StopFullscreenPreview(); From 9d9ce7cc3356e41eac4f3699158b497011f918f5 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 16:20:03 -0400 Subject: [PATCH 098/251] Fixup merge errors Signed-off-by: Yuriy Toporovskyy --- Code/Editor/EditorViewportWidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index b4e844adb4..2d5171a0e9 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -620,7 +620,7 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (m_renderViewport) { - m_renderViewport->GetControllerList()->SetEnabled(false); + m_renderViewport->SetInputProcessingEnabled(false); } } break; From 590de17343cb52e4f4cfcf93ce872d6c0cabf328 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 16:35:10 -0400 Subject: [PATCH 099/251] Delete code which was only commented out Signed-off-by: Yuriy Toporovskyy --- Code/Editor/2DViewport.cpp | 3 +- Code/Editor/CryEdit.cpp | 67 +---------------- Code/Editor/EditorViewportWidget.cpp | 54 +------------- Code/Editor/Export/ExportManager.cpp | 6 -- Code/Editor/Objects/ObjectManager.cpp | 7 +- Code/Editor/ViewManager.cpp | 6 -- .../CrySystem/LevelSystem/LevelSystem.cpp | 10 --- .../LevelSystem/SpawnableLevelSystem.cpp | 10 --- .../CrySystem/ViewSystem/DebugCamera.cpp | 11 +-- Code/Legacy/CrySystem/ViewSystem/View.cpp | 71 ------------------- .../CrySystem/ViewSystem/ViewSystem.cpp | 19 ----- .../Source/ViewportCameraSelectorWindow.cpp | 43 ----------- .../ViewportCameraSelectorWindow_Internals.h | 3 - 13 files changed, 11 insertions(+), 299 deletions(-) diff --git a/Code/Editor/2DViewport.cpp b/Code/Editor/2DViewport.cpp index e231792329..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 = 60; // GetIEditor()->GetSystem()->GetViewCamera().GetFov(); + constexpr float DefaultFov = 60.f; + float fov = DefaultFov; Vec3 q[4]; float dist = 30; diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index ec2df83ba7..96836c9f1e 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -3728,24 +3728,12 @@ void CCryEditApp::OnToolsPreferences() ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToDefaultCamera() { - //CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - //if (CRenderViewport* rvp = viewport_cast(vp)) - //{ - // rvp->SetDefaultCamera(); - //} } ////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnUpdateSwitchToDefaultCamera([[maybe_unused]] QAction* action) +void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action) { Q_ASSERT(action->isCheckable()); - //CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); - //if (false) // (CRenderViewport* rvp = viewport_cast(pViewport)) - //{ - // action->setEnabled(true); - // action->setChecked(rvp->IsDefaultCamera()); - //} - //else { action->setEnabled(false); } @@ -3754,39 +3742,12 @@ void CCryEditApp::OnUpdateSwitchToDefaultCamera([[maybe_unused]] 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); } @@ -3795,32 +3756,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()); - (void)action; - //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); } @@ -3829,11 +3770,7 @@ void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchcameraNext() { - //CViewport* vp = GetIEditor()->GetActiveView(); - //if (CRenderViewport* rvp = viewport_cast(vp)) - //{ - // rvp->CycleCamera(); - //} + } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 2d5171a0e9..73b0483592 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -1524,33 +1524,6 @@ bool EditorViewportWidget::AddCameraMenuItems(QMenu* menu) customCameraMenu->addAction(cameraAction); } - // should this functionality be supported? You can already look through a camera entity - // in multiple different ways, and this additional method of doing so seems unneccessary and confusing - // (since it would select some arbitrary camera entity if there are multiple selected) - - //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; } @@ -2212,14 +2185,10 @@ bool EditorViewportWidget::HitTest(const QPoint& point, HitContext& hitInfo) } ////////////////////////////////////////////////////////////////////////// -bool EditorViewportWidget::IsBoundsVisible(const AABB& box) const +bool EditorViewportWidget::IsBoundsVisible(const AABB&) const { AZ_Assert(false, "Not supported"); - (void)box; return false; - - // If at least part of bbox is visible then its visible. - //return m_Camera.IsAABBVisible_F(AABB(box.min, box.max)); } ////////////////////////////////////////////////////////////////////////// @@ -2333,7 +2302,7 @@ float EditorViewportWidget::GetFOV() const { if (m_viewEntityId.IsValid()) { - float fov = 0.f; // AZ::RadToDeg(m_camFOV); + float fov = 0.f; Camera::CameraRequestBus::EventResult(fov, m_viewEntityId, &Camera::CameraComponentRequests::GetFovRadians); return fov; } @@ -2504,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; @@ -2533,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(); @@ -2889,7 +2841,7 @@ float EditorViewportSettings::AngleStep() const AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once); -bool EditorViewportWidget::ShouldPreviewFullscreen() +bool EditorViewportWidget::ShouldPreviewFullscreen() const { CLayoutWnd* layout = GetIEditor()->GetViewManager()->GetLayout(); if (!layout) diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index f1ef96c8f8..0d114d5da8 100644 --- a/Code/Editor/Export/ExportManager.cpp +++ b/Code/Editor/Export/ExportManager.cpp @@ -662,12 +662,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/Objects/ObjectManager.cpp b/Code/Editor/Objects/ObjectManager.cpp index 928a864cfb..33926c2174 100644 --- a/Code/Editor/Objects/ObjectManager.cpp +++ b/Code/Editor/Objects/ObjectManager.cpp @@ -1331,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(); @@ -1380,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); } diff --git a/Code/Editor/ViewManager.cpp b/Code/Editor/ViewManager.cpp index 88c4823249..4f39f862e4 100644 --- a/Code/Editor/ViewManager.cpp +++ b/Code/Editor/ViewManager.cpp @@ -81,7 +81,6 @@ CViewManager::CViewManager() else { AZ_Assert(false, "Non-Atom viewport no longer supported"); - //RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); } viewportOptions.viewportType = ET_ViewportMap; @@ -252,11 +251,6 @@ void CViewManager::SelectViewport(CViewport* pViewport) ////////////////////////////////////////////////////////////////////////// CViewport* CViewManager::GetGameViewport() const { - //if (CRenderViewport::GetPrimaryViewport()) - //{ - // return CRenderViewport::GetPrimaryViewport(); - //} - return GetViewport(ET_ViewportCamera);; } diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index 27dead077c..dc2526f213 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 962469532d..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/ViewSystem/DebugCamera.cpp b/Code/Legacy/CrySystem/ViewSystem/DebugCamera.cpp index 8bf5c4eee3..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 = Vec3_Zero; // gEnv->pSystem->GetViewCamera().GetPosition(); + m_position = Vec3_Zero; m_moveInput = Vec3_Zero; - Ang3 cameraAngles = Ang3(ZERO); // 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 26f75ced76..610d6b4a14 100644 --- a/Code/Legacy/CrySystem/ViewSystem/View.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/View.cpp @@ -59,77 +59,6 @@ void CView::Update(float frameTime, bool isActive) { (void)(frameTime, isActive); AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CView::Update)"); - ////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); - //} } //----------------------------------------------------------------------- diff --git a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp index 575c373dcd..28cf0eb07a 100644 --- a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp @@ -254,7 +254,6 @@ void CViewSystem::Update(float frameTime) } AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CViewSystem::Update)"); - //m_pSystem->SetViewCamera(rCamera); } } @@ -559,24 +558,6 @@ void CViewSystem::SetOverrideCameraRotation(bool bOverride, Quat rotation) void CViewSystem::UpdateSoundListeners() { AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (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()); - // } - //} } ////////////////////////////////////////////////////////////////// diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp index 0a12ec60e0..edd39772e0 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp @@ -158,36 +158,6 @@ namespace Camera /// Maestro::EditorSequenceNotificationBus::Handler void CameraListModel::OnSequenceSelected(const AZ::EntityId& ) { - // 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) @@ -204,8 +174,6 @@ namespace Camera return index(row, 0); } - //const char* CameraListModel::m_sequenceCameraName = "Sequence camera"; - ViewportCameraSelectorWindow::ViewportCameraSelectorWindow(QWidget* parent) : m_ignoreViewportViewEntityChanged(false) { @@ -254,9 +222,6 @@ 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); @@ -313,14 +278,6 @@ namespace Camera { AZ_UNUSED(oldCameraEntityId); AZ_UNUSED(newCameraEntityId); - - //// 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 diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h index 74a7b292f3..a4d662ef8b 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h @@ -55,9 +55,6 @@ namespace Camera , public Maestro::EditorSequenceNotificationBus::Handler { public: - - //static const char* m_sequenceCameraName; - CameraListModel(ViewportCameraSelectorWindow* myParent); ~CameraListModel(); From 62214567c1b0a7f3b8723b232fc499f0ccee2177 Mon Sep 17 00:00:00 2001 From: yuriy0 Date: Wed, 4 Aug 2021 16:38:57 -0400 Subject: [PATCH 100/251] Handle non-default viewport context Co-authored-by: Nicholas Van Sickle Signed-off-by: Yuriy Toporovskyy --- Code/Editor/EditorViewportWidget.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 73b0483592..32b308ae9b 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -2382,7 +2382,10 @@ void EditorViewportWidget::SetDefaultCamera() ////////////////////////////////////////////////////////////////////////// AZ::RPI::ViewPtr EditorViewportWidget::GetCurrentAtomView() const { - auto atomViewportRequests = AZ::Interface::Get(); +if (m_renderViewport && m_renderViewport->GetViewportContext()) +{ + return m_viewportContext->GetDefaultView(); +} if (atomViewportRequests) { const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName(); From 83099a7f5b44bda1827e02cdc1c45519491307de Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 16:42:59 -0400 Subject: [PATCH 101/251] Update mocks for ISystem changes Signed-off-by: Yuriy Toporovskyy --- Code/Legacy/CryCommon/Mocks/ISystemMock.h | 4 ---- .../Code/Tests/UI/LODSkinnedMeshTests.cpp | 14 -------------- 2 files changed, 18 deletions(-) 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/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp index 4b48936c88..9a11d1bd4b 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 @@ -207,7 +195,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 +204,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{}); From ca96f0055d6b93e1939539de3640dfcc4b29fa5f Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 16:48:41 -0400 Subject: [PATCH 102/251] Remove TrackView-related camera logic TrackView uses 'normal' camera entities now Signed-off-by: Yuriy Toporovskyy --- .../Source/ViewportCameraSelectorWindow.cpp | 62 +------------------ .../ViewportCameraSelectorWindow_Internals.h | 29 +-------- 2 files changed, 3 insertions(+), 88 deletions(-) diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp index edd39772e0..61f921d019 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp @@ -39,7 +39,6 @@ namespace Camera { CameraListItem::CameraListItem(const AZ::EntityId& cameraId) : m_cameraId(cameraId) - , m_sequenceId(AZ::EntityId()) { if (cameraId.IsValid()) { @@ -52,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(ViewportCameraSelectorWindow* myParent) - : QAbstractListModel(myParent), m_parent(myParent) + CameraListModel::CameraListModel(QWidget* myParent) + : QAbstractListModel(myParent) { m_cameraItems.push_back(AZ::EntityId()); CameraNotificationBus::Handler::BusConnect(); - Maestro::EditorSequenceNotificationBus::Handler::BusConnect(); } CameraListModel::~CameraListModel() @@ -97,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(); } @@ -154,12 +132,6 @@ namespace Camera } } - ////////////////////////////////////////////////////////////////////////// - /// Maestro::EditorSequenceNotificationBus::Handler - void CameraListModel::OnSequenceSelected(const AZ::EntityId& ) - { - } - QModelIndex CameraListModel::GetIndexForEntityId(const AZ::EntityId entityId) { int row = 0; @@ -203,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(); } @@ -257,29 +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); - AZ_UNUSED(newCameraEntityId); - } - // 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 a4d662ef8b..e75a820eec 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,37 +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; }; - struct ViewportCameraSelectorWindow; - // holds a list of camera items struct CameraListModel : public QAbstractListModel , public CameraNotificationBus::Handler - , public Maestro::EditorSequenceNotificationBus::Handler { public: - CameraListModel(ViewportCameraSelectorWindow* myParent); + CameraListModel(QWidget* myParent); ~CameraListModel(); // QAbstractItemModel interface @@ -66,24 +53,18 @@ 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: AZStd::vector m_cameraItems; AZ::EntityId m_sequenceCameraEntityId; bool m_sequenceCameraSelected; - ViewportCameraSelectorWindow* m_parent; }; struct ViewportCameraSelectorWindow : 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; From 70adac4f9678d762694b0c8fe0885ec3f984283e Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 16:59:50 -0400 Subject: [PATCH 103/251] Remove ed_useAtomNativeViewport - Legacy Cry viewport no longer supported Signed-off-by: Yuriy Toporovskyy --- Code/Editor/ViewManager.cpp | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/Code/Editor/ViewManager.cpp b/Code/Editor/ViewManager.cpp index 4f39f862e4..2ccbac09ed 100644 --- a/Code/Editor/ViewManager.cpp +++ b/Code/Editor/ViewManager.cpp @@ -32,12 +32,10 @@ #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 +72,7 @@ CViewManager::CViewManager() RegisterQtViewPane(GetIEditor(), "Left", LyViewPane::CategoryViewport, viewportOptions); viewportOptions.viewportType = ET_ViewportCamera; - if (ed_useAtomNativeViewport) - { - RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); - } - else - { - AZ_Assert(false, "Non-Atom viewport no longer supported"); - } + RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); viewportOptions.viewportType = ET_ViewportMap; RegisterQtViewPane(GetIEditor(), "Map", LyViewPane::CategoryViewport, viewportOptions); From e82342dce0957b6068b994978ed0a36075f3b1bd Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 17:19:46 -0400 Subject: [PATCH 104/251] Delete code which was only commented out Signed-off-by: Yuriy Toporovskyy --- Code/Editor/TrackView/CommentNodeAnimator.cpp | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/Code/Editor/TrackView/CommentNodeAnimator.cpp b/Code/Editor/TrackView/CommentNodeAnimator.cpp index f01cbc84b4..ee01656938 100644 --- a/Code/Editor/TrackView/CommentNodeAnimator.cpp +++ b/Code/Editor/TrackView/CommentNodeAnimator.cpp @@ -159,21 +159,10 @@ void CCommentNodeAnimator::Render(CTrackViewAnimNode* pNode, [[maybe_unused]] co } } -Vec2 CCommentNodeAnimator::GetScreenPosFromNormalizedPos(const Vec2& unitPos) +Vec2 CCommentNodeAnimator::GetScreenPosFromNormalizedPos(const Vec2&) { - (void)unitPos; AZ_Error("CryLegacy", false, "CCommentNodeAnimator::GetScreenPosFromNormalizedPos not supported"); return Vec2(0, 0); - //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); } void CCommentNodeAnimator::DrawText(const char* szFontName, float fSize, const Vec2& unitPos, const ColorF col, const char* szText, int align) From bb36a4d40c42eb9dcb3c570119dbb65596159a41 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 17:20:21 -0400 Subject: [PATCH 105/251] Style Signed-off-by: Yuriy Toporovskyy --- Code/Legacy/CrySystem/ViewSystem/View.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Code/Legacy/CrySystem/ViewSystem/View.cpp b/Code/Legacy/CrySystem/ViewSystem/View.cpp index 610d6b4a14..e1191f0a17 100644 --- a/Code/Legacy/CrySystem/ViewSystem/View.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/View.cpp @@ -55,9 +55,8 @@ void CView::Release() } //------------------------------------------------------------------------ -void CView::Update(float frameTime, bool isActive) +void CView::Update([[maybe_unused]] float frameTime, [[maybe_unused]] bool isActive) { - (void)(frameTime, isActive); AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CView::Update)"); } From bf361c2c13c9b8ec77dd855375ee79e76a04ff22 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 17:20:45 -0400 Subject: [PATCH 106/251] Handle the case where a camera deactivates and the previous camera on the stack should become the active view Signed-off-by: Yuriy Toporovskyy --- .../Code/Source/CameraComponentController.cpp | 24 ++++++++++--------- .../Code/Source/CameraComponentController.h | 1 + 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/Gems/Camera/Code/Source/CameraComponentController.cpp b/Gems/Camera/Code/Source/CameraComponentController.cpp index a81ef1c9ae..a8b5b8992e 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.cpp +++ b/Gems/Camera/Code/Source/CameraComponentController.cpp @@ -115,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); @@ -125,7 +132,6 @@ 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); } } @@ -140,7 +146,6 @@ namespace Camera if (atomViewportRequests) { const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName(); - AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(contextName); atomViewportRequests->PopView(contextName, m_atomCamera); } } @@ -446,7 +451,7 @@ namespace Camera bool CameraComponentController::IsActiveView() { - return AZ::RPI::ViewportContextNotificationBus::Handler::BusIsConnected(); + return m_isActiveView; } void CameraComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) @@ -472,18 +477,15 @@ namespace Camera void CameraComponentController::OnViewportSizeChanged([[maybe_unused]] AzFramework::WindowSize size) { - UpdateCamera(); + if (IsActiveView()) + { + UpdateCamera(); + } } void CameraComponentController::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) { - if (m_atomCamera != view) - { - // Note that when disconnected from this bus, this signals that we are not the active view - // There is nothing else to do here: leave our view on the viewport context stack, don't need - // to update properties. The viewport context system should handle it all! - AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(); - } + 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 3d7844e6ac..923da65618 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.h +++ b/Gems/Camera/Code/Source/CameraComponentController.h @@ -132,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; From 83e43dd517a06e82a1b2f8acb840316c6b68e750 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 17:38:19 -0400 Subject: [PATCH 107/251] Re-use existing code Signed-off-by: Yuriy Toporovskyy --- .../Code/Source/CameraSystemComponent.cpp | 32 +++++-------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/Gems/Camera/Code/Source/CameraSystemComponent.cpp b/Gems/Camera/Code/Source/CameraSystemComponent.cpp index 1202e29e20..7c7dac429d 100644 --- a/Gems/Camera/Code/Source/CameraSystemComponent.cpp +++ b/Gems/Camera/Code/Source/CameraSystemComponent.cpp @@ -10,6 +10,8 @@ #include #include +#include + #include #include @@ -87,30 +89,12 @@ namespace Camera { if (auto view = viewSystem->GetCurrentView(viewSystem->GetDefaultViewportContextName())) { - const auto& viewToClip = view->GetViewToClipMatrix(); - cfg.m_fovRadians = AZ::GetPerspectiveMatrixFOV(viewToClip); - - // A = f / (n - f) - // B = n * f / (n - f) - // Then... - // B / A - // = (n * f / (n - f)) / (f / (n - f)) - // = (n * f) / (f) - // = n - // and... - // n * f / (n - f) = B - // n * ((n - f) / f)^-1 = B - // n * (n/f - 1)^-1 = B - // (n/f - 1)^-1 = B/n - // n/f - 1 = n/B - // f = n/(n/B + 1) - const float A = viewToClip.GetElement(2, 2); - const float B = viewToClip.GetElement(2, 3); - cfg.m_nearClipDistance = B / A; - cfg.m_farClipDistance = cfg.m_nearClipDistance / (cfg.m_nearClipDistance / B + 1.f); - - // NB: assumes reversed depth! - AZStd::swap(cfg.m_farClipDistance, cfg.m_nearClipDistance); + 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; From b221ec3024c2486d1cccba3bbf80ce8de22fca05 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Thu, 5 Aug 2021 10:12:24 -0400 Subject: [PATCH 108/251] Merge fixup Signed-off-by: Yuriy Toporovskyy --- Gems/Camera/Code/camera_files.cmake | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Gems/Camera/Code/camera_files.cmake b/Gems/Camera/Code/camera_files.cmake index 4848653121..26769b071c 100644 --- a/Gems/Camera/Code/camera_files.cmake +++ b/Gems/Camera/Code/camera_files.cmake @@ -1,6 +1,7 @@ # -# 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. -# +# 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 # # From a85b97d9ac28cb666d2f6bff23496243609ab63a Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Thu, 5 Aug 2021 10:19:16 -0400 Subject: [PATCH 109/251] Remove unused code Signed-off-by: Yuriy Toporovskyy --- Code/Editor/EditorViewportWidget.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 32b308ae9b..22e6fb9803 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -1486,11 +1486,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); - QVector additionalCameras; additionalCameras.reserve(getCameraResults.values.size()); From ba33dd44334b417f82adccc85b1db2b97dc3b072 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Thu, 5 Aug 2021 10:27:24 -0400 Subject: [PATCH 110/251] Fix strange commit which was automatically created by Githubs 'Suggested Change' feature. Signed-off-by: Yuriy Toporovskyy --- Code/Editor/EditorViewportWidget.cpp | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 22e6fb9803..b205ca5b78 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -2377,14 +2377,9 @@ void EditorViewportWidget::SetDefaultCamera() ////////////////////////////////////////////////////////////////////////// AZ::RPI::ViewPtr EditorViewportWidget::GetCurrentAtomView() const { -if (m_renderViewport && m_renderViewport->GetViewportContext()) -{ - return m_viewportContext->GetDefaultView(); -} - if (atomViewportRequests) + if (m_renderViewport && m_renderViewport->GetViewportContext()) { - const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName(); - return atomViewportRequests->GetCurrentView(contextName); + return m_renderViewport->GetViewportContext()->GetDefaultView(); } else { From 0d0d94f575dfed5f1cf8c83b0841017501cc42a6 Mon Sep 17 00:00:00 2001 From: Nemerle Date: Thu, 5 Aug 2021 16:46:38 +0200 Subject: [PATCH 111/251] Editor code: tidy up BOOLs,NULLs and overrides pt2. A few 'typedefs' replaced by 'using's This shouldn't have any functional changes at all, just c++17 modernization It's a part 2 of a split #2847 Signed-off-by: Nemerle --- Code/Editor/Lib/Tests/test_EditorUtils.cpp | 4 +- Code/Editor/Lib/Tests/test_Main.cpp | 2 +- Code/Editor/Objects/BaseObject.cpp | 60 ++++++------- Code/Editor/Objects/BaseObject.h | 16 ++-- Code/Editor/Objects/EntityObject.cpp | 50 +++++------ Code/Editor/Objects/EntityObject.h | 2 +- Code/Editor/Objects/Gizmo.h | 2 +- Code/Editor/Objects/GizmoManager.cpp | 2 +- Code/Editor/Objects/LineGizmo.cpp | 6 +- Code/Editor/Objects/ObjectLoader.cpp | 14 +-- Code/Editor/Objects/ObjectLoader.h | 2 +- Code/Editor/Objects/ObjectManager.cpp | 90 +++++++++---------- Code/Editor/Objects/SelectionGroup.cpp | 2 +- Code/Editor/Objects/TrackGizmo.cpp | 2 +- .../Platform/Windows/Util/Mailer_Windows.cpp | 8 +- .../SandboxIntegration.cpp | 2 +- .../ComponentPaletteWindow.cpp | 2 +- .../EditorCommon/DockTitleBarWidget.cpp | 16 ++-- Code/Editor/Plugins/FFMPEGPlugin/main.cpp | 2 +- .../PlatformSettings_Android.cpp | 4 +- .../ProjectSettingsTool/Validators.cpp | 2 +- 21 files changed, 145 insertions(+), 145 deletions(-) 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..4faf68181e 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 {} 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 76bd71a1f1..2dc89fdf80 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 350ffa10a9..afe76875ec 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 m_loadedObjects.size(); } diff --git a/Code/Editor/Objects/ObjectManager.cpp b/Code/Editor/Objects/ObjectManager.cpp index 58cd016e22..69e30c46ed 100644 --- a/Code/Editor/Objects/ObjectManager.cpp +++ b/Code/Editor/Objects/ObjectManager.cpp @@ -49,16 +49,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 +69,7 @@ public: return superType->GetFileSpec(); } }; - virtual int GameCreationOrder() { return superType->GameCreationOrder(); }; + int GameCreationOrder() override { return superType->GameCreationOrder(); }; }; void CBaseObjectsCache::AddObject(CBaseObject* object) @@ -86,7 +86,7 @@ void CBaseObjectsCache::AddObject(CBaseObject* object) ////////////////////////////////////////////////////////////////////////// // CObjectManager implementation. ////////////////////////////////////////////////////////////////////////// -CObjectManager* g_pObjectManager = 0; +CObjectManager* g_pObjectManager = nullptr; ////////////////////////////////////////////////////////////////////////// CObjectManager::CObjectManager() @@ -182,19 +182,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 +228,7 @@ CBaseObject* CObjectManager::NewObject(CObjectArchive& ar, CBaseObject* pUndoObj if (!objNode->getAttr("Type", typeName)) { - return 0; + return nullptr; } if (!objNode->getAttr("Id", id)) @@ -268,7 +268,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 +301,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 +355,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 +411,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 +527,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 +603,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 +908,7 @@ void CObjectManager::UnfreezeAll() bool CObjectManager::SelectObject(CBaseObject* obj, bool bUseMask) { assert(obj); - if (obj == NULL) + if (obj == nullptr) { return false; } @@ -974,7 +974,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 +993,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 +1020,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 +1075,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 +1186,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 +1201,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) @@ -1359,7 +1359,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; } @@ -1443,7 +1443,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 +1657,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 +1692,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 +1993,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 +2101,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 +2449,7 @@ void CObjectManager::EndObjectsLoading() { delete m_pLoadProgress; } - m_pLoadProgress = 0; + m_pLoadProgress = nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -2481,20 +2481,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/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 874868b5bc..c78537c77d 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -1815,7 +1815,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/ProjectSettingsTool/PlatformSettings_Android.cpp b/Code/Editor/Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp index d11cc04ba0..fe73253805 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(nullptr, &AndroidSplashscreens::m_landscapeSplashscreens) + ->DataElement(nullptr, &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; From 3ad3dfd6623e23ac3a5fef4559ba79052ee6656f Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Thu, 5 Aug 2021 10:50:29 -0400 Subject: [PATCH 112/251] Address PR feedback Signed-off-by: Yuriy Toporovskyy --- Code/Editor/EditorViewportWidget.cpp | 2 +- Code/Editor/UndoViewRotation.cpp | 5 ++++- Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp | 2 +- .../Code/Source/Editor/AudioControlsEditorPlugin.cpp | 5 ++++- Gems/Camera/Code/Source/CameraSystemComponent.cpp | 9 +++++---- Gems/Camera/Code/Source/CameraSystemComponent.h | 3 ++- 6 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index b205ca5b78..26c96f54b1 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -2513,7 +2513,7 @@ void EditorViewportWidget::SetViewAndMovementLockFromEntityPerspective(const AZ: if (entityId.IsValid()) { - EBUS_EVENT_ID(entityId, Camera::CameraRequestBus, MakeActiveView); + Camera::CameraRequestBus::Event(entityId, &Camera::CameraRequestBus::Events::MakeActiveView); } else { diff --git a/Code/Editor/UndoViewRotation.cpp b/Code/Editor/UndoViewRotation.cpp index c3c6f4253a..a305641d3b 100644 --- a/Code/Editor/UndoViewRotation.cpp +++ b/Code/Editor/UndoViewRotation.cpp @@ -25,7 +25,10 @@ Ang3 CUndoViewRotation::GetActiveCameraRotation() { AZ::Transform activeCameraTm = AZ::Transform::CreateIdentity(); - EBUS_EVENT_RESULT(activeCameraTm, Camera::ActiveCameraRequestBus, GetActiveCameraTransform); + 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)); diff --git a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp index c5b76cbab7..eabfcd8cf0 100644 --- a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp @@ -57,7 +57,7 @@ namespace AZ float GetPerspectiveMatrixFOV(const Matrix4x4& m) { - return 2.0 * atan(1.0f / m.GetElement(1, 1)); + 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) diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp index 2a97bdfb92..2b7023df61 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp @@ -151,7 +151,10 @@ void CAudioControlsEditorPlugin::ExecuteTrigger(const AZStd::string_view sTrigge if (ms_nAudioTriggerID != INVALID_AUDIO_CONTROL_ID) { AZ::Transform activeCameraTm = AZ::Transform::CreateIdentity(); - EBUS_EVENT_RESULT(activeCameraTm, Camera::ActiveCameraRequestBus, GetActiveCameraTransform); + Camera::ActiveCameraRequestBus::BroadcastResult( + activeCameraTm, + &Camera::ActiveCameraRequestBus::Events::GetActiveCameraTransform + ); const AZ::Matrix3x4 cameraMatrix = AZ::Matrix3x4::CreateFromTransform(activeCameraTm); Audio::SAudioRequest request; diff --git a/Gems/Camera/Code/Source/CameraSystemComponent.cpp b/Gems/Camera/Code/Source/CameraSystemComponent.cpp index 7c7dac429d..e9b0132cf8 100644 --- a/Gems/Camera/Code/Source/CameraSystemComponent.cpp +++ b/Gems/Camera/Code/Source/CameraSystemComponent.cpp @@ -1,5 +1,6 @@ /* - * 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. + * 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 * @@ -19,7 +20,7 @@ namespace Camera { void CameraSystemComponent::Reflect(AZ::ReflectContext* context) { - if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() ->Version(1) @@ -36,9 +37,9 @@ namespace Camera void CameraSystemComponent::Deactivate() { - CameraSystemRequestBus::Handler::BusDisconnect(); - ActiveCameraRequestBus::Handler::BusDisconnect(); CameraNotificationBus::Handler::BusDisconnect(); + ActiveCameraRequestBus::Handler::BusDisconnect(); + CameraSystemRequestBus::Handler::BusDisconnect(); } AZ::EntityId CameraSystemComponent::GetActiveCamera() diff --git a/Gems/Camera/Code/Source/CameraSystemComponent.h b/Gems/Camera/Code/Source/CameraSystemComponent.h index 726975ff9d..1b8f31b91e 100644 --- a/Gems/Camera/Code/Source/CameraSystemComponent.h +++ b/Gems/Camera/Code/Source/CameraSystemComponent.h @@ -1,5 +1,6 @@ /* - * 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. + * 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 * From 56dee47c6bf6c4544ed66a6f51a46234cfc64d4a Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Thu, 5 Aug 2021 11:56:09 -0400 Subject: [PATCH 113/251] Address more PR feedback Signed-off-by: Yuriy Toporovskyy --- Code/Editor/AnimationContext.cpp | 1 - Code/Editor/EditorViewportWidget.h | 2 - Code/Editor/Export/ExportManager.cpp | 1 - .../SandboxIntegration.cpp | 1 + Code/Editor/RenderViewport.cpp | 0 Code/Editor/RenderViewport.h | 54 ------------------- Code/Editor/TrackView/TrackViewAnimNode.cpp | 1 - Code/Editor/ViewManager.cpp | 1 - Code/Editor/ViewportTitleDlg.h | 1 - Code/Editor/editor_lib_files.cmake | 2 - .../Code/Source/CameraSystemComponent.h | 2 +- .../ViewportCameraSelectorWindow_Internals.h | 2 +- .../Code/Source/SystemComponent.cpp | 2 +- 13 files changed, 4 insertions(+), 66 deletions(-) delete mode 100644 Code/Editor/RenderViewport.cpp delete mode 100644 Code/Editor/RenderViewport.h diff --git a/Code/Editor/AnimationContext.cpp b/Code/Editor/AnimationContext.cpp index b67e9e602e..d557a8635c 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" diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index dabbbe95f6..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 diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index 0d114d5da8..54f3c2f723 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" diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 874868b5bc..29db338a85 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 diff --git a/Code/Editor/RenderViewport.cpp b/Code/Editor/RenderViewport.cpp deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Code/Editor/RenderViewport.h b/Code/Editor/RenderViewport.h deleted file mode 100644 index 8f5e19f93d..0000000000 --- a/Code/Editor/RenderViewport.h +++ /dev/null @@ -1,54 +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; -} - -#endif diff --git a/Code/Editor/TrackView/TrackViewAnimNode.cpp b/Code/Editor/TrackView/TrackViewAnimNode.cpp index 8696faf516..9d0892888f 100644 --- a/Code/Editor/TrackView/TrackViewAnimNode.cpp +++ b/Code/Editor/TrackView/TrackViewAnimNode.cpp @@ -34,7 +34,6 @@ #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/ViewManager.cpp b/Code/Editor/ViewManager.cpp index 2ccbac09ed..7277a0f4f3 100644 --- a/Code/Editor/ViewManager.cpp +++ b/Code/Editor/ViewManager.cpp @@ -26,7 +26,6 @@ #include "LayoutWnd.h" #include "2DViewport.h" #include "TopRendererWnd.h" -#include "RenderViewport.h" #include "EditorViewportWidget.h" #include "CryEditDoc.h" 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..a007a95e7b 100644 --- a/Code/Editor/editor_lib_files.cmake +++ b/Code/Editor/editor_lib_files.cmake @@ -807,8 +807,6 @@ set(FILES ViewportManipulatorController.h LegacyViewportCameraController.cpp LegacyViewportCameraController.h - RenderViewport.cpp - RenderViewport.h TopRendererWnd.cpp TopRendererWnd.h ViewManager.cpp diff --git a/Gems/Camera/Code/Source/CameraSystemComponent.h b/Gems/Camera/Code/Source/CameraSystemComponent.h index 1b8f31b91e..7fc8d15d6b 100644 --- a/Gems/Camera/Code/Source/CameraSystemComponent.h +++ b/Gems/Camera/Code/Source/CameraSystemComponent.h @@ -58,4 +58,4 @@ namespace Camera AZ::EntityId m_activeView; CameraProperties m_activeViewProperties; }; -} +} // namespace Camera diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h index e75a820eec..2c3d114908 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h @@ -42,7 +42,7 @@ namespace Camera , public CameraNotificationBus::Handler { public: - CameraListModel(QWidget* myParent); + explicit CameraListModel(QWidget* myParent); ~CameraListModel(); // QAbstractItemModel interface diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 97cb4f33d3..16cbdaaf64 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -470,7 +470,7 @@ namespace PhysXDebug AZ::Vector3 GetViewCameraPosition() { - using namespace Camera; + using Camera::ActiveCameraRequestBus; AZ::Transform tm = AZ::Transform::CreateIdentity(); ActiveCameraRequestBus::BroadcastResult(tm, &ActiveCameraRequestBus::Events::GetActiveCameraTransform); From 574bef0cd8daabdae79d933b1011153a6853f83b Mon Sep 17 00:00:00 2001 From: evanchia Date: Thu, 5 Aug 2021 10:19:15 -0700 Subject: [PATCH 114/251] Escape character in Jenkins for test metrics Signed-off-by: evanchia --- scripts/build/Jenkins/Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 9aa09e136e..517fa1136d 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 } From bf7512ebf4b9045b8892779bcc89d6773be5774b Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 14:07:48 -0500 Subject: [PATCH 115/251] Merge fix Signed-off-by: Dayo Lawal --- .../Application/AtomToolsApplication.cpp | 16 ++++-- .../Code/Source/MaterialEditorApplication.cpp | 15 +---- .../Code/Source/MaterialEditorApplication.h | 1 - .../Scripts/GenerateAllMaterialScreenshots.py | 4 +- .../ShaderManagementConsoleApplication.cpp | 57 +++++++------------ .../ShaderManagementConsoleApplication.h | 3 +- 6 files changed, 37 insertions(+), 59 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index 4094e7a3a0..25ef43cfa4 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -70,6 +71,8 @@ namespace AtomToolsFramework AtomToolsApplication ::~AtomToolsApplication() { AtomToolsMainWindowNotificationBus::Handler::BusDisconnect(); + AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); + AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); } void AtomToolsApplication::CreateReflectionManager() @@ -93,14 +96,12 @@ namespace AtomToolsFramework if (auto behaviorContext = azrtti_cast(context)) { - auto targetName = GetBuildTargetName(); - // this will put these methods into the 'azlmbr.AtomTools.general' module - auto addGeneral = [targetName](AZ::BehaviorContext::GlobalMethodBuilder methodBuilder) + auto addGeneral = [](AZ::BehaviorContext::GlobalMethodBuilder methodBuilder) { methodBuilder->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, targetName); + ->Attribute(AZ::Script::Attributes::Module, "atomtools.general"); }; // The reflection here is based on patterns in CryEditPythonHandler::Reflect addGeneral(behaviorContext->Method( @@ -288,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)) { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 53409d717f..0dd8da5415 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -17,7 +17,6 @@ #include #include -#include #include #include @@ -76,16 +75,11 @@ namespace MaterialEditor { QApplication::setApplicationName("O3DE Material Editor"); + // The settings registry has been created at this point, so add the CMake target AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization( *AZ::SettingsRegistry::Get(), GetBuildTargetName()); } - MaterialEditorApplication::~MaterialEditorApplication() - { - AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); - AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); - } - void MaterialEditorApplication::CreateStaticModules(AZStd::vector& outModules) { Base::CreateStaticModules(outModules); @@ -101,13 +95,6 @@ namespace MaterialEditor void MaterialEditorApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { - const AZStd::string activateWindowSwitchName = "activatewindow"; - if (commandLine.HasSwitch(activateWindowSwitchName)) - { - AtomToolsFramework::AtomToolsMainWindowRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsMainWindowRequestBus::Handler::ActivateWindow); - } - // 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) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h index 2fbab79e41..6209a01116 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -26,7 +26,6 @@ namespace MaterialEditor using Base = AtomToolsFramework::AtomToolsApplication; MaterialEditorApplication(int* argc, char*** argv); - virtual ~MaterialEditorApplication(); ////////////////////////////////////////////////////////////////////////// // AzFramework::Application diff --git a/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py b/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py index d2c9bf209e..d7f52d7a24 100755 --- a/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py +++ b/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py @@ -114,11 +114,11 @@ def SetCameraPitch(pitch): azlmbr.render.ArcBallControllerRequestBus(azlmbr.bus.Broadcast, 'SetPitch', pitch) def IdleFrames(numFrames): - azlmbr.materialeditor.general.idle_wait_frames(numFrames) + azlmbr.atomtools.general.idle_wait_frames(numFrames) def CaptureScreenshot(screenshotOutputPath): print("Capturing screenshot to " + screenshotOutputPath + " ...") - return ScreenshotHelper(azlmbr.materialeditor.general.idle_wait_frames).capture_screenshot_blocking(screenshotOutputPath) + return ScreenshotHelper(azlmbr.atomtools.general.idle_wait_frames).capture_screenshot_blocking(screenshotOutputPath) def ResizeViewport(width, height): # This locks the size of the render target to the desired resolution diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp index e3b3c6e5aa..38319e7ce4 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -6,6 +6,18 @@ * */ +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + #include #include #include @@ -23,30 +35,17 @@ #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 AZ_POP_DISABLE_WARNING namespace ShaderManagementConsole { + //! This function returns the build system target name of "ShaderManagementConsole" AZStd::string ShaderManagementConsoleApplication::GetBuildTargetName() const { #if !defined (LY_CMAKE_TARGET) @@ -76,12 +75,6 @@ namespace ShaderManagementConsole *AZ::SettingsRegistry::Get(), GetBuildTargetName()); } - ShaderManagementConsoleApplication::~ShaderManagementConsoleApplication() - { - AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); - AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); - } - void ShaderManagementConsoleApplication::CreateStaticModules(AZStd::vector& outModules) { Base::CreateStaticModules(outModules); @@ -94,27 +87,19 @@ namespace ShaderManagementConsole return AZStd::vector({ "passes/", "config/" }); } - void ShaderManagementConsoleApplication::ProcessCommandLine() + void ShaderManagementConsoleApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { - // Process command line options for running one or more python scripts on startup - const AZStd::string runPythonScriptSwitchName = "runpython"; - size_t runPythonScriptCount = m_commandLine.GetNumSwitchValues(runPythonScriptSwitchName); - for (size_t runPythonScriptIndex = 0; runPythonScriptIndex < runPythonScriptCount; ++runPythonScriptIndex) - { - const AZStd::string runPythonScriptPath = m_commandLine.GetSwitchValue(runPythonScriptSwitchName, runPythonScriptIndex); - AZStd::vector runPythonArgs; - AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast( - &AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByFilenameWithArgs, - runPythonScriptPath, - runPythonArgs); - } - // Process command line options for opening one or more documents on startup size_t openDocumentCount = m_commandLine.GetNumMiscValues(); for (size_t openDocumentIndex = 0; openDocumentIndex < openDocumentCount; ++openDocumentIndex) { - const AZStd::string openDocumentPath = m_commandLine.GetMiscValue(openDocumentIndex); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); + const AZStd::string openDocumentPath = commandLine.GetMiscValue(openDocumentIndex); + + AZ_Printf(GetBuildTargetName().c_str(), "Opening document: %s", openDocumentPath.c_str()); + ShaderManagementConsoleDocumentSystemRequestBus::Broadcast( + &ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); } + + Base::ProcessCommandLine(commandLine); } } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index 4fad40400c..4e3f92c0e5 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -24,7 +24,6 @@ namespace ShaderManagementConsole using Base = AtomToolsFramework::AtomToolsApplication; ShaderManagementConsoleApplication(int* argc, char*** argv); - virtual ~ShaderManagementConsoleApplication(); ////////////////////////////////////////////////////////////////////////// // AzFramework::Application @@ -32,7 +31,7 @@ namespace ShaderManagementConsole const char* GetCurrentConfigurationName() const override; private: - void ProcessCommandLine(); + void ProcessCommandLine(const AZ::CommandLine& commandLine); AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; }; From 9a82005cb8e3d516b43064651b056df6e57128e2 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 12:42:33 -0700 Subject: [PATCH 116/251] PR comments/fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../AzCore/AzCore/std/string/conversions.h | 26 ++++++++++++------- .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp | 2 +- .../Linux/AzCore/Debug/Trace_Linux.cpp | 2 +- Code/Framework/AzCore/Tests/AZStd/String.cpp | 2 +- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index 91af1029b4..235eb188d1 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -58,15 +58,15 @@ namespace AZStd } } - static inline void to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last) + static inline char* to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last) { if constexpr (Size == 2) { - Utf8::Unchecked::utf16to8(first, last, dest, destSize); + return Utf8::Unchecked::utf16to8(first, last, dest, destSize); } else if constexpr (Size == 4) { - Utf8::Unchecked::utf32to8(first, last, dest, destSize); + return Utf8::Unchecked::utf32to8(first, last, dest, destSize); } } @@ -96,15 +96,15 @@ namespace AZStd } } - static inline void to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last) + static inline wchar_t* to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last) { if constexpr (Size == 2) { - Utf8::Unchecked::utf8to16(first, last, dest, destSize); + return Utf8::Unchecked::utf8to16(first, last, dest, destSize); } else if constexpr (Size == 4) { - Utf8::Unchecked::utf8to32(first, last, dest, destSize); + return Utf8::Unchecked::utf8to32(first, last, dest, destSize); } } }; @@ -337,7 +337,11 @@ namespace AZStd if (srcLen > 0) { - Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen + 1); // copy null terminator + char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen); + if (*(endStr - 1) != '\0') + { + *endStr = '\0'; // copy null terminator + } } } @@ -485,12 +489,16 @@ namespace AZStd { if (srcLen == 0) { - srcLen = strlen(str) + 1; + srcLen = strlen(str); } if (srcLen > 0) { - Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen + 1); // copy null terminator + wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen); + if (*(endWStr - 1) != '\0') + { + *endWStr = '\0'; // copy null terminator + } } } diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp index a4af19a2a4..dc104668be 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp @@ -30,7 +30,7 @@ namespace AZ result.m_pathIncludesFilename = true; // Platform specific get exe path: http://stackoverflow.com/a/1024937 // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea - wchar_t pathBufferW[AZ_MAX_PATH_LEN] = { 0 }; + wchar_t pathBufferW[AZ::IO::MaxPathLength] = { 0 }; const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(exeStorageSize)); const DWORD errorCode = GetLastError(); if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER) diff --git a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp index 86c7e14ae6..1ca06fcf7f 100644 --- a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp +++ b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp @@ -15,7 +15,7 @@ namespace AZ { namespace Platform { - void OutputToDebugger(const char* title, const char* message) + void OutputToDebugger([[maybe_unused]] const char* title, [[maybe_unused]] const char* message) { // std::cout << title << ": " << message; } diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index c0d378bd39..309f561a75 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -703,7 +703,7 @@ namespace UnitTest AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BlaBla 5")); // char buffer to wchar_t buffer - memset(wstrBuffer, 0, AZ_ARRAY_SIZE(wstrBuffer)); + memset(wstrBuffer, L' ', AZ_ARRAY_SIZE(wstrBuffer)); // to check that the null terminator is properly placed to_wstring(wstrBuffer, 9, strBuffer); AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BLABLA 5")); From d955189a31a5f8eb6ddc4529c3d28421aba6a558 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 12:43:46 -0700 Subject: [PATCH 117/251] Removal of unused files from Code/Editor XmlHistoryManager.cpp was being compiled but unused Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Animation/SkeletonHierarchy.cpp | 149 --- Code/Editor/Animation/SkeletonHierarchy.h | 57 -- Code/Editor/Animation/SkeletonMapper.cpp | 368 -------- Code/Editor/Animation/SkeletonMapper.h | 76 -- .../Animation/SkeletonMapperOperator.cpp | 284 ------ .../Editor/Animation/SkeletonMapperOperator.h | 164 ---- Code/Editor/ControlMRU.cpp | 135 --- Code/Editor/ControlMRU.h | 24 - Code/Editor/Controls/ConsoleSCBMFC.cpp | 543 ----------- Code/Editor/Util/IXmlHistoryManager.h | 73 -- Code/Editor/Util/StringNoCasePredicate.h | 62 -- Code/Editor/Util/XmlHistoryManager.cpp | 875 ------------------ Code/Editor/Util/XmlHistoryManager.h | 218 ----- Code/Editor/editor_lib_files.cmake | 4 - 14 files changed, 3032 deletions(-) delete mode 100644 Code/Editor/Animation/SkeletonHierarchy.cpp delete mode 100644 Code/Editor/Animation/SkeletonHierarchy.h delete mode 100644 Code/Editor/Animation/SkeletonMapper.cpp delete mode 100644 Code/Editor/Animation/SkeletonMapper.h delete mode 100644 Code/Editor/Animation/SkeletonMapperOperator.cpp delete mode 100644 Code/Editor/Animation/SkeletonMapperOperator.h delete mode 100644 Code/Editor/ControlMRU.cpp delete mode 100644 Code/Editor/ControlMRU.h delete mode 100644 Code/Editor/Controls/ConsoleSCBMFC.cpp delete mode 100644 Code/Editor/Util/IXmlHistoryManager.h delete mode 100644 Code/Editor/Util/StringNoCasePredicate.h delete mode 100644 Code/Editor/Util/XmlHistoryManager.cpp delete mode 100644 Code/Editor/Util/XmlHistoryManager.h diff --git a/Code/Editor/Animation/SkeletonHierarchy.cpp b/Code/Editor/Animation/SkeletonHierarchy.cpp deleted file mode 100644 index 3015ff5e27..0000000000 --- a/Code/Editor/Animation/SkeletonHierarchy.cpp +++ /dev/null @@ -1,149 +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 "EditorDefs.h" -#include "SkeletonHierarchy.h" - -using namespace Skeleton; - -/* - - CHierarchy - -*/ - -CHierarchy::CHierarchy() -{ -} - -CHierarchy::~CHierarchy() -{ -} - -// - -uint32 CHierarchy::AddNode(const char* name, const QuatT& pose, int32 parent) -{ - int32 index = FindNodeIndexByName(name); - - if (index < 0) - { - m_nodes.push_back(SNode()); - index = int32(m_nodes.size() - 1); - } - - m_nodes[index].name = name; - m_nodes[index].pose = pose; - m_nodes[index].parent = parent; - return uint32(index); -} - -int32 CHierarchy::FindNodeIndexByName(const char* name) const -{ - uint32 count = uint32(m_nodes.size()); - for (uint32 i = 0; i < count; ++i) - { - if (::_stricmp(m_nodes[i].name, name)) - { - continue; - } - - return i; - } - - return -1; -} - -const CHierarchy::SNode* CHierarchy::FindNode(const char* name) const -{ - int32 index = FindNodeIndexByName(name); - return index < 0 ? NULL : &m_nodes[index]; -} - -void CHierarchy::CreateFrom(IDefaultSkeleton* pIDefaultSkeleton) -{ - const uint32 jointCount = pIDefaultSkeleton->GetJointCount(); - - m_nodes.clear(); - m_nodes.reserve(jointCount); - for (uint32 i = 0; i < jointCount; ++i) - { - m_nodes.push_back(SNode()); - - m_nodes.back().name = pIDefaultSkeleton->GetJointNameByID(int32(i)); - m_nodes.back().pose = pIDefaultSkeleton->GetDefaultAbsJointByID(int32(i)); - - m_nodes.back().parent = pIDefaultSkeleton->GetJointParentIDByID(int32(i)); - } - - ValidateReferences(); -} - -void CHierarchy::ValidateReferences() -{ - uint32 nodeCount = m_nodes.size(); - if (!nodeCount) - { - return; - } - - for (uint32 i = 0; i < nodeCount; ++i) - { - if (m_nodes[i].parent < nodeCount) - { - continue; - } - - m_nodes[i].parent = -1; - } -} - -void CHierarchy::AbsoluteToRelative(const QuatT* pSource, QuatT* pDestination) -{ - uint32 count = uint32(m_nodes.size()); - std::vector absolutes(count); - for (uint32 i = 0; i < count; ++i) - { - absolutes[i] = pSource[i]; - } - - for (uint32 i = 0; i < count; ++i) - { - int32 parent = m_nodes[i].parent; - if (parent < 0) - { - pDestination[i] = absolutes[i]; - continue; - } - - pDestination[i].t = (absolutes[i].t - absolutes[parent].t) * absolutes[parent].q; - pDestination[i].q = absolutes[parent].q.GetInverted() * absolutes[i].q; - } -} - -bool CHierarchy::SerializeTo(XmlNodeRef& node) -{ - XmlNodeRef hierarchy = node->newChild("Hierarchy"); - - uint32 nodeCount = uint32(m_nodes.size()); - std::vector nodes(nodeCount); - for (uint32 i = 0; i < nodeCount; ++i) - { - XmlNodeRef parent = hierarchy; - if (m_nodes[i].parent > -1) - { - parent = nodes[m_nodes[i].parent]; - } - - nodes[i] = parent->newChild("Node"); - nodes[i]->setAttr("name", m_nodes[i].name); - } - - return true; -} diff --git a/Code/Editor/Animation/SkeletonHierarchy.h b/Code/Editor/Animation/SkeletonHierarchy.h deleted file mode 100644 index ad0d8fc7fc..0000000000 --- a/Code/Editor/Animation/SkeletonHierarchy.h +++ /dev/null @@ -1,57 +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_ANIMATION_SKELETONHIERARCHY_H -#define CRYINCLUDE_EDITOR_ANIMATION_SKELETONHIERARCHY_H -#pragma once - -namespace Skeleton { - class CHierarchy - : public _reference_target_t - { - public: - struct SNode - { - string name; - QuatT pose; - - int32 parent; - - /* TODO: Implement - uint32 childrenIndex; - uint32 childrenCount; - */ - }; - - public: - CHierarchy(); - ~CHierarchy(); - - public: - uint32 AddNode(const char* name, const QuatT& pose, int32 parent = -1); - uint32 GetNodeCount() const { return uint32(m_nodes.size()); } - SNode* GetNode(uint32 index) { return &m_nodes[index]; } - const SNode* GetNode(uint32 index) const { return &m_nodes[index]; } - int32 FindNodeIndexByName(const char* name) const; - const SNode* FindNode(const char* name) const; - void ClearNodes() { m_nodes.clear(); } - - void CreateFrom(IDefaultSkeleton* rIDefaultSkeleton); - void ValidateReferences(); - - void AbsoluteToRelative(const QuatT* pSource, QuatT* pDestination); - - bool SerializeTo(XmlNodeRef& node); - - private: - std::vector m_nodes; - }; -} // namespace Skeleton - -#endif // CRYINCLUDE_EDITOR_ANIMATION_SKELETONHIERARCHY_H diff --git a/Code/Editor/Animation/SkeletonMapper.cpp b/Code/Editor/Animation/SkeletonMapper.cpp deleted file mode 100644 index 3913801fc8..0000000000 --- a/Code/Editor/Animation/SkeletonMapper.cpp +++ /dev/null @@ -1,368 +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 "EditorDefs.h" - -#include "SkeletonMapper.h" - -using namespace Skeleton; - -/* - - CMapper - -*/ - -CMapper::CMapper() -{ -} - -CMapper::~CMapper() -{ -} - -// - -void CMapper::CreateFromHierarchy() -{ - m_nodes.clear(); - - uint32 nodeCount = m_hierarchy.GetNodeCount(); - m_nodes.resize(nodeCount); -} - -// - -uint32 CMapper::CreateLocation(const char* name) -{ - int32 index = FindLocation(name); - if (index < 1) - { - CMapperLocation* pLocation = new CMapperLocation(); - pLocation->SetName(name); - m_locations.push_back(pLocation); - } - return uint32(m_locations.size() - 1); -} - -void CMapper::ClearLocations() -{ - uint32 count = uint32(m_nodes.size()); - for (uint32 i = 0; i < count; ++i) - { - m_nodes[i].position = NULL; - m_nodes[i].orientation = NULL; - } - - m_locations.clear(); -} - -int32 CMapper::FindLocation(const char* name) const -{ - uint32 count = uint32(m_locations.size()); - for (uint32 i = 0; i < count; ++i) - { - if (::_stricmp(m_locations[i]->GetName(), name)) - { - continue; - } - - return int32(i); - } - - return -1; -} - -void CMapper::SetLocation(CMapperLocation& location) -{ - int32 index = FindLocation(location.GetName()); - if (index < 0) - { - m_locations.push_back(&location); - return; - } - - m_locations[index] = &location; -} - -// - -bool CMapper::CreateLocationsHierarchy(uint32 index, CHierarchy& hierarchy, int32 hierarchyParent) -{ - if (NodeHasLocation(index)) - { - const CHierarchy::SNode* pNode = m_hierarchy.GetNode(index); - uint32 nodeIndex = hierarchy.AddNode(pNode->name, pNode->pose, hierarchyParent); - hierarchyParent = uint32(nodeIndex); - } - - std::vector children; - GetChildrenIndices(index, children); - uint32 childCount = uint32(children.size()); - for (uint32 i = 0; i < childCount; ++i) - { - CreateLocationsHierarchy(children[i], hierarchy, hierarchyParent); - } - - return hierarchy.GetNodeCount() != 0; -} - -bool CMapper::CreateLocationsHierarchy(CHierarchy& hierarchy) -{ - hierarchy.ClearNodes(); - if (!CreateLocationsHierarchy(0, hierarchy, -1)) - { - return false; - } - - hierarchy.ValidateReferences(); - return true; -} - -void CMapper::Map(QuatT* pResult) -{ - uint32 outputCount = m_hierarchy.GetNodeCount(); - std::vector absolutes(outputCount); - for (uint32 i = 0; i < outputCount; ++i) - { - pResult[i].SetIdentity(); - absolutes[i].SetIdentity(); - - CHierarchy::SNode* pNode = m_hierarchy.GetNode(i); - if (!pNode) - { - continue; - } - - CHierarchy::SNode* pParent = pNode->parent < 0 ? - NULL : m_hierarchy.GetNode(pNode->parent); - if (pParent) - { - pResult[i].t = - (pNode->pose.t - pParent->pose.t) * pParent->pose.q; - } - - if (m_nodes[i].position) - { - pResult[i].t = m_nodes[i].position->Compute().t; - } - - if (m_nodes[i].orientation) - { - absolutes[i] = m_nodes[i].orientation->Compute().q; - } - else if (pParent) - { - Quat relative = pParent->pose.q.GetInverted() * pNode->pose.q; - absolutes[i] = absolutes[pNode->parent] * relative; - } - } - - for (uint32 i = 0; i < outputCount; ++i) - { - CHierarchy::SNode* pNode = m_hierarchy.GetNode(i); - if (!pNode) - { - continue; - } - - CHierarchy::SNode* pParent = pNode->parent < 0 ? - NULL : m_hierarchy.GetNode(pNode->parent); - if (!pParent) - { - pResult[i].q = absolutes[i]; - continue; - } - - pResult[i].q = absolutes[i]; - if (!m_nodes[i].position) - { - pResult[i].t = pResult[pNode->parent].t + - pResult[i].t * absolutes[pNode->parent].GetInverted(); - } - } -} - -// - -bool CMapper::NodeHasLocation(uint32 index) -{ - if (CMapperOperator* pOperator = m_nodes[index].position) - { - if (pOperator->IsOfClass("Location")) - { - return true; - } - if (pOperator->HasLinksOfClass("Location")) - { - return true; - } - } - - if (CMapperOperator* pOperator = m_nodes[index].orientation) - { - if (pOperator->IsOfClass("Location")) - { - return true; - } - if (pOperator->HasLinksOfClass("Location")) - { - return true; - } - } - - return false; -} - -void CMapper::GetChildrenIndices(uint32 parent, std::vector& children) -{ - uint32 nodeCount = m_hierarchy.GetNodeCount(); - for (uint32 i = 0; i < nodeCount; ++i) - { - if (m_hierarchy.GetNode(i)->parent != parent) - { - continue; - } - - children.push_back(i); - } -} - -bool CMapper::ChildrenHaveLocation(uint32 index) -{ - std::vector children; - GetChildrenIndices(index, children); - - uint32 childrenCount = uint32(children.size()); - for (uint32 i = 0; i < childrenCount; ++i) - { - if (ChildrenHaveLocation(children[i])) - { - return true; - } - } - - return false; -} - -bool CMapper::NodeOrChildrenHaveLocation(uint32 index) -{ - if (NodeHasLocation(index)) - { - return true; - } - - std::vector children; - GetChildrenIndices(index, children); - - uint32 childrenCount = uint32(children.size()); - for (uint32 i = 0; i < childrenCount; ++i) - { - if (NodeOrChildrenHaveLocation(children[i])) - { - return true; - } - } - - return false; -} - -bool CMapper::SerializeTo(XmlNodeRef& node) -{ - XmlNodeRef hierarchy = node->newChild("Hierarchy"); - - uint32 nodeCount = GetNodeCount(); - std::vector nodes(nodeCount); - for (uint32 i = 0; i < nodeCount; ++i) - { - if (!NodeOrChildrenHaveLocation(i)) - { - continue; - } - - CHierarchy::SNode* pNode = m_hierarchy.GetNode(i); - if (!pNode) - { - return false; - } - - XmlNodeRef xmlParent = hierarchy; - int32 parent = pNode->parent; - if (parent > -1) - { - xmlParent = nodes[parent]; - } - - nodes[i] = xmlParent->newChild("Node"); - nodes[i]->setAttr("name", pNode->name); - - if (CMapperOperator* pOperator = m_nodes[i].position) - { - XmlNodeRef position = nodes[i]->newChild("Position"); - XmlNodeRef child = position->newChild("Operator"); - if (!pOperator->SerializeWithLinksTo(child)) - { - return false; - } - } - - if (CMapperOperator* pOperator = m_nodes[i].orientation) - { - XmlNodeRef orientation = nodes[i]->newChild("Orientation"); - XmlNodeRef child = orientation->newChild("Operator"); - if (!pOperator->SerializeWithLinksTo(child)) - { - return false; - } - } - } - - return true; -} - -bool CMapper::SerializeFrom(XmlNodeRef& node, int32 parent) -{ - int childCount = uint32(node->getChildCount()); - for (int i = 0; i < childCount; ++i) - { - XmlNodeRef child = node->getChild(i); - if (::_stricmp(child->getTag(), "Node")) - { - continue; - } - - uint32 index = m_hierarchy.AddNode(child->getAttr("name"), QuatT(IDENTITY), parent); - if (!SerializeFrom(child, int32(index))) - { - return false; - } - } - - return true; -} - -bool CMapper::SerializeFrom(XmlNodeRef& node) -{ - XmlNodeRef hierarchy = node->findChild("Hierarchy"); - if (!hierarchy) - { - return false; - } - - m_hierarchy.ClearNodes(); - - if (!SerializeFrom(hierarchy, -1)) - { - return false; - } - - m_nodes.resize(m_hierarchy.GetNodeCount()); - - return true; -} diff --git a/Code/Editor/Animation/SkeletonMapper.h b/Code/Editor/Animation/SkeletonMapper.h deleted file mode 100644 index 159b019396..0000000000 --- a/Code/Editor/Animation/SkeletonMapper.h +++ /dev/null @@ -1,76 +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_ANIMATION_SKELETONMAPPER_H -#define CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPER_H -#pragma once - - -#include "SkeletonHierarchy.h" -#include "SkeletonMapperOperator.h" - -namespace Skeleton { - class CMapper - { - public: - struct SNode - { - _smart_ptr position; - _smart_ptr orientation; - }; - - public: - CMapper(); - ~CMapper(); - - public: - CHierarchy& GetHierarchy() { return m_hierarchy; } - void CreateFromHierarchy(); - - uint32 GetNodeCount() const { return uint32(m_nodes.size()); } - SNode* GetNode(uint32 index) { return &m_nodes[index]; } - const SNode* GetNode(uint32 index) const { return &m_nodes[index]; } - - uint32 CreateLocation(const char* name); - void ClearLocations(); - int32 FindLocation(const char* name) const; - - uint32 GetLocationCount() const { return uint32(m_locations.size()); } - void SetLocation(CMapperLocation& location); - CMapperLocation* GetLocation(uint32 index) { return m_locations[index]; } - const CMapperLocation* GetLocation(uint32 index) const { return m_locations[index]; } - - bool CreateLocationsHierarchy(CHierarchy& hierarchy); - - void Map(QuatT* pResult); - - bool SerializeTo(XmlNodeRef& node); - bool SerializeFrom(XmlNodeRef& node); - - private: - bool NodeHasLocation(uint32 index); - bool ChildrenHaveLocation(uint32 index); - bool NodeOrChildrenHaveLocation(uint32 index); - - bool SerializeFrom(XmlNodeRef& node, int32 parent); - - bool CreateLocationsHierarchy(uint32 index, CHierarchy& hierarchy, int32 hierarchyParent = -1); - - // TEMP - void GetChildrenIndices(uint32 parent, std::vector& children); - - private: - CHierarchy m_hierarchy; - std::vector<_smart_ptr > m_locations; - - std::vector m_nodes; - }; -} // namespace Skeleton - -#endif // CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPER_H diff --git a/Code/Editor/Animation/SkeletonMapperOperator.cpp b/Code/Editor/Animation/SkeletonMapperOperator.cpp deleted file mode 100644 index 7a69173bed..0000000000 --- a/Code/Editor/Animation/SkeletonMapperOperator.cpp +++ /dev/null @@ -1,284 +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 "EditorDefs.h" - -#include "SkeletonMapperOperator.h" - -using namespace Skeleton; - -/* - - CMapperOperatorDesc - -*/ - -std::vector CMapperOperatorDesc::s_descs; - -// - -CMapperOperatorDesc::CMapperOperatorDesc(const char* name) -{ - s_descs.push_back(this); -} - -/* - - CMapperOperator - -*/ - -CMapperOperator::CMapperOperator(const char* className, uint32 positionCount, uint32 orientationCount) -{ - m_className = className; - m_position.resize(positionCount, NULL); - m_orientation.resize(orientationCount, NULL); -} - -CMapperOperator::~CMapperOperator() -{ -} - -// - -bool CMapperOperator::IsOfClass(const char* className) -{ - if (::_stricmp(m_className, className)) - { - return false; - } - - return true; -} - -uint32 CMapperOperator::HasLinksOfClass(const char* className) -{ - uint32 count = 0; - - uint32 positionCount = m_position.size(); - for (uint32 i = 0; i < positionCount; ++i) - { - CMapperOperator* pOperator = m_position[i]; - if (!pOperator) - { - continue; - } - - if (pOperator->IsOfClass(className)) - { - ++count; - } - } - - uint32 orientationCount = m_orientation.size(); - for (uint32 i = 0; i < orientationCount; ++i) - { - CMapperOperator* pOperator = m_orientation[i]; - if (!pOperator) - { - continue; - } - - if (pOperator->IsOfClass(className)) - { - ++count; - } - } - - return count; -} - -// - -bool CMapperOperator::SerializeTo(XmlNodeRef& node) -{ - node->setAttr("class", m_className); - - uint32 parameterCount = uint32(m_parameters.size()); - for (uint32 i = 0; i < parameterCount; ++i) - { - m_parameters[i]->Serialize(node, false); - } - - return true; -} - -bool CMapperOperator::SerializeFrom(XmlNodeRef& node) -{ - uint32 parameterCount = uint32(m_parameters.size()); - for (uint32 i = 0; i < parameterCount; ++i) - { - m_parameters[i]->Serialize(node, true); - } - - return true; -} - -bool CMapperOperator::SerializeWithLinksTo(XmlNodeRef& node) -{ - if (!SerializeTo(node)) - { - return false; - } - - uint32 positionCount = uint32(m_position.size()); - for (uint32 i = 0; i < positionCount; ++i) - { - CMapperOperator* pOperator = m_position[i]; - if (!pOperator) - { - continue; - } - - XmlNodeRef position = node->newChild("Position"); - position->setAttr("index", i); - - XmlNodeRef child = position->newChild("Operator"); - if (!pOperator->SerializeWithLinksTo(child)) - { - return false; - } - } - - uint32 orientationCount = uint32(m_orientation.size()); - for (uint32 i = 0; i < orientationCount; ++i) - { - CMapperOperator* pOperator = m_orientation[i]; - if (!pOperator) - { - continue; - } - - XmlNodeRef orientation = node->newChild("Orientation"); - orientation->setAttr("index", i); - - XmlNodeRef child = orientation->newChild("Operator"); - if (!pOperator->SerializeWithLinksTo(child)) - { - return false; - } - } - - return true; -} - -bool CMapperOperator::SerializeWithLinksFrom(XmlNodeRef& node) -{ - if (!SerializeFrom(node)) - { - return false; - } - - return true; -} -/* - - CMapperOperator_Transform - -*/ - -class CMapperOperator_Transform - : public CMapperOperator -{ -public: - CMapperOperator_Transform() - : CMapperOperator("Transform", 1, 1) - { - m_pAngles = new CVariable(); - m_pAngles->SetName("rotation"); - m_pAngles->Set(Vec3(0.0f, 0.0f, 0.0f)); - m_pAngles->SetLimits(-180.0f, 180.0f); - AddParameter(*m_pAngles); - - m_pVector = new CVariable(); - m_pVector->SetName("vector"); - m_pVector->Set(Vec3(0.0f, 0.0f, 0.0f)); - AddParameter(*m_pVector); - - m_pScale = new CVariable(); - m_pScale->SetName("scale"); - m_pScale->Set(Vec3(1.0f, 1.0f, 1.0f)); - AddParameter(*m_pScale); - } - - // CMapperOperator -public: - virtual QuatT CMapperOperator_Transform::Compute() - { - QuatT result(IDENTITY); - m_pVector->Get(result.t); - - Vec3 scale; - m_pScale->Get(scale); - - Vec3 angles; - m_pAngles->Get(angles); - - result.q = Quat::CreateRotationXYZ( - Ang3(DEG2RAD(angles.x), DEG2RAD(angles.y), DEG2RAD(angles.z))); - - if (CMapperOperator* pOperator = GetPosition(0)) - { - result.t = pOperator->Compute().t.CompMul(scale) + result.t; - } - if (CMapperOperator* pOperator = GetOrientation(0)) - { - result.q = pOperator->Compute().q * result.q; - } - return result; - } - -private: - CVariable* m_pVector; - CVariable* m_pAngles; - CVariable* m_pScale; -}; - -SkeletonMapperOperatorRegister(Transform, CMapperOperator_Transform) - -class CMapperOperator_PositionsToOrientation - : public CMapperOperator -{ -public: - CMapperOperator_PositionsToOrientation() - : CMapperOperator("PositionsToOrientation", 3, 0) - { - } - - // CMapperOperator -public: - virtual QuatT Compute() - { - CMapperOperator* pOperator0 = GetPosition(0); - CMapperOperator* pOperator1 = GetPosition(1); - CMapperOperator* pOperator2 = GetPosition(2); - if (!pOperator0 || !pOperator1 || !pOperator2) - { - return QuatT(IDENTITY); - } - - Vec3 p0 = pOperator0->Compute().t; - Vec3 p1 = pOperator1->Compute().t; - Vec3 p2 = pOperator2->Compute().t; - - Vec3 m = (p1 + p2) * 0.5f; - Vec3 y = (m - p0).GetNormalized(); - Vec3 z = (p1 - p2).GetNormalized(); - Vec3 x = y % z; - z = x % y; - - Matrix33 m33; - m33.SetFromVectors(x, y, z); - QuatT result(IDENTITY); - result.q = Quat(m33); - return result; - } -}; - -SkeletonMapperOperatorRegister(PositionsToOrientation, CMapperOperator_PositionsToOrientation) diff --git a/Code/Editor/Animation/SkeletonMapperOperator.h b/Code/Editor/Animation/SkeletonMapperOperator.h deleted file mode 100644 index 68bbb84ac7..0000000000 --- a/Code/Editor/Animation/SkeletonMapperOperator.h +++ /dev/null @@ -1,164 +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_ANIMATION_SKELETONMAPPEROPERATOR_H -#define CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPEROPERATOR_H -#pragma once - - -#include "../Util/Variable.h" - -#undef GetClassName - -#define SkeletonMapperOperatorRegister(name, className) \ - class CMapperOperatorDesc_##name \ - : public CMapperOperatorDesc \ - { \ - public: \ - CMapperOperatorDesc_##name() \ - : CMapperOperatorDesc(#name) { } \ - protected: \ - virtual const char* GetName() { return #name; } \ - virtual CMapperOperator* Create() { return new className(); } \ - } mapperOperatorDesc__##name; - -namespace Skeleton { - class CMapperOperator; - - class CMapperOperatorDesc - { - public: - static uint32 GetCount() { return uint32(s_descs.size()); } - static const char* GetName(uint32 index) { return s_descs[index]->GetName(); } - static CMapperOperator* Create(uint32 index) { return s_descs[index]->Create(); } - - private: - static std::vector s_descs; - - public: - CMapperOperatorDesc(const char* name); - - protected: - virtual const char* GetName() = 0; - virtual CMapperOperator* Create() = 0; - }; - - class CMapperOperator - : public _reference_target_t - { - protected: - CMapperOperator(const char* className, uint32 positionCount, uint32 orientationCount); - ~CMapperOperator(); - - public: - const char* GetClassName() { return m_className; } - - uint32 GetPositionCount() const { return uint32(m_position.size()); } - void SetPosition(uint32 index, CMapperOperator* pOperator) { m_position[index] = pOperator; } - CMapperOperator* GetPosition(uint32 index) { return m_position[index]; } - - uint32 GetOrientationCount() const { return uint32(m_orientation.size()); } - void SetOrientation(uint32 index, CMapperOperator* pOperator) { m_orientation[index] = pOperator; } - CMapperOperator* GetOrientation(uint32 index) { return m_orientation[index]; } - - uint32 GetParameterCount() { return uint32(m_parameters.size()); } - IVariable* GetParameter(uint32 index) { return m_parameters[index]; } - - bool IsOfClass(const char* className); - uint32 HasLinksOfClass(const char* className); - - bool SerializeTo(XmlNodeRef& node); - bool SerializeFrom(XmlNodeRef& node); - - bool SerializeWithLinksTo(XmlNodeRef& node); - bool SerializeWithLinksFrom(XmlNodeRef& node); - - protected: - void AddParameter(IVariable& variable) { m_parameters.push_back(&variable); } - - public: - virtual QuatT Compute() = 0; - - private: - const char* m_className; - std::vector<_smart_ptr > m_position; - std::vector<_smart_ptr > m_orientation; - - std::vector m_parameters; - }; - - class CMapperLocation - : public CMapperOperator - { - public: - CMapperLocation() - : CMapperOperator("Location", 0, 0) - { - m_pName = new CVariable(); - m_pName->SetName("name"); - m_pName->SetFlags(m_pName->GetFlags() | IVariable::UI_INVISIBLE); - AddParameter(*m_pName); - - m_pAxis = new CVariable(); - m_pAxis->SetName("axis"); - m_pAxis->SetLimits(-3.0f, +3.0f); - m_pAxis->Set(Vec3(1.0f, 2.0f, 3.0f)); - AddParameter(*m_pAxis); - - m_location = QuatT(IDENTITY); - } - - public: - void SetName(const char* name) { m_pName->Set(name); } - CString GetName() const { CString s; m_pName->Get(s); return s; } - - void SetLocation(const QuatT& location) { m_location = location; } - const QuatT& GetLocation() const { return m_location; } - - // CMapperOperator - public: - virtual QuatT Compute() - { - Vec3 axis; - m_pAxis->Get(axis); - - uint32 x = fabs_tpl(axis.x); - uint32 y = fabs_tpl(axis.y); - uint32 z = fabs_tpl(axis.z); - if (x < 1 || y < 1 || z < 1 || - x > 3 || y > 3 || y > 3 || - x == y || x == z || y == z) - { - return QuatT(IDENTITY); - } - - Matrix33 matrix; - matrix.SetFromVectors( - m_location.q.GetColumn(x - 1) * f32(::sgn(axis.x)), - m_location.q.GetColumn(y - 1) * f32(::sgn(axis.y)), - m_location.q.GetColumn(z - 1) * f32(::sgn(axis.z))); - if (!matrix.IsOrthonormalRH(0.01f)) - { - return QuatT(IDENTITY); - } - - QuatT result = m_location; - result.q = Quat(matrix); - return result; - } - - private: - CVariable* m_pName; - CVariable* m_pAxis; - - QuatT m_location; - }; -} // namespace Skeleton - -#endif // CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPEROPERATOR_H diff --git a/Code/Editor/ControlMRU.cpp b/Code/Editor/ControlMRU.cpp deleted file mode 100644 index 47de13950f..0000000000 --- a/Code/Editor/ControlMRU.cpp +++ /dev/null @@ -1,135 +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 "EditorDefs.h" -#include "ControlMRU.h" - -IMPLEMENT_XTP_CONTROL(CControlMRU, CXTPControlRecentFileList) - -bool CControlMRU::DoesFileExist(CString& sFileName) -{ - return (_access(sFileName.GetBuffer(), 0) == 0); -} - -void CControlMRU::OnCalcDynamicSize(DWORD dwMode) -{ - CRecentFileList* pRecentFileList = GetRecentFileList(); - - if (!pRecentFileList) - { - return; - } - - CString* pArrNames = pRecentFileList->m_arrNames; - - assert(pArrNames != NULL); - if (!pArrNames) - { - return; - } - - while (m_nIndex + 1 < m_pControls->GetCount()) - { - CXTPControl* pControl = m_pControls->GetAt(m_nIndex + 1); - assert(pControl); - if (pControl->GetID() >= GetFirstMruID() - && pControl->GetID() <= GetFirstMruID() + pRecentFileList->m_nSize) - { - m_pControls->Remove(pControl); - } - else - { - break; - } - } - - if (m_pParent->IsCustomizeMode()) - { - m_dwHideFlags = 0; - SetEnabled(TRUE); - return; - } - - if (pArrNames[0].IsEmpty()) - { - SetCaption(CString(MAKEINTRESOURCE(IDS_NORECENTFILE_CAPTION))); - SetDescription("No recently opened files"); - m_dwHideFlags = 0; - SetEnabled(FALSE); - - return; - } - else - { - SetCaption(CString(MAKEINTRESOURCE(IDS_RECENTFILE_CAPTION))); - SetDescription("Open this document"); - } - - m_dwHideFlags |= xtpHideGeneric; - - CString sCurDir = (Path::GetEditingGameDataFolder() + "\\").c_str(); - int nCurDir = sCurDir.GetLength(); - - CString strName; - CString strTemp; - int iLastValidMRU = 0; - - for (int iMRU = 0; iMRU < pRecentFileList->m_nSize; iMRU++) - { - if (!pRecentFileList->GetDisplayName(strName, iMRU, sCurDir.GetBuffer(), nCurDir)) - { - break; - } - - if (DoesFileExist(pArrNames[iMRU])) - { - CString sCurEntryDir = pArrNames[iMRU].Left(nCurDir); - - if (sCurEntryDir.CompareNoCase(sCurDir) != 0) - { - //unavailable entry (wrong directory) - continue; - } - } - else - { - //invalid entry (not existing) - continue; - } - - int nId = iMRU + GetFirstMruID(); - - CXTPControl* pControl = m_pControls->Add(xtpControlButton, nId, _T(""), m_nIndex + iLastValidMRU + 1, TRUE); - assert(pControl); - - pControl->SetCaption(CXTPControlWindowList::ConstructCaption(strName, iLastValidMRU + 1)); - pControl->SetFlags(xtpFlagManualUpdate); - pControl->SetBeginGroup(iLastValidMRU == 0 && m_nIndex != 0); - pControl->SetParameter(pArrNames[iMRU]); - - CString sDescription = "Open file: " + pArrNames[iMRU]; - pControl->SetDescription(sDescription); - - if ((GetFlags() & xtpFlagWrapRow) && iMRU == 0) - { - pControl->SetFlags(pControl->GetFlags() | xtpFlagWrapRow); - } - - ++iLastValidMRU; - } - - //if no entry was valid, treat as none would exist - if (iLastValidMRU == 0) - { - SetCaption(CString(MAKEINTRESOURCE(IDS_NORECENTFILE_CAPTION))); - SetDescription("No recently opened files"); - m_dwHideFlags = 0; - SetEnabled(FALSE); - } -} diff --git a/Code/Editor/ControlMRU.h b/Code/Editor/ControlMRU.h deleted file mode 100644 index 4ca6562589..0000000000 --- a/Code/Editor/ControlMRU.h +++ /dev/null @@ -1,24 +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 -#ifndef CRYINCLUDE_EDITOR_CONTROLMRU_H -#define CRYINCLUDE_EDITOR_CONTROLMRU_H - -class CControlMRU - : public CXTPControlRecentFileList -{ -protected: - virtual void OnCalcDynamicSize(DWORD dwMode); - -private: - DECLARE_XTP_CONTROL(CControlMRU) - bool DoesFileExist(CString& sFileName); -}; -#endif // CRYINCLUDE_EDITOR_CONTROLMRU_H diff --git a/Code/Editor/Controls/ConsoleSCBMFC.cpp b/Code/Editor/Controls/ConsoleSCBMFC.cpp deleted file mode 100644 index 3337997811..0000000000 --- a/Code/Editor/Controls/ConsoleSCBMFC.cpp +++ /dev/null @@ -1,543 +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 "EditorDefs.h" -#include "ConsoleSCBMFC.h" -#include "PropertiesDialog.h" -#include "QtViewPaneManager.h" -#include "Core/QtEditorApplication.h" - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace MFC -{ - -static CPropertiesDialog* gPropertiesDlg = nullptr; -static CString mfc_popup_helper(HWND hwnd, int x, int y); -static CConsoleSCB* s_consoleSCB = nullptr; - -static QString RemoveColorCode(const QString& text, int& iColorCode) -{ - QString cleanString; - cleanString.reserve(text.size()); - - const int textSize = text.size(); - for (int i = 0; i < textSize; ++i) - { - QChar c = text.at(i); - bool isLast = i == textSize - 1; - if (c == '$' && !isLast && text.at(i + 1).isDigit()) - { - if (iColorCode == 0) - { - iColorCode = text.at(i + 1).digitValue(); - } - ++i; - continue; - } - - if (c == '\r' || c == '\n') - { - ++i; - continue; - } - - cleanString.append(c); - } - - return cleanString; -} - -ConsoleLineEdit::ConsoleLineEdit(QWidget* parent) - : QLineEdit(parent) - , m_historyIndex(0) - , m_bReusedHistory(false) -{ -} - -void ConsoleLineEdit::mousePressEvent(QMouseEvent* ev) -{ - if (ev->type() == QEvent::MouseButtonPress && ev->button() & Qt::RightButton) - { - Q_EMIT variableEditorRequested(); - } - - QLineEdit::mousePressEvent(ev); -} - -void ConsoleLineEdit::mouseDoubleClickEvent(QMouseEvent* ev) -{ - Q_EMIT variableEditorRequested(); -} - -bool ConsoleLineEdit::event(QEvent* ev) -{ - // Tab key doesn't go to keyPressEvent(), must be processed here - - if (ev->type() != QEvent::KeyPress) - { - return QLineEdit::event(ev); - } - - QKeyEvent* ke = static_cast(ev); - if (ke->key() != Qt::Key_Tab) - { - return QLineEdit::event(ev); - } - - QString inputStr = text(); - QString newStr; - - QStringList tokens = inputStr.split(" "); - inputStr = tokens.isEmpty() ? QString() : tokens.first(); - IConsole* console = GetIEditor()->GetSystem()->GetIConsole(); - - const bool ctrlPressed = ke->modifiers() & Qt::ControlModifier; - CString cstring = QtUtil::ToCString(inputStr); // TODO: Use QString once the backend stops using QString - if (ctrlPressed) - { - newStr = QtUtil::ToString(console->AutoCompletePrev(cstring)); - } - else - { - newStr = QtUtil::ToString(console->ProcessCompletion(cstring)); - newStr = QtUtil::ToString(console->AutoComplete(cstring)); - - if (newStr.isEmpty()) - { - newStr = QtUtil::ToQString(GetIEditor()->GetCommandManager()->AutoComplete(QtUtil::ToString(newStr))); - } - } - - if (!newStr.isEmpty()) - { - newStr += " "; - setText(newStr); - } - - deselect(); - return true; -} - -void ConsoleLineEdit::keyPressEvent(QKeyEvent* ev) -{ - IConsole* console = GetIEditor()->GetSystem()->GetIConsole(); - auto commandManager = GetIEditor()->GetCommandManager(); - - console->ResetAutoCompletion(); - - switch (ev->key()) - { - case Qt::Key_Enter: - case Qt::Key_Return: - { - QString str = text().trimmed(); - if (!str.isEmpty()) - { - if (commandManager->IsRegistered(QtUtil::ToCString(str))) - { - commandManager->Execute(QtUtil::ToString(str)); - } - else - { - CLogFile::WriteLine(QtUtil::ToCString(str)); - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString(QtUtil::ToCString(str)); - } - - // If a history command was reused directly via up arrow enter, do not reset history index - if (m_history.size() > 0 && m_historyIndex < m_history.size() && m_history[m_historyIndex] == str) - { - m_bReusedHistory = true; - } - else - { - m_historyIndex = m_history.size(); - } - - // Do not add the same string if it is the top of the stack, but allow duplicate entries otherwise - if (m_history.isEmpty() || m_history.back() != str) - { - m_history.push_back(str); - if (!m_bReusedHistory) - { - m_historyIndex = m_history.size(); - } - } - } - else - { - m_historyIndex = m_history.size(); - } - - setText(QString()); - break; - } - case Qt::Key_AsciiTilde: // ~ - case Qt::Key_Agrave: // ` - // disable log. - GetIEditor()->ShowConsole(false); - setText(QString()); - m_historyIndex = m_history.size(); - break; - case Qt::Key_Escape: - setText(QString()); - m_historyIndex = m_history.size(); - break; - case Qt::Key_Up: - DisplayHistory(false /*bForward*/); - break; - case Qt::Key_Down: - DisplayHistory(true /*bForward*/); - break; - default: - QLineEdit::keyPressEvent(ev); - } -} - -void ConsoleLineEdit::DisplayHistory(bool bForward) -{ - if (m_history.isEmpty()) - { - return; - } - - // Immediately after reusing a history entry, ensure up arrow re-displays command just used - if (!m_bReusedHistory || bForward) - { - m_historyIndex = static_cast(clamp_tpl(static_cast(m_historyIndex) + (bForward ? 1 : -1), 0, m_history.size() - 1)); - } - m_bReusedHistory = false; - - setText(m_history[m_historyIndex]); -} - -ConsoleTextEdit::ConsoleTextEdit(QWidget* parent) - : QTextEdit(parent) -{ -} - - -Lines CConsoleSCB::s_pendingLines; - -CConsoleSCB::CConsoleSCB(QWidget* parent) - : QWidget(parent) - , ui(new Ui::ConsoleMFC()) - , m_richEditTextLength(0) - , m_backgroundTheme(gSettings.consoleBackgroundColorTheme) -{ - m_lines = s_pendingLines; - s_pendingLines.clear(); - s_consoleSCB = this; - ui->setupUi(this); - setMinimumHeight(120); - - // Setup the color table for the default (light) theme - m_colorTable << QColor(0, 0, 0) - << QColor(0, 0, 0) - << QColor(0, 0, 200) // blue - << QColor(0, 200, 0) // green - << QColor(200, 0, 0) // red - << QColor(0, 200, 200) // cyan - << QColor(128, 112, 0) // yellow - << QColor(200, 0, 200) // red+blue - << QColor(0x000080ff) - << QColor(0x008f8f8f); - OnStyleSettingsChanged(); - - connect(ui->button, &QPushButton::clicked, this, &CConsoleSCB::showVariableEditor); - connect(ui->lineEdit, &MFC::ConsoleLineEdit::variableEditorRequested, this, &MFC::CConsoleSCB::showVariableEditor); - connect(Editor::EditorQtApplication::instance(), &Editor::EditorQtApplication::skinChanged, this, &MFC::CConsoleSCB::OnStyleSettingsChanged); - - if (GetIEditor()->IsInConsolewMode()) - { - // Attach / register edit box - //CLogFile::AttachEditBox(m_edit.GetSafeHwnd()); // FIXME - } -} - -CConsoleSCB::~CConsoleSCB() -{ - s_consoleSCB = nullptr; - delete gPropertiesDlg; - gPropertiesDlg = nullptr; - CLogFile::AttachEditBox(nullptr); -} - -void CConsoleSCB::RegisterViewClass() -{ - QtViewOptions opts; - opts.preferedDockingArea = Qt::BottomDockWidgetArea; - opts.isDeletable = false; - opts.isStandard = true; - opts.showInMenu = true; - opts.builtInActionId = ID_VIEW_CONSOLEWINDOW; - opts.sendViewPaneNameBackToAmazonAnalyticsServers = true; - RegisterQtViewPane(GetIEditor(), LyViewPane::Console, LyViewPane::CategoryTools, opts); -} - -void CConsoleSCB::OnStyleSettingsChanged() -{ - ui->button->setIcon(QIcon(QString(":/controls/img/cvar_dark.bmp"))); - - // Set the debug/warning text colors appropriately for the background theme - // (e.g. not have black text on black background) - QColor textColor = Qt::black; - m_backgroundTheme = gSettings.consoleBackgroundColorTheme; - if (m_backgroundTheme == SEditorSettings::ConsoleColorTheme::Dark) - { - textColor = Qt::white; - } - m_colorTable[0] = textColor; - m_colorTable[1] = textColor; - - QColor bgColor; - if (!GetIEditor()->IsInConsolewMode() && CConsoleSCB::GetCreatedInstance() && m_backgroundTheme == SEditorSettings::ConsoleColorTheme::Dark) - { - bgColor = Qt::black; - } - else - { - bgColor = Qt::white; - } - - ui->textEdit->setStyleSheet(QString("QTextEdit{ background: %1 }").arg(bgColor.name(QColor::HexRgb))); - - // Clear out the console text when we change our background color since - // some of the previous text colors may not be appropriate for the - // new background color - ui->textEdit->clear(); -} - -void CConsoleSCB::showVariableEditor() -{ - const QPoint cursorPos = QCursor::pos(); - CString str = mfc_popup_helper(0, cursorPos.x(), cursorPos.y()); - if (!str.IsEmpty()) - { - ui->lineEdit->setText(QtUtil::ToQString(str)); - } -} - -void CConsoleSCB::SetInputFocus() -{ - ui->lineEdit->setFocus(); - ui->lineEdit->setText(QString()); -} - -void CConsoleSCB::AddToConsole(const QString& text, bool bNewLine) -{ - m_lines.push_back({ text, bNewLine }); - FlushText(); -} - -void CConsoleSCB::FlushText() -{ - if (m_lines.empty()) - { - return; - } - - // Store our current cursor in case we need to restore it, and check if - // the user has scrolled the text edit away from the bottom - const QTextCursor oldCursor = ui->textEdit->textCursor(); - QScrollBar* scrollBar = ui->textEdit->verticalScrollBar(); - const int oldScrollValue = scrollBar->value(); - bool scrolledOffBottom = oldScrollValue != scrollBar->maximum(); - - ui->textEdit->moveCursor(QTextCursor::End); - QTextCursor textCursor = ui->textEdit->textCursor(); - - while (!m_lines.empty()) - { - ConsoleLine line = m_lines.front(); - m_lines.pop_front(); - - int iColor = 0; - QString text = MFC::RemoveColorCode(line.text, iColor); - if (iColor < 0 || iColor >= m_colorTable.size()) - { - iColor = 0; - } - - if (line.newLine) - { - text = QtUtil::trimRight(text); - text = "\r\n" + text; - } - - QTextCharFormat format; - const QColor color(m_colorTable[iColor]); - format.setForeground(color); - - if (iColor != 0) - { - format.setFontWeight(QFont::Bold); - } - - textCursor.setCharFormat(format); - textCursor.insertText(text); - } - - // If the user has selected some text in the text edit area or has scrolled - // away from the bottom, then restore the previous cursor and keep the scroll - // bar in the same location - if (oldCursor.hasSelection() || scrolledOffBottom) - { - ui->textEdit->setTextCursor(oldCursor); - scrollBar->setValue(oldScrollValue); - } - // Otherwise scroll to the bottom so the latest text can be seen - else - { - scrollBar->setValue(scrollBar->maximum()); - } -} - -QSize CConsoleSCB::minimumSizeHint() const -{ - return QSize(-1, -1); -} - -QSize CConsoleSCB::sizeHint() const -{ - return QSize(100, 100); -} - -/** static */ -void CConsoleSCB::AddToPendingLines(const QString& text, bool bNewLine) -{ - s_pendingLines.push_back({ text, bNewLine }); -} - -static CVarBlock* VarBlockFromConsoleVars() -{ - IConsole* console = GetIEditor()->GetSystem()->GetIConsole(); - std::vector cmds; - cmds.resize(console->GetNumVars()); - size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size()); - - CVarBlock* vb = new CVarBlock; - IVariable* pVariable = 0; - for (int i = 0; i < cmdCount; i++) - { - ICVar* pCVar = console->GetCVar(cmds[i]); - if (!pCVar) - { - continue; - } - int varType = pCVar->GetType(); - - switch (varType) - { - case CVAR_INT: - pVariable = new CVariable(); - pVariable->Set(pCVar->GetIVal()); - break; - case CVAR_FLOAT: - pVariable = new CVariable(); - pVariable->Set(pCVar->GetFVal()); - break; - case CVAR_STRING: - pVariable = new CVariable(); - pVariable->Set(pCVar->GetString()); - break; - default: - assert(0); - } - - pVariable->SetDescription(pCVar->GetHelp()); - pVariable->SetName(cmds[i]); - - if (pVariable) - { - vb->AddVariable(pVariable); - } - } - return vb; -} - -static void OnConsoleVariableUpdated(IVariable* pVar) -{ - if (!pVar) - { - return; - } - CString varName = pVar->GetName(); - ICVar* pCVar = GetIEditor()->GetSystem()->GetIConsole()->GetCVar(varName); - if (!pCVar) - { - return; - } - if (pVar->GetType() == IVariable::INT) - { - int val; - pVar->Get(val); - pCVar->Set(val); - } - else if (pVar->GetType() == IVariable::FLOAT) - { - float val; - pVar->Get(val); - pCVar->Set(val); - } - else if (pVar->GetType() == IVariable::STRING) - { - CString val; - pVar->Get(val); - pCVar->Set(val); - } -} - -static CString mfc_popup_helper(HWND hwnd, int x, int y) -{ - IConsole* console = GetIEditor()->GetSystem()->GetIConsole(); - - TSmartPtr vb = VarBlockFromConsoleVars(); - XmlNodeRef node; - if (!gPropertiesDlg) - { - gPropertiesDlg = new CPropertiesDialog("Console Variables", node, AfxGetMainWnd(), true); - } - if (!gPropertiesDlg->m_hWnd) - { - gPropertiesDlg->Create(CPropertiesDialog::IDD, AfxGetMainWnd()); - gPropertiesDlg->SetUpdateCallback(AZStd::bind(OnConsoleVariableUpdated, AZStd::placeholders::_1)); - } - gPropertiesDlg->ShowWindow(SW_SHOW); - gPropertiesDlg->BringWindowToTop(); - gPropertiesDlg->GetPropertyCtrl()->AddVarBlock(vb); - - return ""; -} - -CConsoleSCB* CConsoleSCB::GetCreatedInstance() -{ - return s_consoleSCB; -} - -} // namespace MFC - -#include diff --git a/Code/Editor/Util/IXmlHistoryManager.h b/Code/Editor/Util/IXmlHistoryManager.h deleted file mode 100644 index e133d073bc..0000000000 --- a/Code/Editor/Util/IXmlHistoryManager.h +++ /dev/null @@ -1,73 +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_UTIL_IXMLHISTORYMANAGER_H -#define CRYINCLUDE_EDITOR_UTIL_IXMLHISTORYMANAGER_H -#pragma once - - -// Helper class to handle Redo/Undo on set of Xml nodes -struct IXmlUndoEventHandler -{ - virtual bool SaveToXml(XmlNodeRef& xmlNode) = 0; - virtual bool LoadFromXml(const XmlNodeRef& xmlNode) = 0; - virtual bool ReloadFromXml(const XmlNodeRef& xmlNode) = 0; -}; - -struct IXmlHistoryEventListener -{ - enum EHistoryEventType - { - eHET_HistoryDeleted, - eHET_HistoryCleared, - eHET_HistorySaved, - - eHET_VersionChanged, - eHET_VersionAdded, - - eHET_HistoryInvalidate, - - eHET_HistoryGroupChanged, - eHET_HistoryGroupAdded, - eHET_HistoryGroupRemoved, - }; - virtual void OnEvent(EHistoryEventType event, void* pData = NULL) = 0; -}; - -struct IXmlHistoryView -{ - virtual bool LoadXml(int typeId, const XmlNodeRef& xmlNode, IXmlUndoEventHandler*& pUndoEventHandler, uint32 userindex) = 0; - virtual void UnloadXml(int typeId) = 0; -}; - -struct IXmlHistoryManager -{ - // Undo/Redo - virtual bool Undo() = 0; - virtual bool Redo() = 0; - virtual bool Goto(int historyNum) = 0; - virtual void RecordUndo(IXmlUndoEventHandler* pEventHandler, const char* desc) = 0; - virtual void UndoEventHandlerDestroyed(IXmlUndoEventHandler* pEventHandler, uint32 typeId = 0, bool destoryForever = false) = 0; - virtual void RestoreUndoEventHandler(IXmlUndoEventHandler* pEventHandler, uint32 typeId) = 0; - - virtual void RegisterEventListener(IXmlHistoryEventListener* pEventListener) = 0; - virtual void UnregisterEventListener(IXmlHistoryEventListener* pEventListener) = 0; - - // History - virtual void ClearHistory(bool flagAsSaved = false) = 0; - virtual int GetVersionCount() const = 0; - virtual const AZStd::string& GetVersionDesc(int number) const = 0; - virtual int GetCurrentVersionNumber() const = 0; - - // Views - virtual void RegisterView(IXmlHistoryView* pView) = 0; - virtual void UnregisterView(IXmlHistoryView* pView) = 0; -}; - -#endif // CRYINCLUDE_EDITOR_UTIL_IXMLHISTORYMANAGER_H diff --git a/Code/Editor/Util/StringNoCasePredicate.h b/Code/Editor/Util/StringNoCasePredicate.h deleted file mode 100644 index 4fb81cf7d6..0000000000 --- a/Code/Editor/Util/StringNoCasePredicate.h +++ /dev/null @@ -1,62 +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 : Utility class to help in STL algorithms on containers with -// CStrings when intending to use case insensitive searches or sorting for -// example. - - -#ifndef CRYINCLUDE_EDITOR_UTIL_STRINGNOCASEPREDICATE_H -#define CRYINCLUDE_EDITOR_UTIL_STRINGNOCASEPREDICATE_H -#pragma once - -/* -Utility class to help in STL algorithms on containers with CStrings -when intending to use case insensitive searches or sorting for example. - -e.g. -std::vector< CString > v; -... -std::sort( v.begin(), v.end(), CStringNoCasePredicate::LessThan() ); -std::find_if( v.begin(), v.end(), CStringNoCasePredicate::Equal( stringImLookingFor ) ); -*/ -class CStringNoCasePredicate -{ -public: - ////////////////////////////////////////////////////////////////////////// - struct Equal - { - Equal(const QString& referenceString) - : m_referenceString(referenceString) - { - } - - bool operator() (const QString& arg) const - { - return (m_referenceString.compare(arg, Qt::CaseInsensitive) == 0); - } - - private: - const QString& m_referenceString; - }; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - struct LessThan - { - bool operator() (const QString& arg1, const QString& arg2) const - { - return (arg1.CompareNoCase(arg2) < 0); - } - }; - ////////////////////////////////////////////////////////////////////////// -}; - - -#endif // CRYINCLUDE_EDITOR_UTIL_STRINGNOCASEPREDICATE_H diff --git a/Code/Editor/Util/XmlHistoryManager.cpp b/Code/Editor/Util/XmlHistoryManager.cpp deleted file mode 100644 index b642929af1..0000000000 --- a/Code/Editor/Util/XmlHistoryManager.cpp +++ /dev/null @@ -1,875 +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 "EditorDefs.h" - -#include "XmlHistoryManager.h" - -//////////////////////////////////////////////////////////////////////////// -SXmlHistory::SXmlHistory(CXmlHistoryManager* pManager, const XmlNodeRef& xmlBaseVersion, uint32 typeId) - : m_pManager(pManager) - , m_typeId(typeId) - , m_DeletedVersion(-1) - , m_SavedVersion(-1) -{ - int newVersionNumber = m_pManager->GetCurrentVersionNumber() + (m_pManager->IsPreparedForNextVersion() ? 1 : 0); - m_xmlVersionList[ newVersionNumber ] = xmlBaseVersion; -} - -//////////////////////////////////////////////////////////////////////////// -void SXmlHistory::AddToHistory(const XmlNodeRef& newXmlVersion) -{ - int newVersionNumber = m_pManager->IncrementVersion(this); - m_xmlVersionList[ newVersionNumber ] = newXmlVersion; -} - -//////////////////////////////////////////////////////////////////////////// -const XmlNodeRef& SXmlHistory::Undo(bool* bVersionExist) -{ - m_pManager->Undo(); - return GetCurrentVersion(bVersionExist); -} - -//////////////////////////////////////////////////////////////////////////// -const XmlNodeRef& SXmlHistory::Redo() -{ - m_pManager->Redo(); - return GetCurrentVersion(); -} - -//////////////////////////////////////////////////////////////////////////// -const XmlNodeRef& SXmlHistory::GetCurrentVersion(bool* bVersionExist, int* iVersionNumber) const -{ - int currentVersion = m_pManager->GetCurrentVersionNumber(); - - TXmlVersionMap::const_iterator it = m_xmlVersionList.begin(); - TXmlVersionMap::const_iterator previt = m_xmlVersionList.begin(); - while (it != m_xmlVersionList.end()) - { - if (it->first > currentVersion) - { - break; - } - previt = it; - ++it; - } - - if (bVersionExist) - { - *bVersionExist = currentVersion >= m_xmlVersionList.begin()->first; - } - if (iVersionNumber) - { - *iVersionNumber = previt->first; - } - - return previt->second; -} - -//////////////////////////////////////////////////////////////////////////// -bool SXmlHistory::IsModified() const -{ - int currVersion; - GetCurrentVersion(NULL, &currVersion); - return m_SavedVersion != currVersion; -} - -//////////////////////////////////////////////////////////////////////////// -void SXmlHistory::FlagAsDeleted() -{ - assert(m_pManager->IsPreparedForNextVersion()); - m_DeletedVersion = m_pManager->GetCurrentVersionNumber() + 1; - m_SavedVersion = -1; -} - -//////////////////////////////////////////////////////////////////////////// -void SXmlHistory::FlagAsSaved() -{ - if (Exist()) - { - int currVersion; - GetCurrentVersion(NULL, &currVersion); - m_SavedVersion = currVersion; - } -} - -//////////////////////////////////////////////////////////////////////////// -bool SXmlHistory::Exist() const -{ - // int currentVersion = m_pManager->GetCurrentVersionNumber(); - // bool deleted = m_DeletedVersion != -1 && currentVersion >= m_DeletedVersion; - // bool exist = currentVersion >= m_xmlVersionList.begin()->first; - // return !deleted && exist; - int currentVersion = m_pManager->GetCurrentVersionNumber(); - return currentVersion >= m_xmlVersionList.begin()->first && (m_DeletedVersion == -1 || currentVersion < m_DeletedVersion); -} - -//////////////////////////////////////////////////////////////////////////// -void SXmlHistory::ClearRedo() -{ - int currentVersion = m_pManager->GetCurrentVersionNumber(); - if (m_DeletedVersion > currentVersion + (m_pManager->IsPreparedForNextVersion() ? 1 : 0)) - { - m_DeletedVersion = -1; - } - TXmlVersionMap::iterator it = m_xmlVersionList.begin(); - for (; it != m_xmlVersionList.end(); ++it) - { - if (it->first > currentVersion) - { - break; - } - } - if (it != m_xmlVersionList.end()) - { - ++it; - while (it != m_xmlVersionList.end()) - { - m_xmlVersionList.erase(it++); - } - } -} - -//////////////////////////////////////////////////////////////////////////// -void SXmlHistory::ClearHistory(bool flagAsSaved) -{ - bool wasModified = !flagAsSaved && IsModified(); - m_DeletedVersion = Exist() ? -1 : 0; - ClearRedo(); - XmlNodeRef latest = m_xmlVersionList.rbegin()->second; - m_xmlVersionList.clear(); - m_xmlVersionList[ 0 ] = latest; - m_SavedVersion = wasModified ? -1 : 0; -} - -//////////////////////////////////////////////////////////////////////////// -SXmlHistoryGroup::SXmlHistoryGroup(CXmlHistoryManager* pManager, uint32 typeId) - : m_pManager(pManager) - , m_typeId(typeId) -{ -} - -//////////////////////////////////////////////////////////////////////////// -SXmlHistory* SXmlHistoryGroup::GetHistory(int index) const -{ - THistoryList::const_iterator it = m_List.begin(); - while (index > 0 && it != m_List.end()) - { - ++it; - if ((*it)->Exist()) - { - --index; - } - } - return it != m_List.end() ? *it : NULL; -} - -//////////////////////////////////////////////////////////////////////////// -int SXmlHistoryGroup::GetHistoryCount() const -{ - int count = 0; - for (THistoryList::const_iterator it = m_List.begin(); it != m_List.end(); ++it) - { - if ((*it)->Exist()) - { - count++; - } - } - return count; -} - -//////////////////////////////////////////////////////////////////////////// -SXmlHistory* SXmlHistoryGroup::GetHistoryByTypeId(uint32 typeId, int index /*= 0*/) const -{ - for (int i = 0; i < GetHistoryCount(); ++i) - { - SXmlHistory* pHistory = GetHistory(i); - if (pHistory->GetTypeId() == typeId) - { - index--; - } - if (index == -1) - { - return pHistory; - } - } - return NULL; -} - -//////////////////////////////////////////////////////////////////////////// -int SXmlHistoryGroup::GetHistoryCountByTypeId(uint32 typeId) const -{ - int res = 0; - for (int i = 0; i < GetHistoryCount(); ++i) - { - if (GetHistory(i)->GetTypeId() == typeId) - { - res++; - } - } - return res; -} - -//////////////////////////////////////////////////////////////////////////// -int SXmlHistoryGroup::CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion) -{ - if (m_pManager) - { - m_List.push_back(m_pManager->CreateXmlHistory(typeId, xmlBaseVersion)); - return m_List.size() - 1; - } - return -1; -} - -//////////////////////////////////////////////////////////////////////////// -int SXmlHistoryGroup::GetHistoryIndex(const SXmlHistory* pHistory) const -{ - int index = 0; - for (THistoryList::const_iterator it = m_List.begin(); it != m_List.end(); ++it) - { - if (*it == pHistory) - { - return index; - } - index++; - } - return -1; -} - -//////////////////////////////////////////////////////////////////////////// -CXmlHistoryManager::CXmlHistoryManager() - : m_CurrentVersion(0) - , m_LatestVersion(0) - , m_pExclusiveListener(NULL) - , m_RecordNextVersion(false) - , m_pExActiveGroup(NULL) - , m_bIsActiveGroupEx(false) -{ - m_pNullGroup = new SXmlHistoryGroup(this, (uint32) - 1); -} - -CXmlHistoryManager::~CXmlHistoryManager() -{ - delete m_pNullGroup; -} - -///////////////////////////////////////////////////////////////////////////// -bool CXmlHistoryManager::Undo() -{ - if (m_CurrentVersion > 0) - { - int prevVersion = m_CurrentVersion; - const SXmlHistoryGroup* pPrevCurrGroup = GetActiveGroup(); - m_CurrentVersion--; - ReloadCurrentVersion(pPrevCurrGroup, prevVersion); - return true; - } - return false; -} - -///////////////////////////////////////////////////////////////////////////// -bool CXmlHistoryManager::Redo() -{ - if (m_CurrentVersion < m_LatestVersion) - { - int prevVersion = m_CurrentVersion; - const SXmlHistoryGroup* pPrevCurrGroup = GetActiveGroup(); - m_CurrentVersion++; - ReloadCurrentVersion(pPrevCurrGroup, prevVersion); - return true; - } - return false; -} - -///////////////////////////////////////////////////////////////////////////// -bool CXmlHistoryManager::Goto(int historyNum) -{ - if (historyNum >= 0 && historyNum <= m_LatestVersion) - { - int prevVersion = m_CurrentVersion; - const SXmlHistoryGroup* pPrevCurrGroup = GetActiveGroup(); - m_CurrentVersion = historyNum; - ReloadCurrentVersion(pPrevCurrGroup, prevVersion); - return true; - } - return false; -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RecordUndo(IXmlUndoEventHandler* pEventHandler, const char* desc) -{ - ClearRedo(); - SXmlHistory* pChangedXml = m_UndoEventHandlerMap[ pEventHandler ].CurrentData; - assert(pChangedXml); - - XmlNodeRef newData = gEnv->pSystem->CreateXmlNode(); -#if !defined(NDEBUG) - bool bRes = -#endif - pEventHandler->SaveToXml(newData); - assert(bRes); - - TXmlHistotyGroupPtrList activeGroups = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups; - - pChangedXml->AddToHistory(newData); - m_UndoEventHandlerMap[ pEventHandler ].HistoryData[ m_CurrentVersion ] = pChangedXml; - m_HistoryInfoMap[ m_CurrentVersion ].HistoryDescription = desc; - m_HistoryInfoMap[ m_CurrentVersion ].IsNullUndo = false; - m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups = activeGroups; - m_HistoryInfoMap[ m_CurrentVersion ].HistoryInvalidated = false; - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_VersionAdded); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::UndoEventHandlerDestroyed(IXmlUndoEventHandler* pEventHandler, uint32 typeId /*= 0*/, bool destoryForever /*= false*/) -{ - if (destoryForever) - { - UnregisterUndoEventHandler(pEventHandler); - } - else - { - m_InvalidHandlerMap[typeId] = pEventHandler; - } -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RestoreUndoEventHandler(IXmlUndoEventHandler* pEventHandler, uint32 typeId) -{ - TInvalidUndoEventListener::iterator it = m_InvalidHandlerMap.find(typeId); - if (it != m_InvalidHandlerMap.end()) - { - IXmlUndoEventHandler* pLastHandler = it->second; - TUndoEventHandlerMap::iterator lastit = m_UndoEventHandlerMap.find(pLastHandler); - if (lastit != m_UndoEventHandlerMap.end()) - { - m_UndoEventHandlerMap[pEventHandler] = lastit->second; - m_UndoEventHandlerMap.erase(lastit); - } - m_InvalidHandlerMap.erase(it); - } -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RegisterEventListener(IXmlHistoryEventListener* pEventListener) -{ - stl::push_back_unique(m_EventListener, pEventListener); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::UnregisterEventListener(IXmlHistoryEventListener* pEventListener) -{ - m_EventListener.remove(pEventListener); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::PrepareForNextVersion() -{ - assert(!m_RecordNextVersion); - m_RecordNextVersion = true; -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RecordNextVersion(SXmlHistory* pHistory, XmlNodeRef newData, const char* undoDesc /*= NULL*/) -{ - assert(m_RecordNextVersion); - RegisterUndoEventHandler(this, pHistory); - m_newHistoryData = newData; - RecordUndo(this, undoDesc ? undoDesc : ""); - m_RecordNextVersion = false; - m_HistoryInfoMap[ m_CurrentVersion ].HistoryInvalidated = true; - UnregisterUndoEventHandler(this); - SetActiveGroupInt(GetActiveGroup()); - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryInvalidate); -} - -///////////////////////////////////////////////////////////////////////////// -bool CXmlHistoryManager::SaveToXml(XmlNodeRef& xmlNode) -{ - assert(m_newHistoryData); - xmlNode = m_newHistoryData; - return true; -} -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::ClearHistory(bool flagAsSaved) -{ - TXmlHistotyGroupPtrList activeGropus = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups; - for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it) - { - it->ClearHistory(flagAsSaved); - } - - SetActiveGroup(NULL); - - m_CurrentVersion = 0; - m_LatestVersion = 0; - - m_UndoEventHandlerMap.clear(); - m_HistoryInfoMap.clear(); - - m_HistoryInfoMap[ 0 ].HistoryDescription = "New History"; - m_HistoryInfoMap[ 0 ].ActiveGroups = activeGropus; - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryCleared); -} - -///////////////////////////////////////////////////////////////////////////// -const AZStd::string& CXmlHistoryManager::GetVersionDesc(int number) const -{ - THistoryInfoMap::const_iterator it = m_HistoryInfoMap.find(number); - if (it != m_HistoryInfoMap.end()) - { - return it->second.HistoryDescription; - } - - static AZStd::string undef("UNDEFINED"); - return undef; -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RegisterView(IXmlHistoryView* pView) -{ - stl::push_back_unique(m_Views, pView); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::UnregisterView(IXmlHistoryView* pView) -{ - m_Views.remove(pView); -} - -///////////////////////////////////////////////////////////////////////////// -SXmlHistoryGroup* CXmlHistoryManager::CreateXmlGroup(uint32 typeId) -{ - m_Groups.push_back(SXmlHistoryGroup(this, typeId)); - return &(*m_Groups.rbegin()); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::AddXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc /*= NULL*/) -{ - RecordUndoInternal(undoDesc ? undoDesc : "New XML Group added"); - m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups.push_back(pGroup); - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupAdded, (void*)pGroup); -} -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RemoveXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc /*= NULL*/) -{ - bool unload = m_HistoryInfoMap[ m_CurrentVersion ].CurrGroup == pGroup; - RecordUndoInternal(undoDesc ? undoDesc : "XML Group deleted"); - TXmlHistotyGroupPtrList& list = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups; - stl::find_and_erase(list, pGroup); - if (unload) - { - SetActiveGroupInt(NULL); - } - m_HistoryInfoMap[ m_CurrentVersion ].CurrGroup = m_pNullGroup; - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupRemoved, (void*)pGroup); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::SetActiveGroup(const SXmlHistoryGroup* pGroup, const char* displayName /*= NULL*/, const TGroupIndexMap& groupIndex /*= TGroupIndexMap()*/, bool setExternal /*= false*/) -{ - TGroupIndexMap userIndex; - const SXmlHistoryGroup* pActiveGroup = GetActiveGroup(userIndex); - if (pGroup != pActiveGroup || userIndex != groupIndex || setExternal) - { - const bool isEx = m_CurrentVersion != m_LatestVersion || setExternal; - m_pExActiveGroup = const_cast(pGroup); - m_ExCurrentIndex = groupIndex; - m_bIsActiveGroupEx = true; - SetActiveGroupInt(pGroup, displayName, !isEx, groupIndex); - m_bIsActiveGroupEx = isEx; - } -} - -void CXmlHistoryManager::SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const char* displayName /*= NULL*/, bool bRecordNullUndo /*= false*/, const TGroupIndexMap& groupIndex /*= TGroupIndexMap()*/) -{ - UnloadInt(); - - TEventHandlerList eventHandler; - AZStd::string undoDesc; - - if (pGroup) - { - for (TViews::iterator it = m_Views.begin(); it != m_Views.end(); ++it) - { - IXmlHistoryView* pView = *it; - - std::map userIndexCount; - - for (SXmlHistoryGroup::THistoryList::const_iterator history = pGroup->m_List.begin(); history != pGroup->m_List.end(); ++history) - { - std::map::iterator it2 = userIndexCount.find((*history)->GetTypeId()); - if (it2 == userIndexCount.end()) - { - userIndexCount[ (*history)->GetTypeId() ] = 0; - } - uint32 userindex = userIndexCount[ (*history)->GetTypeId() ]; - IXmlUndoEventHandler* pEventHandler = NULL; - TGroupIndexMap::const_iterator indexIter = groupIndex.find((*history)->GetTypeId()); - if (indexIter == groupIndex.end() || indexIter->second == userindex) - { - if ((*history)->Exist()) - { - if (pView->LoadXml((*history)->GetTypeId(), (*history)->GetCurrentVersion(), pEventHandler, userindex)) - { - if (pEventHandler) - { - m_UndoHandlerViewMap[ pEventHandler ] = pView; - RegisterUndoEventHandler(pEventHandler, *history); - eventHandler.push_back(pEventHandler); - } - } - } - } - if ((*history)->Exist()) - { - userIndexCount[ (*history)->GetTypeId() ]++; - } - } - } - undoDesc = AZStd::string::format("Changed View to \"%s\"", displayName ? displayName : "UNDEFINED"); - } - else - { - undoDesc = "Unloaded Views"; - for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it) - { - eventHandler.push_back(it->first); - } - pGroup = m_pNullGroup; - } - - if (bRecordNullUndo) - { - RecordNullUndo(eventHandler, undoDesc.c_str()); - m_HistoryInfoMap[ m_CurrentVersion ].CurrGroup = pGroup; - m_HistoryInfoMap[ m_CurrentVersion ].CurrUserIndex = groupIndex; - } - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupChanged); -} - -///////////////////////////////////////////////////////////////////////////// -const SXmlHistoryGroup* CXmlHistoryManager::GetActiveGroup() const -{ - TGroupIndexMap userIndex; - return GetActiveGroup(userIndex); -} - -///////////////////////////////////////////////////////////////////////////// -const SXmlHistoryGroup* CXmlHistoryManager::GetActiveGroup(TGroupIndexMap& currUserIndex /*out*/) const -{ - if (m_bIsActiveGroupEx) - { - currUserIndex = m_ExCurrentIndex; - return m_pExActiveGroup; - } - - int currVersion = m_CurrentVersion; - do - { - THistoryInfoMap::const_iterator it = m_HistoryInfoMap.find(currVersion); - if (it != m_HistoryInfoMap.end()) - { - const SXmlHistoryGroup* pGroup = it->second.CurrGroup; - if (it != m_HistoryInfoMap.end() && pGroup) - { - currUserIndex = it->second.CurrUserIndex; - return pGroup == m_pNullGroup ? NULL : pGroup; - } - } - currVersion--; - } while (currVersion >= 0); - return NULL; -} - -///////////////////////////////////////////////////////////////////////////// -SXmlHistory* CXmlHistoryManager::CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion) -{ - m_XmlHistoryList.push_back(SXmlHistory(this, xmlBaseVersion, typeId)); - return &(*m_XmlHistoryList.rbegin()); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::DeleteXmlHistory(const SXmlHistory* pXmlHistry) -{ - for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it) - { - if (&(*it) == pXmlHistry) - { - m_XmlHistoryList.erase(it); - return; - } - } -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::UnloadInt() -{ - for (TViews::iterator it = m_Views.begin(); it != m_Views.end(); ++it) - { - IXmlHistoryView* pView = *it; - pView->UnloadXml(-1); - } -} - -///////////////////////////////////////////////////////////////////////////// -namespace -{ - template< class T > - void ClearAfterVersion(T& container, int version) - { - auto foundit = container.end(); - do - { - auto it = container.find(version); - if (it != container.end()) - { - foundit = it; - break; - } - version--; - } while (version >= 0); - if (foundit != container.end()) - { - for (auto it = ++foundit; it != container.end(); ) - { - container.erase(it++); - } - } - } -} - -void CXmlHistoryManager::ClearRedo() -{ - ClearAfterVersion(m_HistoryInfoMap, m_CurrentVersion); - for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it) - { - ClearAfterVersion(it->second.HistoryData, m_CurrentVersion); - } -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::DeleteAll() -{ - ClearHistory(); - m_Groups.clear(); - m_UndoEventHandlerMap.clear(); - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryDeleted); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::FlagHistoryAsSaved() -{ - for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it) - { - it->FlagAsSaved(); - } - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistorySaved); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RecordNullUndo(const TEventHandlerList& eventHandler, const char* desc, bool isNull /*= true*/) -{ - TXmlHistotyGroupPtrList activeGroups = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups; - - // if current version is already null undo, overwrite it instead of create a new version - if (m_HistoryInfoMap[ m_CurrentVersion ].IsNullUndo && isNull) - { - assert(m_CurrentVersion); - m_CurrentVersion--; - } - - ClearRedo(); - IncrementVersion(); - - for (TEventHandlerList::const_iterator it = eventHandler.begin(); it != eventHandler.end(); ++it) - { - SXmlHistory* pChangedXml = m_UndoEventHandlerMap[ *it ].CurrentData; - m_UndoEventHandlerMap[ *it ].HistoryData[ m_CurrentVersion ] = pChangedXml; - } - m_HistoryInfoMap[ m_CurrentVersion ].HistoryDescription = desc; - m_HistoryInfoMap[ m_CurrentVersion ].IsNullUndo = isNull; - m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups = activeGroups; - m_HistoryInfoMap[ m_CurrentVersion ].HistoryInvalidated = false; - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_VersionAdded); -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::ReloadCurrentVersion(const SXmlHistoryGroup* pPrevGroup, int prevVersion) -{ - m_bIsActiveGroupEx = false; - const SXmlHistoryGroup* pActiveGroup = GetActiveGroup(); - - bool bInvalidated = false; - int start = min(prevVersion, m_CurrentVersion); - int end = max(prevVersion, m_CurrentVersion); - for (int i = start; i <= end; ++i) - { - if (m_HistoryInfoMap[i].HistoryInvalidated) - { - bInvalidated = true; - break; - } - } - - if (!bInvalidated && pPrevGroup == pActiveGroup) - { - for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it) - { - IXmlUndoEventHandler* pEventHandler = it->first; - if (!IsEventHandlerValid(pEventHandler)) - { - assert(false); - continue; - } - SXmlHistory* pXmlHistory = GetLatestHistory(m_UndoEventHandlerMap[ pEventHandler ]); /*m_UndoEventHandlerMap[ pEventHandler ].HistoryData[ m_CurrentVersion ];*/ - if (pXmlHistory) - { - if (pXmlHistory->Exist()) - { - pEventHandler->ReloadFromXml(pXmlHistory->GetCurrentVersion()); - } - } - } - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_VersionChanged); - } - else - { - SetActiveGroupInt(pActiveGroup); - } - - if (bInvalidated) - { - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryInvalidate); - } - - TXmlHistotyGroupPtrList oldActiveGroups = m_HistoryInfoMap[ prevVersion ].ActiveGroups; - TXmlHistotyGroupPtrList newActiveGroups = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups; - - RemoveListFromList(newActiveGroups, oldActiveGroups); - RemoveListFromList(oldActiveGroups, m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups); - - for (TXmlHistotyGroupPtrList::iterator it = newActiveGroups.begin(); it != newActiveGroups.end(); ++it) - { - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupAdded, (void*) *it); - } - - for (TXmlHistotyGroupPtrList::iterator it = oldActiveGroups.begin(); it != oldActiveGroups.end(); ++it) - { - NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupRemoved, (void*) *it); - } -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RemoveListFromList(TXmlHistotyGroupPtrList& list, const TXmlHistotyGroupPtrList& removeList) -{ - for (TXmlHistotyGroupPtrList::const_iterator rit = removeList.begin(); rit != removeList.end(); ++rit) - { - for (TXmlHistotyGroupPtrList::iterator it = list.begin(); it != list.end(); ++it) - { - if (*it == *rit) - { - list.erase(it); - break; - } - } - } -} - -///////////////////////////////////////////////////////////////////////////// -SXmlHistory* CXmlHistoryManager::GetLatestHistory(SUndoEventHandlerData& eventHandlerData) -{ - int currVersion = m_CurrentVersion; - do - { - THistoryVersionMap::iterator it = eventHandlerData.HistoryData.find(currVersion); - if (it != eventHandlerData.HistoryData.end()) - { - return it->second; - } - currVersion--; - } while (currVersion >= 0); - return NULL; -} - - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::NotifyUndoEventListener(IXmlHistoryEventListener::EHistoryEventType event, void* pData) -{ - if (m_pExclusiveListener) - { - m_pExclusiveListener->OnEvent(event, pData); - } - else - { - for (TEventListener::iterator it = m_EventListener.begin(); it != m_EventListener.end(); ++it) - { - (*it)->OnEvent(event, pData); - } - } -} - -///////////////////////////////////////////////////////////////////////////// -int CXmlHistoryManager::IncrementVersion([[maybe_unused]] SXmlHistory* pXmlHistry) -{ - for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it) - { - it->ClearRedo(); - } - return IncrementVersion(); -} - -///////////////////////////////////////////////////////////////////////////// -int CXmlHistoryManager::IncrementVersion() -{ - m_CurrentVersion++; - m_LatestVersion = m_CurrentVersion; - return m_CurrentVersion; -} - -//////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RegisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler, SXmlHistory* pXmlData) -{ - m_UndoEventHandlerMap[ pEventHandler ].CurrentData = pXmlData; -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::UnregisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler) -{ - TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.find(pEventHandler); - if (it != m_UndoEventHandlerMap.end()) - { - m_UndoEventHandlerMap.erase(it); - } -} - -///////////////////////////////////////////////////////////////////////////// -void CXmlHistoryManager::RecordUndoInternal(const char* desc) -{ - TEventHandlerList eventHandler; - for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it) - { - eventHandler.push_back(it->first); - } - RecordNullUndo(eventHandler, desc, false); -} - -///////////////////////////////////////////////////////////////////////////// -bool CXmlHistoryManager::IsEventHandlerValid(IXmlUndoEventHandler* pEventHandler) -{ - for (TInvalidUndoEventListener::iterator it = m_InvalidHandlerMap.begin(); it != m_InvalidHandlerMap.end(); ++it) - { - if (it->second == pEventHandler) - { - return false; - } - } - return true; -} diff --git a/Code/Editor/Util/XmlHistoryManager.h b/Code/Editor/Util/XmlHistoryManager.h deleted file mode 100644 index 176f0a8d83..0000000000 --- a/Code/Editor/Util/XmlHistoryManager.h +++ /dev/null @@ -1,218 +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_UTIL_XMLHISTORYMANAGER_H -#define CRYINCLUDE_EDITOR_UTIL_XMLHISTORYMANAGER_H -#pragma once - - -#include "IXmlHistoryManager.h" - -class CXmlHistoryManager; - -struct SXmlHistory -{ -public: - SXmlHistory(CXmlHistoryManager* pManager, const XmlNodeRef& xmlBaseVersion, uint32 typeId); - - void AddToHistory(const XmlNodeRef& newXmlVersion); - - const XmlNodeRef& Undo(bool* bVersionExist = NULL); - const XmlNodeRef& Redo(); - const XmlNodeRef& GetCurrentVersion(bool* bVersionExist = NULL, int* iVersionNumber = NULL) const; - bool IsModified() const; - uint32 GetTypeId() const {return m_typeId; } - void FlagAsDeleted(); - void FlagAsSaved(); - bool Exist() const; - -private: - friend class CXmlHistoryManager; - - void ClearRedo(); - void ClearHistory(bool flagAsSaved); - -private: - CXmlHistoryManager* m_pManager; - uint32 m_typeId; - int m_DeletedVersion; - int m_SavedVersion; - - typedef std::map< int, XmlNodeRef > TXmlVersionMap; - TXmlVersionMap m_xmlVersionList; -}; - - -struct SXmlHistoryGroup -{ - SXmlHistoryGroup(CXmlHistoryManager* pManager, uint32 typeId); - - SXmlHistory* GetHistory(int index) const; - int GetHistoryCount() const; - - SXmlHistory* GetHistoryByTypeId(uint32 typeId, int index = 0) const; - int GetHistoryCountByTypeId(uint32 typeId) const; - - int CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion); - uint32 GetTypeId() const {return m_typeId; } - - int GetHistoryIndex(const SXmlHistory* pHistory) const; - -private: - friend class CXmlHistoryManager; - CXmlHistoryManager* m_pManager; - uint32 m_typeId; - - typedef std::list< SXmlHistory* > THistoryList; - THistoryList m_List; -}; - -typedef std::map TGroupIndexMap; - - -class CXmlHistoryManager - : public IXmlHistoryManager - , public IXmlUndoEventHandler -{ -public: - CXmlHistoryManager(); - ~CXmlHistoryManager(); - - // Undo/Redo - bool Undo(); - bool Redo(); - bool Goto(int historyNum); - void RecordUndo(IXmlUndoEventHandler* pEventHandler, const char* desc); - void UndoEventHandlerDestroyed(IXmlUndoEventHandler* pEventHandler, uint32 typeId = 0, bool destoryForever = false); - void RestoreUndoEventHandler(IXmlUndoEventHandler* pEventHandler, uint32 typeId); - - void PrepareForNextVersion(); - void RecordNextVersion(SXmlHistory* pHistory, XmlNodeRef newData, const char* undoDesc = NULL); - bool IsPreparedForNextVersion() const {return m_RecordNextVersion; } - - void RegisterEventListener(IXmlHistoryEventListener* pEventListener); - void UnregisterEventListener(IXmlHistoryEventListener* pEventListener); - void SetExclusiveListener(IXmlHistoryEventListener* pEventListener) { m_pExclusiveListener = pEventListener; } - - // History - void ClearHistory(bool flagAsSaved = false); - int GetVersionCount() const { return m_LatestVersion; } - const AZStd::string& GetVersionDesc(int number) const; - int GetCurrentVersionNumber() const { return m_CurrentVersion; } - - // Views - void RegisterView(IXmlHistoryView* pView); - void UnregisterView(IXmlHistoryView* pView); - - // Xml History Groups - SXmlHistoryGroup* CreateXmlGroup(uint32 typeId); - void SetActiveGroup(const SXmlHistoryGroup* pGroup, const char* displayName = NULL, const TGroupIndexMap& groupIndex = TGroupIndexMap(), bool setExternal = false); - const SXmlHistoryGroup* GetActiveGroup() const; - const SXmlHistoryGroup* GetActiveGroup(TGroupIndexMap& currUserIndex /*out*/) const; - void AddXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc = NULL); - void RemoveXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc = NULL); - - void DeleteAll(); - - void FlagHistoryAsSaved(); - - virtual bool SaveToXml(XmlNodeRef& xmlNode); - virtual bool LoadFromXml([[maybe_unused]] const XmlNodeRef& xmlNode) { return false; }; - virtual bool ReloadFromXml([[maybe_unused]] const XmlNodeRef& xmlNode) { return false; }; - -private: - typedef std::list< SXmlHistory > TXmlHistoryList; - TXmlHistoryList m_XmlHistoryList; - int m_CurrentVersion; - int m_LatestVersion; - SXmlHistoryGroup* m_pNullGroup; // hack for unload view ... - XmlNodeRef m_newHistoryData; - bool m_RecordNextVersion; - bool m_bIsActiveGroupEx; - SXmlHistoryGroup* m_pExActiveGroup; - TGroupIndexMap m_ExCurrentIndex; - - typedef std::list< SXmlHistoryGroup > TXmlHistotyGroupList; - TXmlHistotyGroupList m_Groups; - - // event listener - typedef std::list< IXmlHistoryEventListener* > TEventListener; - TEventListener m_EventListener; - IXmlHistoryEventListener* m_pExclusiveListener; - - // views - typedef std::list< IXmlHistoryView* > TViews; - TViews m_Views; - - typedef std::list< const SXmlHistoryGroup* > TXmlHistotyGroupPtrList; - // history - struct SHistoryInfo - { - SHistoryInfo() - : IsNullUndo(false) - , CurrGroup(NULL) - , HistoryInvalidated(false) {} - - const SXmlHistoryGroup* CurrGroup; - TGroupIndexMap CurrUserIndex; - AZStd::string HistoryDescription; - bool IsNullUndo; - bool HistoryInvalidated; - TXmlHistotyGroupPtrList ActiveGroups; - }; - typedef std::map< int, SHistoryInfo > THistoryInfoMap; - THistoryInfoMap m_HistoryInfoMap; - - // undo event handler - typedef std::map< int, SXmlHistory* > THistoryVersionMap; - struct SUndoEventHandlerData - { - SUndoEventHandlerData() - : CurrentData(NULL) {} - - SXmlHistory* CurrentData; - THistoryVersionMap HistoryData; - }; - typedef std::map< IXmlUndoEventHandler*, SUndoEventHandlerData > TUndoEventHandlerMap; - TUndoEventHandlerMap m_UndoEventHandlerMap; - - typedef std::map< IXmlUndoEventHandler*, IXmlHistoryView* > TUndoHandlerViewMap; - TUndoHandlerViewMap m_UndoHandlerViewMap; - - typedef std::map< uint32, IXmlUndoEventHandler* > TInvalidUndoEventListener; - TInvalidUndoEventListener m_InvalidHandlerMap; - -private: - friend struct SXmlHistory; - friend struct SXmlHistoryGroup; - - int IncrementVersion(SXmlHistory* pXmlHistry); - int IncrementVersion(); - SXmlHistory* CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion); - void DeleteXmlHistory(const SXmlHistory* pXmlHistry); - - void RegisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler, SXmlHistory* pXmlData); - void UnregisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler); - typedef std::list< IXmlUndoEventHandler* > TEventHandlerList; - void RecordNullUndo(const TEventHandlerList& eventHandler, const char* desc, bool isNull = true); - void ReloadCurrentVersion(const SXmlHistoryGroup* pPrevGroup, int prevVersion); - SXmlHistory* GetLatestHistory(SUndoEventHandlerData& eventHandlerData); - void NotifyUndoEventListener(IXmlHistoryEventListener::EHistoryEventType event, void* pData = NULL); - - void SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const char* displayName = NULL, bool bRecordNullUndo = false, const TGroupIndexMap& groupIndex = TGroupIndexMap()); - void UnloadInt(); - void ClearRedo(); - - void RecordUndoInternal(const char* desc); - void RemoveListFromList(TXmlHistotyGroupPtrList& list, const TXmlHistotyGroupPtrList& removeList); - - bool IsEventHandlerValid(IXmlUndoEventHandler* pEventHandler); -}; - -#endif // CRYINCLUDE_EDITOR_UTIL_XMLHISTORYMANAGER_H diff --git a/Code/Editor/editor_lib_files.cmake b/Code/Editor/editor_lib_files.cmake index 386b495faa..7f59eed7ae 100644 --- a/Code/Editor/editor_lib_files.cmake +++ b/Code/Editor/editor_lib_files.cmake @@ -498,9 +498,7 @@ set(FILES UndoViewPosition.h UndoViewRotation.h Util/GeometryUtil.h - Util/IXmlHistoryManager.h Util/KDTree.h - Util/XmlHistoryManager.h WipFeaturesDlg.h WipFeaturesDlg.ui WipFeaturesDlg.qrc @@ -737,14 +735,12 @@ set(FILES Util/PredefinedAspectRatios.h Util/StringHelpers.cpp Util/StringHelpers.h - Util/StringNoCasePredicate.h Util/TRefCountBase.h Util/Triangulate.cpp Util/Triangulate.h Util/Util.h Util/XmlArchive.cpp Util/XmlArchive.h - Util/XmlHistoryManager.cpp Util/XmlTemplate.cpp Util/XmlTemplate.h Util/bitarray.h From 0545ce4f59c67fdfb094d5610b66165eacdfe78f Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 12:46:50 -0700 Subject: [PATCH 118/251] More PR comments/fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/ConfigGroup.cpp | 4 ++-- Code/Editor/GameExporter.cpp | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Editor/ConfigGroup.cpp b/Code/Editor/ConfigGroup.cpp index 04c92ff155..d65cbf2c3b 100644 --- a/Code/Editor/ConfigGroup.cpp +++ b/Code/Editor/ConfigGroup.cpp @@ -127,7 +127,7 @@ namespace Config case IConfigVar::eType_STRING: { - AZStd::string currentValue = 0; + AZStd::string currentValue; var->Get(¤tValue); node->setAttr(szName, currentValue.c_str()); break; @@ -186,7 +186,7 @@ namespace Config case IConfigVar::eType_STRING: { - AZStd::string currentValue = 0; + AZStd::string currentValue; var->GetDefault(¤tValue); QString readValue(currentValue.c_str()); if (node->getAttr(szName, readValue)) diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 4c9031f08d..784951cc4d 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -380,12 +380,12 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName // that can later be used for map downloads AZStd::string newpath; - QString filename = levelName; - AZStd::string mapname = (filename + ".dds").toUtf8().data(); - AZStd::string metaname = (filename + ".xml").toUtf8().data(); + AZStd::string filename = levelName.toUtf8().data(); + AZStd::string mapname = (filename + ".dds"); + AZStd::string metaname = (filename + ".xml"); XmlNodeRef rootNode = gEnv->pSystem->CreateXmlNode("download"); - rootNode->setAttr("name", filename.toUtf8().data()); + rootNode->setAttr("name", filename.c_str()); rootNode->setAttr("type", "Map"); XmlNodeRef indexNode = rootNode->newChild("index"); if (indexNode) From aa124347284cfc3b36902719a74d9808cc8948bc Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 12:47:36 -0700 Subject: [PATCH 119/251] removing some dead code, commented code referring old types, static AZStd::strings Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/CryEdit.cpp | 5 ---- Code/Editor/CryEditPy.cpp | 4 ++-- Code/Editor/GenericSelectItemDialog.cpp | 14 ----------- Code/Editor/LogFile.cpp | 3 --- Code/Editor/QtUtil.h | 1 - Code/Editor/Settings.cpp | 16 ------------- Code/Editor/Util/EditorUtils.cpp | 24 ------------------- Code/Editor/Util/PathUtil.cpp | 4 ++-- Code/Legacy/CryCommon/CryTypeInfo.cpp | 3 ++- Code/Legacy/CrySystem/SystemWin32.cpp | 21 +--------------- .../CrySystem/XML/SerializeXMLReader.cpp | 9 ++++--- .../Legacy/CrySystem/XML/SerializeXMLReader.h | 2 +- .../CrySystem/XML/SerializeXMLWriter.cpp | 18 +++++++------- .../Legacy/CrySystem/XML/SerializeXMLWriter.h | 8 +++---- Code/Legacy/CrySystem/XML/XMLBinaryNode.h | 2 -- .../DataTypes/Rules/IMeshAdvancedRule.h | 3 ++- .../SceneData/GraphData/MaterialData.cpp | 8 +++---- .../SceneData/GraphData/MaterialData.h | 8 +++---- .../Code/Source/Editor/EditorCommon.cpp | 8 +++---- .../Source/OpenGLRender/GLWidget.cpp | 3 +-- 20 files changed, 39 insertions(+), 125 deletions(-) diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index b69bfa78f3..3673367c12 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -1883,11 +1883,6 @@ void CCryEditApp::UnregisterEventLoopHook(IEventLoopHook* pHookToRemove) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::LoadFile(QString fileName) { - //CEditCommandLineInfo cmdLine; - //ProcessCommandLine(cmdinfo); - - //bool bBuilding = false; - //CString file = cmdLine.SpanExcluding() if (GetIEditor()->GetViewManager()->GetViewCount() == 0) { return; diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp index 6abaf933fe..7e07d5553d 100644 --- a/Code/Editor/CryEditPy.cpp +++ b/Code/Editor/CryEditPy.cpp @@ -210,7 +210,7 @@ namespace const char* PyGetCurrentLevelName() { // Using static member to capture temporary data - static AZStd::string tempLevelName; + static AZStd::fixed_string tempLevelName; tempLevelName = GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().data(); return tempLevelName.c_str(); } @@ -218,7 +218,7 @@ namespace const char* PyGetCurrentLevelPath() { // Using static member to capture temporary data - static AZStd::string tempLevelPath; + static AZStd::fixed_string tempLevelPath; tempLevelPath = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data(); return tempLevelPath.c_str(); } diff --git a/Code/Editor/GenericSelectItemDialog.cpp b/Code/Editor/GenericSelectItemDialog.cpp index ef109336ef..59c7986a68 100644 --- a/Code/Editor/GenericSelectItemDialog.cpp +++ b/Code/Editor/GenericSelectItemDialog.cpp @@ -91,20 +91,6 @@ void CGenericSelectItemDialog::ReloadTree() QTreeWidgetItem* hSelected = nullptr; - /* - std::vector::const_iterator iter = m_items.begin(); - while (iter != m_items.end()) - { - const CString& itemName = *iter; - HTREEITEM hItem = m_tree.InsertItem(itemName, 0, 0, TVI_ROOT, TVI_SORT); - if (!m_preselect.IsEmpty() && m_preselect.CompareNoCase(itemName) == 0) - { - hSelected = hItem; - } - ++iter; - } - */ - std::map items; QRegularExpression sep(QStringLiteral("[\\/.") + m_treeSeparator + QStringLiteral("]+")); diff --git a/Code/Editor/LogFile.cpp b/Code/Editor/LogFile.cpp index 76c6f34181..56e91a6806 100644 --- a/Code/Editor/LogFile.cpp +++ b/Code/Editor/LogFile.cpp @@ -572,9 +572,6 @@ void CLogFile::OnWriteToConsole(const char* sText, bool bNewLine) } if (bNewLine) { - //str = CString("\r\n") + str.TrimLeft(); - //str = CString("\r\n") + str; - //str = CString("\r") + str; str = QString("\r\n") + str; str = str.trimmed(); } diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h index a9aaadc491..380f4dfa4a 100644 --- a/Code/Editor/QtUtil.h +++ b/Code/Editor/QtUtil.h @@ -34,7 +34,6 @@ public: namespace QtUtil { - // Replacement for CString::trimRight() inline QString trimRight(const QString& str) { // We prepend a char, so that the left doesn't get trimmed, then we remove it after trimming diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp index 8f86c74b25..ae4fa75d41 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -656,22 +656,6 @@ void SEditorSettings::Save() ////////////////////////////////////////////////////////////////////////// SaveValue("Settings\\Slices", "DynamicByDefault", sliceSettings.dynamicByDefault); - /* - ////////////////////////////////////////////////////////////////////////// - // Save paths. - ////////////////////////////////////////////////////////////////////////// - for (int id = 0; id < EDITOR_PATH_LAST; id++) - { - for (int i = 0; i < searchPaths[id].size(); i++) - { - CString path = searchPaths[id][i]; - CString key; - key.Format( "Paths","Path_%.2d_%.2d",id,i ); - SaveValue( "Paths",key,path ); - } - } - */ - s_editorSettings()->sync(); // --- Settings Registry values diff --git a/Code/Editor/Util/EditorUtils.cpp b/Code/Editor/Util/EditorUtils.cpp index 8f56e4d956..9f42a5da83 100644 --- a/Code/Editor/Util/EditorUtils.cpp +++ b/Code/Editor/Util/EditorUtils.cpp @@ -30,30 +30,6 @@ void HeapCheck::Check([[maybe_unused]] const char* file, [[maybe_unused]] int li _ASSERTE(_CrtCheckMemory()); #endif - /* - int heapstatus = _heapchk(); - switch( heapstatus ) - { - case _HEAPOK: - break; - case _HEAPEMPTY: - break; - case _HEAPBADBEGIN: - { - CString str; - str.Format( "Bad Start of Heap, at file %s line:%d",file,line ); - MessageBox( NULL,str,"Heap Check",MB_OK ); - } - break; - case _HEAPBADNODE: - { - CString str; - str.Format( "Bad Node in Heap, at file %s line:%d",file,line ); - MessageBox( NULL,str,"Heap Check",MB_OK ); - } - break; - } - */ #endif } diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp index 2f99f42188..22c638e289 100644 --- a/Code/Editor/Util/PathUtil.cpp +++ b/Code/Editor/Util/PathUtil.cpp @@ -245,8 +245,8 @@ namespace Path /// Get the data folder AZStd::string GetEditingGameDataFolder() { - static AZStd::string s_currentModName; - // query the editor root. The bus exists in case we want tools to be able to override this. + // Define here the mod name + static AZStd::fixed_string s_currentModName; if (s_currentModName.empty()) { diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp index ffadc732b0..5f0cb47b63 100644 --- a/Code/Legacy/CryCommon/CryTypeInfo.cpp +++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp @@ -131,7 +131,8 @@ const CTypeInfo&PtrTypeInfo() // bool AZStd::string ToString(bool const& val) { - static AZStd::string sTrue = "true", sFalse = "false"; + static AZStd::fixed_string sTrue = "true"; + static AZStd::fixed_string sFalse = "false"; return val ? sTrue : sFalse; } diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index 66be2a2ca5..b114c9bf12 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -173,7 +173,7 @@ int CSystem::GetApplicationInstance() AZStd::wstring suffix; for (int instance = 0;; ++instance) { - suffix = AZStd::wstring::format(L"LumberyardApplication(%d)", instance); + suffix = AZStd::wstring::format(L"O3DEApplication(%d)", instance); CreateMutexW(NULL, TRUE, suffix.c_str()); // search for duplicates @@ -222,25 +222,6 @@ struct CryDbgModule }; #ifdef WIN32 -////////////////////////////////////////////////////////////////////////// -class CStringOrder -{ -public: - bool operator () (const char* szLeft, const char* szRight) const {return azstricmp(szLeft, szRight) < 0; } -}; -typedef std::map StringToSizeMap; -void AddSize (StringToSizeMap& mapSS, const char* szString, unsigned nSize) -{ - StringToSizeMap::iterator it = mapSS.find (szString); - if (it == mapSS.end()) - { - mapSS.insert (StringToSizeMap::value_type(szString, nSize)); - } - else - { - it->second += nSize; - } -} ////////////////////////////////////////////////////////////////////////// const char* GetModuleGroup (const char* szString) diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp index 55fab84286..e74b457191 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp @@ -15,7 +15,7 @@ #define TAG_SCRIPT_TYPE "t" #define TAG_SCRIPT_NAME "n" -//#define LOG_SERIALIZE_STACK(tag,szName) CryLogAlways( "<%s> %s/%s",tag,GetStackInfo(),szName ); +//#define LOG_SERIALIZE_STACK(tag,szName) CryLogAlways( "<%s> %s/%s",tag,GetStackInfo().c_str(), szName); #define LOG_SERIALIZE_STACK(tag, szName) CSerializeXMLReaderImpl::CSerializeXMLReaderImpl(const XmlNodeRef& nodeRef) @@ -175,10 +175,9 @@ void CSerializeXMLReaderImpl::EndGroup() } ////////////////////////////////////////////////////////////////////////// -const char* CSerializeXMLReaderImpl::GetStackInfo() const +AZStd::string CSerializeXMLReaderImpl::GetStackInfo() const { - static AZStd::string str; - str.assign(""); + AZStd::string str; for (int i = 0; i < (int)m_nodeStack.size(); i++) { const char* name = m_nodeStack[i].m_node->getAttr(TAG_SCRIPT_NAME); @@ -195,7 +194,7 @@ const char* CSerializeXMLReaderImpl::GetStackInfo() const str += "/"; } } - return str.c_str(); + return str; } void CSerializeXMLReaderImpl::GetMemoryUsage(ICrySizer* pSizer) const diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h index 177db0ffaa..f87350d3fe 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h @@ -88,7 +88,7 @@ public: void BeginGroup(const char* szName); bool BeginOptionalGroup(const char* szName, bool condition); void EndGroup(); - const char* GetStackInfo() const; + AZStd::string GetStackInfo() const; void GetMemoryUsage(ICrySizer* pSizer) const; diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp index 26007eb229..ce3fbcc2b1 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp +++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp @@ -64,14 +64,14 @@ void CSerializeXMLWriterImpl::BeginGroup(const char* szName) if (strchr(szName, ' ') != 0) { assert(0 && "Spaces in group name not supported"); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in group name not supported: %s/%s", GetStackInfo(), szName); + CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in group name not supported: %s/%s", GetStackInfo().c_str(), szName); } XmlNodeRef node = CreateNodeNamed(szName); CurNode()->addChild(node); m_nodeStack.push_back(node); if (m_nodeStack.size() > MAX_NODE_STACK_DEPTH) { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Too Deep Node Stack:\r\n%s", GetStackInfo()); + CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Too Deep Node Stack:\r\n%s", GetStackInfo().c_str()); } } @@ -112,10 +112,9 @@ void CSerializeXMLWriterImpl::GetMemoryUsage(ICrySizer* pSizer) const } ////////////////////////////////////////////////////////////////////////// -const char* CSerializeXMLWriterImpl::GetStackInfo() const +AZStd::string CSerializeXMLWriterImpl::GetStackInfo() const { - static AZStd::string str; - str.assign(""); + AZStd::string str; for (int i = 0; i < (int)m_nodeStack.size(); i++) { const char* name = m_nodeStack[i]->getAttr(TAG_SCRIPT_NAME); @@ -132,14 +131,13 @@ const char* CSerializeXMLWriterImpl::GetStackInfo() const str += "/"; } } - return str.c_str(); + return str; } ////////////////////////////////////////////////////////////////////////// -const char* CSerializeXMLWriterImpl::GetLuaStackInfo() const +AZStd::string CSerializeXMLWriterImpl::GetLuaStackInfo() const { - static AZStd::string str; - str.assign(""); + AZStd::string str; for (int i = 0; i < (int)m_luaSaveStack.size(); i++) { const char* name = m_luaSaveStack[i]; @@ -149,5 +147,5 @@ const char* CSerializeXMLWriterImpl::GetLuaStackInfo() const str += "."; } } - return str.c_str(); + return str; } diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h index 41dbe3dd7b..5f3e9f2c53 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h +++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h @@ -77,7 +77,7 @@ private: if (strchr(name, ' ') != 0) { assert(0 && "Spaces in Value name not supported"); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in Value name not supported: %s in Group %s", name, GetStackInfo()); + CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in Value name not supported: %s in Group %s", name, GetStackInfo().c_str()); return; } if (GetISystem()->IsDevMode() && CurNode()) @@ -86,7 +86,7 @@ private: if (CurNode()->haveAttr(name)) { assert(0); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Duplicate tag Value( \"%s\" ) in Group %s", name, GetStackInfo()); + CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Duplicate tag Value( \"%s\" ) in Group %s", name, GetStackInfo().c_str()); } } @@ -115,8 +115,8 @@ private: } // Used for printing currebnt stack info for warnings. - const char* GetStackInfo() const; - const char* GetLuaStackInfo() const; + AZStd::string GetStackInfo() const; + AZStd::string GetLuaStackInfo() const; ////////////////////////////////////////////////////////////////////////// // Check For Defaults. diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryNode.h b/Code/Legacy/CrySystem/XML/XMLBinaryNode.h index cd9ce04e6c..34e0ca22ce 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryNode.h +++ b/Code/Legacy/CrySystem/XML/XMLBinaryNode.h @@ -189,8 +189,6 @@ public: bool getAttr(const char* key, Vec3d& value) const; bool getAttr(const char* key, Quat& value) const; bool getAttr(const char* key, ColorB& value) const; - // bool getAttr( const char *key,CString &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; } - private: ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h index d3b31913dd..b759fea158 100644 --- a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h +++ b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h @@ -18,7 +18,8 @@ namespace AZ { namespace DataTypes { - const static AZStd::string s_advancedDisabledString = "Disabled"; + const static AZStd::fixed_string s_advancedDisabledString = "Disabled"; + class IMeshAdvancedRule : public IRule { diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp index cf0f0a6f56..e41e39dd0a 100644 --- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp +++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp @@ -18,10 +18,10 @@ namespace AZ { namespace DataTypes = AZ::SceneAPI::DataTypes; - const AZStd::string MaterialData::s_DiffuseMapName = "Diffuse"; - const AZStd::string MaterialData::s_SpecularMapName = "Specular"; - const AZStd::string MaterialData::s_BumpMapName = "Bump"; - const AZStd::string MaterialData::s_emptyString = ""; + const AZStd::fixed_string<8> MaterialData::s_DiffuseMapName = "Diffuse"; + const AZStd::fixed_string<9> MaterialData::s_SpecularMapName = "Specular"; + const AZStd::fixed_string<5> MaterialData::s_BumpMapName = "Bump"; + const AZStd::fixed_string<1> MaterialData::s_emptyString = ""; MaterialData::MaterialData() : m_isNoDraw(false) diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h index 8cc9de8352..8c8f8bd66e 100644 --- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h +++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h @@ -96,10 +96,10 @@ namespace AZ bool m_isNoDraw; - const static AZStd::string s_DiffuseMapName; - const static AZStd::string s_SpecularMapName; - const static AZStd::string s_BumpMapName; - const static AZStd::string s_emptyString; + const static AZStd::fixed_string<8> s_DiffuseMapName; + const static AZStd::fixed_string<9> s_SpecularMapName; + const static AZStd::fixed_string<5> s_BumpMapName; + const static AZStd::fixed_string<1> s_emptyString; // A unique id which is used to identify a material in a fbx. // This is the same as the ID in the fbx file's FbxNode diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp index 9938d55502..8ce8b2d487 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp @@ -57,10 +57,10 @@ namespace ImageProcessingAtomEditor static double mb = kb * 1024.0; static double gb = mb * 1024.0; - static AZStd::string byteStr = "B"; - static AZStd::string kbStr = "KB"; - static AZStd::string mbStr = "MB"; - static AZStd::string gbStr = "GB"; + static AZStd::fixed_string<2> byteStr = "B"; + static AZStd::fixed_string<3> kbStr = "KB"; + static AZStd::fixed_string<3> mbStr = "MB"; + static AZStd::fixed_string<3> gbStr = "GB"; #if AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX kb = 1000.0; 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..cfdcd704c5 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 @@ -284,8 +284,7 @@ namespace EMStudio fpsNumFrames = 0; } - static AZStd::string perfTempString; - perfTempString = AZStd::string::format("%d FPS (%.1f ms)", lastFPS, renderTime); + const AZStd::string perfTempString = AZStd::string::format("%d FPS (%.1f ms)", lastFPS, renderTime); // initialize the painter and get the font metrics //painter.setBrush( Qt::NoBrush ); From b521113fe1f51416a35ee28226e9cc2b521c1743 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 15:10:13 -0500 Subject: [PATCH 120/251] SMC fix Signed-off-by: Dayo Lawal --- .../Code/Source/ShaderManagementConsoleApplication.h | 1 - 1 file changed, 1 deletion(-) diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index 206b5cc94f..7a3a422dc9 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -29,7 +29,6 @@ namespace ShaderManagementConsole // AzFramework::Application void CreateStaticModules(AZStd::vector& outModules) override; const char* GetCurrentConfigurationName() const override; - void Stop() override; private: void ProcessCommandLine(const AZ::CommandLine& commandLine); From e8d685211b684fa5bd332515fe72ce5604d3b826 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 16:24:49 -0500 Subject: [PATCH 121/251] CreateMenu/CreateTabBar Signed-off-by: Dayo Lawal --- .../Window/AtomToolsMainWindow.h | 6 ++-- .../Source/Window/AtomToolsMainWindow.cpp | 36 ++++++------------- .../Source/Window/MaterialEditorWindow.cpp | 30 ++++++++++++---- .../Code/Source/Window/MaterialEditorWindow.h | 5 +-- .../Window/ShaderManagementConsoleWindow.cpp | 30 ++++++++++++---- .../Window/ShaderManagementConsoleWindow.h | 5 +-- 6 files changed, 64 insertions(+), 48 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h index f3271123b0..141fa1cad2 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -38,9 +38,9 @@ namespace AtomToolsFramework bool IsDockWidgetVisible(const AZStd::string& name) const override; AZStd::vector GetDockWidgetNames() const override; - virtual void SetupMenu(); + virtual void CreateMenu(); - virtual void SetupTabs(); + virtual void CreateTabBar(); virtual void AddTabForDocumentId(const AZ::Uuid& documentId); virtual void RemoveTabForDocumentId(const AZ::Uuid& documentId); virtual void UpdateTabForDocumentId(const AZ::Uuid& documentId); @@ -57,7 +57,5 @@ namespace AtomToolsFramework QStatusBar* m_statusBar = nullptr; AZStd::unordered_map m_dockWidgets; - - QMenu* m_menuFile = {}; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp index ffc618c574..cafaff339e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -21,16 +21,6 @@ namespace AtomToolsFramework setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); - m_menuBar = new QMenuBar(this); - m_menuBar->setObjectName("MenuBar"); - setMenuBar(m_menuBar); - - 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_statusBar = new QStatusBar(this); m_statusBar->setObjectName("StatusBar"); statusBar()->addPermanentWidget(m_statusBar, 1); @@ -110,26 +100,20 @@ namespace AtomToolsFramework return names; } - void AtomToolsMainWindow::SetupMenu() + void AtomToolsMainWindow::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"); + m_menuBar = new QMenuBar(this); + m_menuBar->setObjectName("MenuBar"); + setMenuBar(m_menuBar); } - void AtomToolsMainWindow::SetupTabs() + void AtomToolsMainWindow::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(); - }); + 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); } void AtomToolsMainWindow::AddTabForDocumentId(const AZ::Uuid& documentId) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 8367f30680..788680a227 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -93,6 +93,9 @@ namespace MaterialEditor 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); @@ -101,9 +104,6 @@ namespace MaterialEditor m_centralWidget->setLayout(vl); setCentralWidget(m_centralWidget); - 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); @@ -283,9 +283,12 @@ namespace MaterialEditor m_statusBar->setWindowIconText(QString("%1").arg(status)); } - void MaterialEditorWindow::SetupMenu() + void MaterialEditorWindow::CreateMenu() { - Base::SetupMenu(); + 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"); m_actionNew = m_menuFile->addAction("&New...", [this]() { CreateMaterialDialog createDialog(this); @@ -481,9 +484,22 @@ namespace MaterialEditor }); } - void MaterialEditorWindow::SetupTabs() + void MaterialEditorWindow::CreateTabBar() { - Base::SetupTabs(); + Base::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(); + }); // 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 diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index d865f1170d..e066d0f78a 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -68,9 +68,9 @@ namespace MaterialEditor void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override; void OnDocumentSaved(const AZ::Uuid& documentId) override; - void SetupMenu() override; + void CreateMenu() override; - void SetupTabs() override; + void CreateTabBar() override; void AddTabForDocumentId(const AZ::Uuid& documentId) override; void UpdateTabForDocumentId(const AZ::Uuid& documentId) override; QString GetDocumentPath(const AZ::Uuid& documentId) const; @@ -82,6 +82,7 @@ namespace MaterialEditor MaterialViewportWidget* m_materialViewport = nullptr; MaterialEditorToolBar* m_toolBar = nullptr; + QMenu* m_menuFile = {}; QAction* m_actionNew = {}; QAction* m_actionOpen = {}; QAction* m_actionOpenRecent = {}; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 24acf1eb89..7874fcb2dc 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -49,6 +49,9 @@ namespace ShaderManagementConsole m_toolBar->setObjectName("ToolBar"); addToolBar(m_toolBar); + CreateMenu(); + CreateTabBar(); + QVBoxLayout* vl = new QVBoxLayout(m_centralWidget); vl->setMargin(0); vl->setContentsMargins(0, 0, 0, 0); @@ -56,9 +59,6 @@ namespace ShaderManagementConsole m_centralWidget->setLayout(vl); setCentralWidget(m_centralWidget); - SetupMenu(); - SetupTabs(); - AddDockWidget("Asset Browser", new ShaderManagementConsoleBrowserWidget, Qt::BottomDockWidgetArea, Qt::Vertical); AddDockWidget("Python Terminal", new AzToolsFramework::CScriptTermDialog, Qt::BottomDockWidgetArea, Qt::Horizontal); @@ -159,9 +159,12 @@ namespace ShaderManagementConsole UpdateTabForDocumentId(documentId); } - void ShaderManagementConsoleWindow::SetupMenu() + void ShaderManagementConsoleWindow::CreateMenu() { - Base::SetupMenu(); + 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"); m_actionOpen = m_menuFile->addAction("&Open...", [this]() { const AZStd::vector assetTypes = { @@ -277,9 +280,22 @@ namespace ShaderManagementConsole }); } - void ShaderManagementConsoleWindow::SetupTabs() + void ShaderManagementConsoleWindow::CreateTabBar() { - Base::SetupTabs(); + Base::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(); + }); // 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 diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index 127a777ddd..3b529a52b3 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -63,9 +63,9 @@ namespace ShaderManagementConsole void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override; void OnDocumentSaved(const AZ::Uuid& documentId) override; - void SetupMenu() override; + void CreateMenu() override; - void SetupTabs() override; + void CreateTabBar() override; void AddTabForDocumentId(const AZ::Uuid& documentId) override; void UpdateTabForDocumentId(const AZ::Uuid& documentId) override; @@ -81,6 +81,7 @@ namespace ShaderManagementConsole ShaderManagementConsoleToolBar* m_toolBar = nullptr; + QMenu* m_menuFile = {}; QMenu* m_menuNew = {}; QAction* m_actionOpen = {}; QAction* m_actionOpenRecent = {}; From 0dc829891a29addd0a74f0ee0d46085ebc57f769 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 14:30:04 -0700 Subject: [PATCH 122/251] fixing build Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Util/PathUtil.cpp | 2 +- Code/Legacy/CryCommon/CryTypeInfo.cpp | 7 ++++--- .../SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h | 3 ++- Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp | 7 +------ Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h | 6 ++---- 5 files changed, 10 insertions(+), 15 deletions(-) diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp index 22c638e289..3ca4b6222c 100644 --- a/Code/Editor/Util/PathUtil.cpp +++ b/Code/Editor/Util/PathUtil.cpp @@ -254,7 +254,7 @@ namespace Path } AZStd::string str(GetGameAssetsFolder()); str += "Mods\\"; - str += s_currentModName; + str += s_currentModName.c_str(); return str; } diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp index 5f0cb47b63..b1f7f20601 100644 --- a/Code/Legacy/CryCommon/CryTypeInfo.cpp +++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp @@ -16,6 +16,7 @@ #include "CrySizer.h" #include "CryEndian.h" #include "TypeInfo_impl.h" +#include // Traits #if defined(AZ_RESTRICTED_PLATFORM) @@ -131,9 +132,9 @@ const CTypeInfo&PtrTypeInfo() // bool AZStd::string ToString(bool const& val) { - static AZStd::fixed_string sTrue = "true"; - static AZStd::fixed_string sFalse = "false"; - return val ? sTrue : sFalse; + static AZStd::fixed_string<5> sTrue = "true"; + static AZStd::fixed_string<6> sFalse = "false"; + return val ? sTrue.c_str() : sFalse.c_str(); } bool FromString(bool& val, cstr s) diff --git a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h index b759fea158..48310091b3 100644 --- a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h +++ b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace AZ { @@ -18,7 +19,7 @@ namespace AZ { namespace DataTypes { - const static AZStd::fixed_string s_advancedDisabledString = "Disabled"; + static AZStd::string s_advancedDisabledString = "Disabled"; class IMeshAdvancedRule : public IRule diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp index e41e39dd0a..d58a89a110 100644 --- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp +++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp @@ -18,11 +18,6 @@ namespace AZ { namespace DataTypes = AZ::SceneAPI::DataTypes; - const AZStd::fixed_string<8> MaterialData::s_DiffuseMapName = "Diffuse"; - const AZStd::fixed_string<9> MaterialData::s_SpecularMapName = "Specular"; - const AZStd::fixed_string<5> MaterialData::s_BumpMapName = "Bump"; - const AZStd::fixed_string<1> MaterialData::s_emptyString = ""; - MaterialData::MaterialData() : m_isNoDraw(false) , m_diffuseColor(AZ::Vector3::CreateOne()) @@ -72,7 +67,7 @@ namespace AZ return result->second; } - return s_emptyString; + return m_emptyString; } void MaterialData::SetNoDraw(bool isNoDraw) diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h index 8c8f8bd66e..2a83a53c53 100644 --- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h +++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace AZ { @@ -96,10 +97,7 @@ namespace AZ bool m_isNoDraw; - const static AZStd::fixed_string<8> s_DiffuseMapName; - const static AZStd::fixed_string<9> s_SpecularMapName; - const static AZStd::fixed_string<5> s_BumpMapName; - const static AZStd::fixed_string<1> s_emptyString; + const AZStd::string m_emptyString; // A unique id which is used to identify a material in a fbx. // This is the same as the ID in the fbx file's FbxNode From e50723625729df1ebc4608d22129feb105c4ecdc Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 17:59:00 -0500 Subject: [PATCH 123/251] Addressing requests Signed-off-by: Dayo Lawal --- .../Application/AtomToolsApplication.cpp | 2 +- .../Source/Window/AtomToolsMainWindow.cpp | 19 ++++++++++- .../Code/Source/MaterialEditorApplication.cpp | 2 +- .../Source/Window/MaterialEditorWindow.cpp | 13 ------- .../Code/Source/Window/MaterialEditorWindow.h | 11 +----- .../Window/MaterialEditorWindowComponent.cpp | 34 ++++++++----------- .../Code/materialeditorwindow_files.cmake | 3 -- .../ShaderManagementConsoleApplication.cpp | 2 +- .../Window/ShaderManagementConsoleWindow.cpp | 13 ------- .../Window/ShaderManagementConsoleWindow.h | 7 ---- ...ShaderManagementConsoleWindowComponent.cpp | 12 +++---- 11 files changed, 42 insertions(+), 76 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index 25ef43cfa4..aedad7706b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -476,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 index cafaff339e..af4c3571e7 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -25,6 +25,8 @@ namespace AtomToolsFramework m_statusBar->setObjectName("StatusBar"); statusBar()->addPermanentWidget(m_statusBar, 1); + m_centralWidget = new QWidget(this); + AtomToolsMainWindowRequestBus::Handler::BusConnect(); } @@ -109,11 +111,26 @@ namespace AtomToolsFramework void AtomToolsMainWindow::CreateTabBar() { - 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); + + // 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) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 0c1cff334c..7b90be2dd1 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -38,8 +38,8 @@ #include #include -#include #include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 788680a227..8d89e7442e 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -488,19 +488,6 @@ namespace MaterialEditor { Base::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(); - }); - // 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 // This should automatically clear the active document diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index e066d0f78a..d789e1d839 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -14,18 +14,9 @@ #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 r> AZ_POP_DISABLE_WARNING #endif diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 33987df5b6..4135ec66b4 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -6,7 +6,8 @@ * */ -#include +#include +#include #include #include #include @@ -17,14 +18,9 @@ #include #include #include -#include - namespace MaterialEditor { - using FactoryRequestBus = AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus; - using RequestBus = AtomToolsFramework::AtomToolsMainWindowRequestBus; - void MaterialEditorWindowComponent::Reflect(AZ::ReflectContext* context) { MaterialEditorWindowSettings::Reflect(context); @@ -37,25 +33,25 @@ namespace MaterialEditor if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("MaterialEditorWindowFactoryRequestBus") + behaviorContext->EBus("MaterialEditorWindowAtomToolsFramework::AtomToolsMainWindowFactoryRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "materialeditor") - ->Event("CreateMaterialEditorWindow", &FactoryRequestBus::Events::CreateMainWindow) - ->Event("DestroyMaterialEditorWindow", &FactoryRequestBus::Events::DestroyMainWindow) + ->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", &RequestBus::Events::ActivateWindow) - ->Event("SetDockWidgetVisible", &RequestBus::Events::SetDockWidgetVisible) - ->Event("IsDockWidgetVisible", &RequestBus::Events::IsDockWidgetVisible) - ->Event("GetDockWidgetNames", &RequestBus::Events::GetDockWidgetNames) - ->Event("ResizeViewportRenderTarget", &RequestBus::Events::ResizeViewportRenderTarget) - ->Event("LockViewportRenderTargetSize", &RequestBus::Events::LockViewportRenderTargetSize) - ->Event("UnlockViewportRenderTargetSize", &RequestBus::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) ; } } @@ -84,13 +80,13 @@ namespace MaterialEditor void MaterialEditorWindowComponent::Activate() { AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - FactoryRequestBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusConnect(); AzToolsFramework::SourceControlConnectionRequestBus::Broadcast(&AzToolsFramework::SourceControlConnectionRequests::EnableSourceControl, true); } void MaterialEditorWindowComponent::Deactivate() { - FactoryRequestBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); m_window.reset(); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake index 6294adad88..b814ad3f47 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake @@ -39,9 +39,6 @@ set(FILES Source/Window/PerformanceMonitor/PerformanceMonitorWidget.cpp Source/Window/PerformanceMonitor/PerformanceMonitorWidget.h Source/Window/PerformanceMonitor/PerformanceMonitorWidget.ui - Source/Window/StatusBar/StatusBarWidget.cpp - Source/Window/StatusBar/StatusBarWidget.h - Source/Window/StatusBar/StatusBarWidget.ui Source/Window/ToolBar/MaterialEditorToolBar.h Source/Window/ToolBar/MaterialEditorToolBar.cpp Source/Window/ToolBar/ModelPresetComboBox.h diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp index 37e617fda2..876f58e8d5 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -36,7 +36,7 @@ #include #include -#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 7874fcb2dc..0a7ce6dd59 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -284,19 +284,6 @@ namespace ShaderManagementConsole { Base::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(); - }); - // 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 // This should automatically clear the active document diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index 3b529a52b3..f1c74a1f48 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -17,17 +17,10 @@ #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 diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp index e9dda40a50..44715ef64f 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp @@ -34,8 +34,6 @@ AZ_POP_DISABLE_WARNING namespace ShaderManagementConsole { - using FactoryRequestBus = AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus; - void ShaderManagementConsoleWindowComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serialize = azrtti_cast(context)) @@ -46,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", &FactoryRequestBus::Events::CreateMainWindow) - ->Event("DestroyShaderManagementConsoleWindow", &FactoryRequestBus::Events::DestroyMainWindow) + ->Event("CreateShaderManagementConsoleWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::CreateMainWindow) + ->Event("DestroyShaderManagementConsoleWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::DestroyMainWindow) ; behaviorContext->EBus("ShaderManagementConsoleRequestBus") @@ -89,7 +87,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::Activate() { AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - FactoryRequestBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusConnect(); ShaderManagementConsoleRequestBus::Handler::BusConnect(); AzToolsFramework::SourceControlConnectionRequestBus::Broadcast(&AzToolsFramework::SourceControlConnectionRequests::EnableSourceControl, true); } @@ -97,7 +95,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::Deactivate() { ShaderManagementConsoleRequestBus::Handler::BusDisconnect(); - FactoryRequestBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); m_window.reset(); From 32ba658e5eb4b2ea8b1bfcd635bcf8351dfe8794 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 18:35:54 -0500 Subject: [PATCH 124/251] Typo fix Signed-off-by: Dayo Lawal --- .../Code/Source/MaterialEditorApplication.cpp | 7 +------ .../MaterialEditor/Code/Source/MaterialEditorApplication.h | 2 -- .../Code/Source/Window/MaterialEditorWindowComponent.cpp | 2 +- .../Code/Source/ShaderManagementConsoleApplication.cpp | 5 ----- .../Code/Source/ShaderManagementConsoleApplication.h | 2 -- 5 files changed, 2 insertions(+), 16 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 7b90be2dd1..e12bc2409a 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -41,14 +41,9 @@ #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) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h index f65f719caa..164fb9d920 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -11,8 +11,6 @@ #include #include -#include - namespace MaterialEditor { class MaterialThumbnailRenderer; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 4135ec66b4..8406ae891f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -33,7 +33,7 @@ namespace MaterialEditor if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("MaterialEditorWindowAtomToolsFramework::AtomToolsMainWindowFactoryRequestBus") + 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") diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp index 876f58e8d5..2a5cd1430a 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -38,11 +38,6 @@ #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" diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index 7a3a422dc9..0714ec17bc 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -11,8 +11,6 @@ #include #include -#include - namespace ShaderManagementConsole { class ShaderManagementConsoleApplication From cb5e2c71ffc59725ade56af09a5f27fd5d81ad34 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 19:08:45 -0500 Subject: [PATCH 125/251] Typo fix2 Signed-off-by: Dayo Lawal --- .../MaterialEditor/Code/Source/Window/MaterialEditorWindow.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index d789e1d839..9eb8edbff3 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -16,7 +16,7 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include #include -#include r> +#include AZ_POP_DISABLE_WARNING #endif From 3a76f2e6ce08ae736498852cc5d0d61654ddc781 Mon Sep 17 00:00:00 2001 From: evanchia Date: Thu, 5 Aug 2021 17:41:06 -0700 Subject: [PATCH 126/251] Fixing incorrect string replacement in Jenkinsfile Signed-off-by: evanchia --- scripts/build/Jenkins/Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 517fa1136d..d71d9964d9 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}.replace('%','%%')" + "${cmakeBuildDir} ${branchName} %BUILD_NUMBER% AR ${configuration} ${repoName} --url ${env.BUILD_URL.replace('%','%%')}" bat label: "Publishing ${buildJobName} Test Metrics", script: command } From 44a007547c1bf4a097cbeae55d7785b65a248106 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 5 Aug 2021 19:55:56 -0500 Subject: [PATCH 127/251] minor reformatting and removed unused headers from ME/SMCApplication.* Signed-off-by: Guthrie Adams --- .../Code/Source/MaterialEditorApplication.cpp | 29 +------------------ .../Code/Source/MaterialEditorApplication.h | 2 +- .../ShaderManagementConsoleApplication.cpp | 27 +---------------- .../ShaderManagementConsoleApplication.h | 2 +- 4 files changed, 4 insertions(+), 56 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index e12bc2409a..6f9d5aca41 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -6,40 +6,13 @@ * */ -#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 namespace MaterialEditor { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h index 164fb9d920..da691feff7 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -34,5 +34,5 @@ namespace MaterialEditor void ProcessCommandLine(const AZ::CommandLine& commandLine) override; AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; - }; + }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp index 2a5cd1430a..313522a256 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -8,35 +8,10 @@ #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 namespace ShaderManagementConsole { diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index 0714ec17bc..24b2020dad 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -32,5 +32,5 @@ namespace ShaderManagementConsole void ProcessCommandLine(const AZ::CommandLine& commandLine); AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; - }; + }; } // namespace ShaderManagementConsole From 782e8465a48b37221a171881062430cab1884d44 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 5 Aug 2021 20:05:01 -0500 Subject: [PATCH 128/251] removed StatusBarWidget class references Signed-off-by: Guthrie Adams --- .../Code/Source/Window/MaterialEditorWindow.h | 1 - .../Window/StatusBar/StatusBarWidget.cpp | 37 --------- .../Source/Window/StatusBar/StatusBarWidget.h | 42 ---------- .../Window/StatusBar/StatusBarWidget.ui | 82 ------------------- 4 files changed, 162 deletions(-) delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.cpp delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.h delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.ui diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 9eb8edbff3..5ecff06bc7 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -15,7 +15,6 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include -#include #include AZ_POP_DISABLE_WARNING #endif 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 - - - - - - - - - - - From d6f08151cc721bc4ba3ab9997719bd0b6ca735e5 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 5 Aug 2021 20:56:46 -0500 Subject: [PATCH 129/251] removed unused headers and forwards Signed-off-by: Guthrie Adams --- .../Code/Source/MaterialEditorApplication.cpp | 2 +- .../Source/Window/MaterialEditorWindow.cpp | 22 ++++---------- .../Code/Source/Window/MaterialEditorWindow.h | 7 +---- .../Window/ShaderManagementConsoleWindow.cpp | 29 ++++++++----------- .../Window/ShaderManagementConsoleWindow.h | 10 ++----- 5 files changed, 21 insertions(+), 49 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 6f9d5aca41..bdd9e6fbaf 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -56,7 +56,7 @@ namespace MaterialEditor AZStd::vector MaterialEditorApplication::GetCriticalAssetFilters() const { - return AZStd::vector({ "passes/", "config/", "MaterialEditor" }); + return AZStd::vector({ "passes/", "config/", "MaterialEditor/" }); } void MaterialEditorApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 8d89e7442e..f93edfd275 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 AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 5ecff06bc7..9a713426ea 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -19,11 +19,6 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnin AZ_POP_DISABLE_WARNING #endif -namespace AzToolsFramework -{ - class CScriptTermDialog; -} - namespace MaterialEditor { /** @@ -59,8 +54,8 @@ namespace MaterialEditor void OnDocumentSaved(const AZ::Uuid& documentId) override; void CreateMenu() override; - void CreateTabBar() override; + void AddTabForDocumentId(const AZ::Uuid& documentId) override; void UpdateTabForDocumentId(const AZ::Uuid& documentId) override; QString GetDocumentPath(const AZ::Uuid& documentId) const; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 0a7ce6dd59..2cc4e67ba0 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -6,34 +6,29 @@ * */ -#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 #include -#include -#include -#include -#include #include +#include #include +#include +#include +#include +#include AZ_POP_DISABLE_WARNING namespace ShaderManagementConsole @@ -482,4 +477,4 @@ namespace ShaderManagementConsole } } // 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 f1c74a1f48..57bd11cb0a 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -10,11 +10,10 @@ #if !defined(Q_MOC_RUN) #include -#include - #include #include #include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -24,11 +23,6 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnin AZ_POP_DISABLE_WARNING #endif -namespace AzToolsFramework -{ - class CScriptTermDialog; -} - namespace ShaderManagementConsole { /** @@ -57,8 +51,8 @@ namespace ShaderManagementConsole void OnDocumentSaved(const AZ::Uuid& documentId) override; void CreateMenu() override; - void CreateTabBar() override; + void AddTabForDocumentId(const AZ::Uuid& documentId) override; void UpdateTabForDocumentId(const AZ::Uuid& documentId) override; From 84623dfb6693ed38596c25a7c2902aaa0c4b997f Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 19:25:26 -0700 Subject: [PATCH 130/251] FixedMaxPathString replacement Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/CryEditPy.cpp | 4 ++-- Code/Editor/Util/PathUtil.cpp | 2 +- .../Framework/AzCore/Tests/IO/Path/PathTests.cpp | 4 ++-- .../AzFramework/AzFramework/Archive/Archive.cpp | 8 ++++---- .../AzFramework/AzFramework/Archive/IArchive.h | 2 +- .../AzFramework/Archive/NestedArchive.cpp | 16 ++++++++-------- .../AzFramework/Archive/ZipDirStructures.cpp | 2 +- .../native/ui/ProductAssetTreeModel.cpp | 4 ++-- .../native/ui/SourceAssetTreeModel.cpp | 4 ++-- 9 files changed, 23 insertions(+), 23 deletions(-) diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp index 7e07d5553d..e4c300d744 100644 --- a/Code/Editor/CryEditPy.cpp +++ b/Code/Editor/CryEditPy.cpp @@ -210,7 +210,7 @@ namespace const char* PyGetCurrentLevelName() { // Using static member to capture temporary data - static AZStd::fixed_string tempLevelName; + static AZ::IO::FixedMaxPathString tempLevelName; tempLevelName = GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().data(); return tempLevelName.c_str(); } @@ -218,7 +218,7 @@ namespace const char* PyGetCurrentLevelPath() { // Using static member to capture temporary data - static AZStd::fixed_string tempLevelPath; + static AZ::IO::FixedMaxPathString tempLevelPath; tempLevelPath = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data(); return tempLevelPath.c_str(); } diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp index 3ca4b6222c..e8a5f0f74a 100644 --- a/Code/Editor/Util/PathUtil.cpp +++ b/Code/Editor/Util/PathUtil.cpp @@ -246,7 +246,7 @@ namespace Path AZStd::string GetEditingGameDataFolder() { // Define here the mod name - static AZStd::fixed_string s_currentModName; + static AZ::IO::FixedMaxPathString s_currentModName; if (s_currentModName.empty()) { diff --git a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp index 79d9f8c302..41e0ac3f09 100644 --- a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp +++ b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp @@ -418,7 +418,7 @@ namespace UnitTest // Check each operator/= and append overload for success { - AZStd::fixed_string pathString{ "foo" }; + AZ::IO::FixedMaxPathString pathString{ "foo" }; AZ::IO::FixedMaxPath testPath('/'); testPath /= AZ::IO::PathView(pathString); testPath /= pathString; @@ -428,7 +428,7 @@ namespace UnitTest EXPECT_STREQ("foo/foo/foo/foo/f", testPath.c_str()); } { - AZStd::fixed_string pathString{ "foo" }; + AZ::IO::FixedMaxPathString pathString{ "foo" }; AZ::IO::FixedMaxPath testPath('/'); testPath.Append(AZ::IO::PathView(pathString)); testPath.Append(pathString); diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp index 8c24250396..a3d2103650 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp @@ -94,7 +94,7 @@ namespace AZ::IO::ArchiveInternal } return convertedPath; } - return AZStd::make_optional>(sourcePath); + return AZStd::make_optional(sourcePath); } struct CCachedFileRawData @@ -614,7 +614,7 @@ namespace AZ::IO const char* Archive::AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t, bool) { - AZStd::fixed_string srcPath{ src }; + AZ::IO::FixedMaxPathString srcPath{ src }; return AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(srcPath.c_str(), dst, dstSize) ? dst : nullptr; } @@ -2407,14 +2407,14 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// bool Archive::RemoveFile(AZStd::string_view pName) { - AZStd::fixed_string szFullPath{ pName }; + AZ::IO::FixedMaxPathString szFullPath{ pName }; return AZ::IO::FileIOBase::GetDirectInstance()->Remove(szFullPath.c_str()) == AZ::IO::ResultCode::Success; } ////////////////////////////////////////////////////////////////////////// bool Archive::RemoveDir(AZStd::string_view pName) { - AZStd::fixed_string szFullPath{ pName }; + AZ::IO::FixedMaxPathString szFullPath{ pName }; if (AZ::IO::FileIOBase::GetDirectInstance()->IsDirectory(szFullPath.c_str())) { diff --git a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h index 3de63169b2..a23a213f05 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h @@ -30,7 +30,7 @@ namespace AZ::IO struct INestedArchive; struct IArchive; - using PathString = AZStd::fixed_string; + using PathString = AZ::IO::FixedMaxPathString; using StackString = AZStd::fixed_string<512>; struct MemoryBlock; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp index 16548c6a39..dc1d4aa864 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp @@ -41,7 +41,7 @@ namespace AZ::IO return ZipDir::ZD_ERROR_INVALID_CALL; } - AZStd::fixed_string fullPath = AdjustPath(szRelativePath); + AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath); if (fullPath.empty()) { return ZipDir::ZD_ERROR_INVALID_PATH; @@ -63,7 +63,7 @@ namespace AZ::IO return ZipDir::ZD_ERROR_INVALID_CALL; } - AZStd::fixed_string fullPath = AdjustPath(szRelativePath); + AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath); if (fullPath.empty()) { return ZipDir::ZD_ERROR_INVALID_PATH; @@ -81,7 +81,7 @@ namespace AZ::IO return ZipDir::ZD_ERROR_INVALID_CALL; } - AZStd::fixed_string fullPath = AdjustPath(szRelativePath); + AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath); if (fullPath.empty()) { return ZipDir::ZD_ERROR_INVALID_PATH; @@ -105,7 +105,7 @@ namespace AZ::IO return ZipDir::ZD_ERROR_INVALID_CALL; } - AZStd::fixed_string fullPath = AdjustPath(szRelativePath); + AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath); if (fullPath.empty()) { return ZipDir::ZD_ERROR_INVALID_PATH; @@ -122,7 +122,7 @@ namespace AZ::IO return ZipDir::ZD_ERROR_INVALID_CALL; } - AZStd::fixed_string fullPath = AdjustPath(szRelativePath); + AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath); if (fullPath.empty()) { return ZipDir::ZD_ERROR_INVALID_PATH; @@ -141,7 +141,7 @@ namespace AZ::IO return ZipDir::ZD_ERROR_INVALID_CALL; } - AZStd::fixed_string fullPath = AdjustPath(szRelativePath); + AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath); if (fullPath.empty()) { return ZipDir::ZD_ERROR_INVALID_PATH; @@ -152,7 +152,7 @@ namespace AZ::IO // finds the file; you don't have to close the returned handle auto NestedArchive::FindFile(AZStd::string_view szRelativePath) -> Handle { - AZStd::fixed_string fullPath = AdjustPath(szRelativePath); + AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath); if (fullPath.empty()) { return nullptr; @@ -249,7 +249,7 @@ namespace AZ::IO if (m_nFlags & FLAGS_RELATIVE_PATHS_ONLY) { - return AZStd::fixed_string{ szRelativePath }; + return AZ::IO::FixedMaxPathString{ szRelativePath }; } if ((szRelativePath.size() > 1 && szRelativePath[1] == ':') || (m_nFlags & FLAGS_ABSOLUTE_PATHS)) diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp index 034d2f4029..445bba63f4 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp @@ -440,7 +440,7 @@ namespace AZ::IO::ZipDir azstrcpy(volume, AZ_ARRAY_SIZE(volume), filename); } - AZStd::fixed_string drive{ AZ::IO::PathView(volume).RootName().Native() }; + AZ::IO::FixedMaxPathString drive{ AZ::IO::PathView(volume).RootName().Native() }; if (drive.empty()) { return false; diff --git a/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp b/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp index 6b5fa191e8..0574f00961 100644 --- a/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp +++ b/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp @@ -195,7 +195,7 @@ namespace AssetProcessor AZ::IO::Path currentFullFolderPath; const AZ::IO::PathView filename = productNamePath.Filename(); const AZ::IO::PathView fullPathWithoutFilename = productNamePath.RemoveFilename(); - AZStd::fixed_string currentPath; + AZ::IO::FixedMaxPathString currentPath; for (auto pathIt = fullPathWithoutFilename.begin(); pathIt != fullPathWithoutFilename.end(); ++pathIt) { currentPath = pathIt->FixedMaxPathString(); @@ -236,7 +236,7 @@ namespace AssetProcessor } AZStd::shared_ptr productItemData = - ProductAssetTreeItemData::MakeShared(&product, product.m_productName, AZStd::fixed_string(filename.Native()).c_str(), false, sourceId); + ProductAssetTreeItemData::MakeShared(&product, product.m_productName, AZ::IO::FixedMaxPathString(filename.Native()).c_str(), false, sourceId); m_productToTreeItem[product.m_productName] = parentItem->CreateChild(productItemData); m_productIdToTreeItem[product.m_productID] = m_productToTreeItem[product.m_productName]; diff --git a/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp b/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp index 6a5e53eb75..1fcdd62cf7 100644 --- a/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp +++ b/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp @@ -94,7 +94,7 @@ namespace AssetProcessor AZ::IO::Path currentFullFolderPath(AZ::IO::PosixPathSeparator); const AZ::IO::FixedMaxPath filename = fullPath.Filename(); fullPath.RemoveFilename(); - AZStd::fixed_string currentPath; + AZ::IO::FixedMaxPathString currentPath; for (auto pathIt = fullPath.begin(); pathIt != fullPath.end(); ++pathIt) { currentPath = pathIt->FixedMaxPathString(); @@ -125,7 +125,7 @@ namespace AssetProcessor } m_sourceToTreeItem[source.m_sourceName] = - parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(&source, &scanFolder, source.m_sourceName, AZStd::fixed_string(filename.Native()).c_str(), false)); + parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(&source, &scanFolder, source.m_sourceName, AZ::IO::FixedMaxPathString(filename.Native()).c_str(), false)); m_sourceIdToTreeItem[source.m_sourceID] = m_sourceToTreeItem[source.m_sourceName]; if (!modelIsResetting) { From 895dc09176351b44de34a7f810b40dc6c854f6dc Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 19:30:09 -0700 Subject: [PATCH 131/251] addressing PR comments/suggestions Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../AzCore/AzCore/std/string/conversions.h | 4 +- .../AzCore/AzCore/std/string/utf8/unchecked.h | 48 +++++++++++++++++++ .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp | 12 ++++- .../AzCore/Debug/StackTracer_Windows.cpp | 2 +- Code/Legacy/CryCommon/CryTypeInfo.cpp | 4 +- .../DataTypes/Rules/IMeshAdvancedRule.h | 2 +- 6 files changed, 63 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index 235eb188d1..473c327143 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -338,7 +338,7 @@ namespace AZStd if (srcLen > 0) { char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen); - if (*(endStr - 1) != '\0') + if (endStr < (dest + destSize) && *(endStr - 1) != '\0') { *endStr = '\0'; // copy null terminator } @@ -495,7 +495,7 @@ namespace AZStd if (srcLen > 0) { wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen); - if (*(endWStr - 1) != '\0') + if (endWStr < (dest + destSize) && *(endWStr - 1) != '\0') { *endWStr = '\0'; // copy null terminator } diff --git a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h index cfc917ddc4..7199c58d3e 100644 --- a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h +++ b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h @@ -251,6 +251,54 @@ namespace Utf8::Unchecked return result; } + + static constexpr size_t utf8_codepoint_length(AZ::u32 cp) + { + if (cp < 0x80) + { + return 1; + } + else if (cp < 0x800) + { + return 2; + } + else if (cp < 0x10000) + { + return 3; + } + return 4; + } + + template + size_t utf16ToUtf8BytesRequired(u16bit_iterator start, u16bit_iterator end) + { + size_t bytesRequired = 0; + while (start != end) + { + AZ::u32 cp = Utf8::Internal::mask16(*start++); + // Take care of surrogate pairs first + if (Utf8::Internal::is_lead_surrogate(cp)) + { + AZ::u32 trail_surrogate = Utf8::Internal::mask16(*start++); + cp = (cp << 10) + trail_surrogate + Internal::SURROGATE_OFFSET; + } + bytesRequired += utf8_codepoint_length(cp); + } + return bytesRequired; + } + + template + size_t utf32ToUtf8BytesRequired(u32bit_iterator start, u32bit_iterator end) + { + size_t bytesRequired = 0; + while (start != end) + { + bytesRequired += utf8_codepoint_length(*start++); + } + return bytesRequired; + } + + } // namespace Utf8::Unchecked diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp index dc104668be..4d8c9c8cfc 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp @@ -31,7 +31,7 @@ namespace AZ // Platform specific get exe path: http://stackoverflow.com/a/1024937 // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea wchar_t pathBufferW[AZ::IO::MaxPathLength] = { 0 }; - const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(exeStorageSize)); + const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(AZStd::size(pathBufferW))); const DWORD errorCode = GetLastError(); if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER) { @@ -43,7 +43,15 @@ namespace AZ } else { - AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBufferW); + size_t utf8PathSize = Utf8::Unchecked::utf16ToUtf8BytesRequired(pathBufferW, pathBufferW + pathLen); + if (utf8PathSize >= exeStorageSize) + { + result.m_pathStored = ExecutablePathResult::BufferSizeNotLargeEnough; + } + else + { + AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBufferW); + } } return result; diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index 8a99616de3..6cfaf1703b 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -90,7 +90,7 @@ namespace AZ { { case CBA_EVENT: evt = (PIMAGEHLP_CBA_EVENT)CallbackData; - _tprintf(_T("%s"), evt->desc); + printf("%s", evt->desc); break; default: diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp index b1f7f20601..82743f7eef 100644 --- a/Code/Legacy/CryCommon/CryTypeInfo.cpp +++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp @@ -132,9 +132,7 @@ const CTypeInfo&PtrTypeInfo() // bool AZStd::string ToString(bool const& val) { - static AZStd::fixed_string<5> sTrue = "true"; - static AZStd::fixed_string<6> sFalse = "false"; - return val ? sTrue.c_str() : sFalse.c_str(); + return val ? "true" : "false"; } bool FromString(bool& val, cstr s) diff --git a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h index 48310091b3..04ed3f0949 100644 --- a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h +++ b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h @@ -19,7 +19,7 @@ namespace AZ { namespace DataTypes { - static AZStd::string s_advancedDisabledString = "Disabled"; + static const char* s_advancedDisabledString = "Disabled"; class IMeshAdvancedRule : public IRule From 6d79f1beee1987bcaac4d5e0c0c84bfdf430c625 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 19:30:52 -0700 Subject: [PATCH 132/251] more replacements of A functions Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp | 2 +- Code/Editor/ProcessInfo.cpp | 2 +- .../Platform/Windows/AzCore/Platform_Windows.cpp | 12 ++++++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp index 0b33caed88..a3be4cfd45 100644 --- a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp +++ b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp @@ -28,7 +28,7 @@ bool CMailer::SendMail(const char* subject, GetCurrentDirectoryW(sizeof(dir), dir); // Load MAPI dll - HMODULE hMAPILib = LoadLibraryA("MAPI32.DLL"); + HMODULE hMAPILib = LoadLibraryW(L"MAPI32.DLL"); LPMAPISENDMAIL lpfnMAPISendMail = (LPMAPISENDMAIL) GetProcAddress(hMAPILib, "MAPISendMail"); int numRecipients = (int)_recipients.size(); diff --git a/Code/Editor/ProcessInfo.cpp b/Code/Editor/ProcessInfo.cpp index 87f4f23846..692e5d65ef 100644 --- a/Code/Editor/ProcessInfo.cpp +++ b/Code/Editor/ProcessInfo.cpp @@ -41,7 +41,7 @@ void LoadPSApi() { if (!g_hPSAPI) { - g_hPSAPI = LoadLibraryA("psapi.dll"); + g_hPSAPI = LoadLibraryW(L"psapi.dll"); if (g_hPSAPI) { diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp index dc675cd931..cc45b36c41 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp @@ -31,8 +31,8 @@ namespace AZ // Query the machine guid generated at install time by windows, which is generated from // hardware signatures. This guid is not enough, because images (AWS) may duplicate this, // so include the hostname/username as well - TCHAR machineInfo[MAX_COMPUTERNAME_LENGTH + 1024] = { 0 }; - ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", 0, KEY_QUERY_VALUE, &key); + wchar_t machineInfo[MAX_COMPUTERNAME_LENGTH + 1024] = { 0 }; + ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography", 0, KEY_QUERY_VALUE, &key); if (ret == ERROR_SUCCESS) { DWORD dataType = REG_SZ; @@ -45,17 +45,17 @@ namespace AZ AZ_Error("System", false, "Failed to open HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid!") } - TCHAR* hostname = machineInfo + wcslen(machineInfo); + wchar_t* hostname = machineInfo + wcslen(machineInfo); // salt the guid time with ComputerName/UserName DWORD bufCharCount = DWORD(sizeof(machineInfo) - (hostname - machineInfo)); - if (!::GetComputerName(hostname, &bufCharCount)) + if (!::GetComputerNameW(hostname, &bufCharCount)) { AZ_Error("System", false, "GetComputerName filed with code %d", GetLastError()); } - TCHAR* username = hostname + wcslen(hostname); + wchar_t* username = hostname + wcslen(hostname); bufCharCount = DWORD(sizeof(machineInfo) - (username - machineInfo)); - if( !GetUserName( username, &bufCharCount ) ) + if(!GetUserNameW(username, &bufCharCount)) { AZ_Error("System",false,"GetUserName filed with code %d",GetLastError()); } From 4358b6eb27fbb65baebb0afc2444015f8983af83 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 19:31:12 -0700 Subject: [PATCH 133/251] runtime fixes (Editor running) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Controls/ConsoleSCB.cpp | 8 +- Code/Editor/QuickAccessBar.cpp | 6 +- Code/Editor/SettingsManager.cpp | 10 +- Code/Editor/ToolsConfigPage.cpp | 6 +- Code/Legacy/CryCommon/IConsole.h | 2 +- Code/Legacy/CryCommon/Mocks/IConsoleMock.h | 2 +- Code/Legacy/CrySystem/XConsole.cpp | 115 +++++------------- Code/Legacy/CrySystem/XConsole.h | 2 +- Code/Legacy/CrySystem/XConsoleVariable.h | 7 +- .../RemoteConsole/Core/RemoteConsoleCore.cpp | 6 +- 10 files changed, 55 insertions(+), 109 deletions(-) diff --git a/Code/Editor/Controls/ConsoleSCB.cpp b/Code/Editor/Controls/ConsoleSCB.cpp index 0c664bbc59..9c13aa7328 100644 --- a/Code/Editor/Controls/ConsoleSCB.cpp +++ b/Code/Editor/Controls/ConsoleSCB.cpp @@ -562,15 +562,15 @@ static void OnVariableUpdated([[maybe_unused]] int row, ICVar* pCVar) static CVarBlock* VarBlockFromConsoleVars() { IConsole* console = GetIEditor()->GetSystem()->GetIConsole(); - std::vector cmds; + AZStd::vector cmds; cmds.resize(console->GetNumVars()); - size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size()); + size_t cmdCount = console->GetSortedVars(cmds); CVarBlock* vb = new CVarBlock; IVariable* pVariable = 0; for (int i = 0; i < cmdCount; i++) { - ICVar* pCVar = console->GetCVar(cmds[i]); + ICVar* pCVar = console->GetCVar(cmds[i].data()); if (!pCVar) { continue; @@ -602,7 +602,7 @@ static CVarBlock* VarBlockFromConsoleVars() pCVar->AddOnChangeFunctor(onChange); pVariable->SetDescription(pCVar->GetHelp()); - pVariable->SetName(cmds[i]); + pVariable->SetName(cmds[i].data()); // Transfer the custom limits have they have been set for this variable if (pCVar->HasCustomLimits()) diff --git a/Code/Editor/QuickAccessBar.cpp b/Code/Editor/QuickAccessBar.cpp index 0379be027d..59b4418c4c 100644 --- a/Code/Editor/QuickAccessBar.cpp +++ b/Code/Editor/QuickAccessBar.cpp @@ -68,12 +68,12 @@ void CQuickAccessBar::OnInitDialog() // Add console variables & commands. IConsole* console = GetIEditor()->GetSystem()->GetIConsole(); - std::vector cmds; + AZStd::vector cmds; cmds.resize(console->GetNumVars()); - size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size()); + size_t cmdCount = console->GetSortedVars(cmds); for (int i = 0; i < cmdCount; ++i) { - m_model->setStringList(m_model->stringList() += cmds[i]); + m_model->setStringList(m_model->stringList() += cmds[i].data()); } } diff --git a/Code/Editor/SettingsManager.cpp b/Code/Editor/SettingsManager.cpp index 82e3eaf1e6..3f170e83c8 100644 --- a/Code/Editor/SettingsManager.cpp +++ b/Code/Editor/SettingsManager.cpp @@ -607,7 +607,7 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad) int nCurrentVariable(0); IConsole* piConsole(NULL); ICVar* piVariable(NULL); - std::vector cszVariableNames; + AZStd::vector cszVariableNames; char* szKey(NULL); char* szValue(NULL); @@ -662,7 +662,7 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad) nNumberOfVariables = piConsole->GetNumVisibleVars(); cszVariableNames.resize(nNumberOfVariables, NULL); - if (piConsole->GetSortedVars((const char**)&cszVariableNames.front(), nNumberOfVariables, NULL) != nNumberOfVariables) + if (piConsole->GetSortedVars(cszVariableNames, NULL) != nNumberOfVariables) { assert(false); return; @@ -670,12 +670,12 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad) for (nCurrentVariable = 0; nCurrentVariable < cszVariableNames.size(); ++nCurrentVariable) { - if (_stricmp(cszVariableNames[nCurrentVariable], "_TestFormatMessage") == 0) + if (_stricmp(cszVariableNames[nCurrentVariable].data(), "_TestFormatMessage") == 0) { continue; } - piVariable = piConsole->GetCVar(cszVariableNames[nCurrentVariable]); + piVariable = piConsole->GetCVar(cszVariableNames[nCurrentVariable].data()); if (!piVariable) { assert(false); @@ -683,7 +683,7 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad) } newCVarNode = XmlHelpers::CreateXmlNode(CVAR_NODE); - newCVarNode->setAttr(cszVariableNames[nCurrentVariable], piVariable->GetString()); + newCVarNode->setAttr(cszVariableNames[nCurrentVariable].data(), piVariable->GetString()); cvarsNode->addChild(newCVarNode); } diff --git a/Code/Editor/ToolsConfigPage.cpp b/Code/Editor/ToolsConfigPage.cpp index a2328550e0..7e481506b3 100644 --- a/Code/Editor/ToolsConfigPage.cpp +++ b/Code/Editor/ToolsConfigPage.cpp @@ -818,12 +818,12 @@ void CToolsConfigPage::FillConsoleCmds() { QStringList commands; IConsole* console = GetIEditor()->GetSystem()->GetIConsole(); - std::vector cmds; + AZStd::vector cmds; cmds.resize(console->GetNumVars()); - size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size()); + size_t cmdCount = console->GetSortedVars(cmds); for (int i = 0; i < cmdCount; ++i) { - commands.push_back(cmds[i]); + commands.push_back(cmds[i].data()); } m_completionModel->setStringList(commands); } diff --git a/Code/Legacy/CryCommon/IConsole.h b/Code/Legacy/CryCommon/IConsole.h index 79bfc5b532..e03de35aa1 100644 --- a/Code/Legacy/CryCommon/IConsole.h +++ b/Code/Legacy/CryCommon/IConsole.h @@ -426,7 +426,7 @@ struct IConsole // szPrefix - 0 or prefix e.g. "sys_spec_" // Return // used size - virtual size_t GetSortedVars(const char** pszArray, size_t numItems, const char* szPrefix = 0) = 0; + virtual size_t GetSortedVars(AZStd::vector& pszArray, const char* szPrefix = 0) = 0; virtual const char* AutoComplete(const char* substr) = 0; virtual const char* AutoCompletePrev(const char* substr) = 0; virtual const char* ProcessCompletion(const char* szInputBuffer) = 0; diff --git a/Code/Legacy/CryCommon/Mocks/IConsoleMock.h b/Code/Legacy/CryCommon/Mocks/IConsoleMock.h index 1475e8e01e..b416aa5f11 100644 --- a/Code/Legacy/CryCommon/Mocks/IConsoleMock.h +++ b/Code/Legacy/CryCommon/Mocks/IConsoleMock.h @@ -56,7 +56,7 @@ public: MOCK_METHOD0(IsOpened, bool ()); MOCK_METHOD0(GetNumVars, int()); MOCK_METHOD0(GetNumVisibleVars, int()); - MOCK_METHOD3(GetSortedVars, size_t (const char** pszArray, size_t numItems, const char* szPrefix)); + MOCK_METHOD2(GetSortedVars, size_t (AZStd::vector& pszArray, const char* szPrefix)); MOCK_METHOD1(AutoComplete, const char*(const char* substr)); MOCK_METHOD1(AutoCompletePrev, const char*(const char* substr)); MOCK_METHOD1(ProcessCompletion, const char*(const char* szInputBuffer)); diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index 6da42420f8..0f98dd12d6 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -84,35 +84,6 @@ inline int GetCharPrio(char x) return x; } } -// case sensitive -inline bool less_CVar(const AZStd::string& left, const AZStd::string& right) -{ - AZStd::string_view leftView(left); - AZStd::string_view rightView(right); - for (;; ) - { - uint32 l = GetCharPrio(leftView.front()), r = GetCharPrio(rightView.front()); - - if (l < r) - { - return true; - } - if (l > r) - { - return false; - } - - if (leftView.front() == 0 || rightView.front() == 0) - { - break; - } - - leftView.remove_prefix(1); - rightView.remove_prefix(1); - } - - return false; -} void Command_SetWaitSeconds(IConsoleCmdArgs* pCmd) { @@ -347,28 +318,6 @@ void CXConsole::Init(ISystem* pSystem) con_restricted = 0; } - // test cases ----------------------------------------------- - assert(GetCVar("con_debug") != 0); // should be registered a few lines above - assert(GetCVar("Con_Debug") == GetCVar("con_debug")); // different case - - // editor - assert(strcmp(AutoComplete("con_"), "con_debug") == 0); - assert(strcmp(AutoComplete("CON_"), "con_debug") == 0); - assert(strcmp(AutoComplete("con_debug"), "con_display_last_messages") == 0); // actually we should reconsider this behavior - assert(strcmp(AutoComplete("Con_Debug"), "con_display_last_messages") == 0); // actually we should reconsider this behavior - - // game - assert(strcmp(ProcessCompletion("con_"), "con_debug ") == 0); - ResetAutoCompletion(); - assert(strcmp(ProcessCompletion("CON_"), "con_debug ") == 0); - ResetAutoCompletion(); - assert(strcmp(ProcessCompletion("con_debug"), "con_debug ") == 0); - ResetAutoCompletion(); - assert(strcmp(ProcessCompletion("Con_Debug"), "con_debug ") == 0); - ResetAutoCompletion(); - - // ---------------------------------------------------------- - m_nLoadingBackTexID = -1; if (gEnv->IsDedicated()) @@ -2424,7 +2373,7 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) if (!matches.empty()) { - std::sort(matches.begin(), matches.end(), less_CVar); // to sort commands with variables + std::sort(matches.begin(), matches.end()); // to sort commands with variables } if (showlist && !matches.empty()) { @@ -3181,7 +3130,7 @@ char* CXConsole::GetCheatVarAt(uint32 nOffset) ////////////////////////////////////////////////////////////////////////// -size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const char* szPrefix) +size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, const char* szPrefix) { size_t i = 0; size_t iPrefixLen = szPrefix ? strlen(szPrefix) : 0; @@ -3191,7 +3140,7 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch ConsoleVariablesMap::const_iterator it, end = m_mapVariables.end(); for (it = m_mapVariables.begin(); it != end; ++it) { - if (pszArray && i >= numItems) + if (i >= pszArray.size()) { break; } @@ -3209,10 +3158,7 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch continue; } - if (pszArray) - { - pszArray[i] = it->first; - } + pszArray[i] = it->first; i++; } @@ -3223,7 +3169,7 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch ConsoleCommandsMap::iterator it, end = m_mapCommands.end(); for (it = m_mapCommands.begin(); it != end; ++it) { - if (pszArray && i >= numItems) + if (i >= pszArray.size()) { break; } @@ -3241,18 +3187,15 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch continue; } - if (pszArray) - { - pszArray[i] = it->first.c_str(); - } + pszArray[i] = it->first.c_str(); i++; } } - if (i != 0 && pszArray) + if (i != 0) { - std::sort(pszArray, pszArray + i, less_CVar); + std::sort(pszArray.begin(), pszArray.end()); } return i; @@ -3261,22 +3204,22 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch ////////////////////////////////////////////////////////////////////////// void CXConsole::FindVar(const char* substr) { - std::vector cmds; + AZStd::vector cmds; cmds.resize(GetNumVars() + m_mapCommands.size()); - size_t cmdCount = GetSortedVars(&cmds[0], cmds.size()); + size_t cmdCount = GetSortedVars(cmds); for (size_t i = 0; i < cmdCount; i++) { if (AZ::StringFunc::Find(cmds[i], substr) != AZStd::string::npos) { - ICVar* pCvar = gEnv->pConsole->GetCVar(cmds[i]); + ICVar* pCvar = gEnv->pConsole->GetCVar(cmds[i].data()); if (pCvar) { DisplayVarValue(pCvar); } else { - ConsoleLogInputResponse(" $3%s $6(Command)", cmds[i]); + ConsoleLogInputResponse(" $3%.*s $6(Command)", aznumeric_cast(cmds[i].size()), cmds[i].data()); } } } @@ -3287,22 +3230,22 @@ const char* CXConsole::AutoComplete(const char* substr) { // following code can be optimized - std::vector cmds; + AZStd::vector cmds; cmds.resize(GetNumVars() + m_mapCommands.size()); - size_t cmdCount = GetSortedVars(&cmds[0], cmds.size()); + size_t cmdCount = GetSortedVars(cmds); size_t substrLen = strlen(substr); // If substring is empty return first command. if (substrLen == 0 && cmdCount > 0) { - return cmds[0]; + return cmds[0].data(); } // find next for (size_t i = 0; i < cmdCount; i++) { - const char* szCmd = cmds[i]; + const char* szCmd = cmds[i].data(); size_t cmdlen = strlen(szCmd); if (cmdlen >= substrLen && memcmp(szCmd, substr, substrLen) == 0) { @@ -3311,18 +3254,18 @@ const char* CXConsole::AutoComplete(const char* substr) i++; if (i < cmdCount) { - return cmds[i]; + return cmds[i].data(); } - return cmds[i - 1]; + return cmds[i - 1].data(); } - return cmds[i]; + return cmds[i].data(); } } // then first matching case insensitive for (size_t i = 0; i < cmdCount; i++) { - const char* szCmd = cmds[i]; + const char* szCmd = cmds[i].data(); size_t cmdlen = strlen(szCmd); if (cmdlen >= substrLen && azstrnicmp(szCmd, substr, substrLen) == 0) @@ -3332,11 +3275,11 @@ const char* CXConsole::AutoComplete(const char* substr) i++; if (i < cmdCount) { - return cmds[i]; + return cmds[i].data(); } - return cmds[i - 1]; + return cmds[i - 1].data(); } - return cmds[i]; + return cmds[i].data(); } } @@ -3357,27 +3300,27 @@ void CXConsole::SetInputLine(const char* szLine) ////////////////////////////////////////////////////////////////////////// const char* CXConsole::AutoCompletePrev(const char* substr) { - std::vector cmds; + AZStd::vector cmds; cmds.resize(GetNumVars() + m_mapCommands.size()); - size_t cmdCount = GetSortedVars(&cmds[0], cmds.size()); + size_t cmdCount = GetSortedVars(cmds); // If substring is empty return last command. if (strlen(substr) == 0 && cmds.size() > 0) { - return cmds[cmdCount - 1]; + return cmds[cmdCount - 1].data(); } for (unsigned int i = 0; i < cmdCount; i++) { - if (azstricmp(substr, cmds[i]) == 0) + if (azstricmp(substr, cmds[i].data()) == 0) { if (i > 0) { - return cmds[i - 1]; + return cmds[i - 1].data(); } else { - return cmds[0]; + return cmds[0].data(); } } } diff --git a/Code/Legacy/CrySystem/XConsole.h b/Code/Legacy/CrySystem/XConsole.h index b141a88e52..16d1870be6 100644 --- a/Code/Legacy/CrySystem/XConsole.h +++ b/Code/Legacy/CrySystem/XConsole.h @@ -181,7 +181,7 @@ public: virtual bool IsOpened(); virtual int GetNumVars(); virtual int GetNumVisibleVars(); - virtual size_t GetSortedVars(const char** pszArray, size_t numItems, const char* szPrefix = 0); + virtual size_t GetSortedVars(AZStd::vector& pszArray, const char* szPrefix = 0); virtual int GetNumCheatVars(); virtual void SetCheatVarHashRange(size_t firstVar, size_t lastVar); virtual void CalcCheatVarHash(); diff --git a/Code/Legacy/CrySystem/XConsoleVariable.h b/Code/Legacy/CrySystem/XConsoleVariable.h index e4f9c14355..122389407f 100644 --- a/Code/Legacy/CrySystem/XConsoleVariable.h +++ b/Code/Legacy/CrySystem/XConsoleVariable.h @@ -179,8 +179,11 @@ public: CXConsoleVariableString(CXConsole* pConsole, const char* sName, const char* szDefault, int nFlags, const char* help) : CXConsoleVariableBase(pConsole, sName, nFlags, help) { - m_sValue = szDefault; - m_sDefault = szDefault; + if (szDefault) + { + m_sValue = szDefault; + m_sDefault = szDefault; + } } // interface ICVar -------------------------------------------------------------------------------------- diff --git a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp index 24faf2ccaa..aa439116a0 100644 --- a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp +++ b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp @@ -446,10 +446,10 @@ bool SRemoteClient::SendPackage(const char* buffer, int size) ///////////////////////////////////////////////////////////////////////////////////////////// void SRemoteClient::FillAutoCompleteList(AZStd::vector& list) { - AZStd::vector cmds; - size_t count = gEnv->pConsole->GetSortedVars(nullptr, 0); + AZStd::vector cmds; + size_t count = gEnv->pConsole->GetSortedVars(cmds); cmds.resize(count); - count = gEnv->pConsole->GetSortedVars(&cmds[0], count); + count = gEnv->pConsole->GetSortedVars(cmds); for (size_t i = 0; i < count; ++i) { list.push_back(cmds[i]); From b4bf775647c3d2bc03a94988226e1751644ed9ae Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 16 Jun 2021 17:14:27 -0700 Subject: [PATCH 134/251] enable the warning Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- cmake/Platform/Common/MSVC/Configurations_msvc.cmake | 1 - 1 file changed, 1 deletion(-) diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index 4024e45bad..118a515e30 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -38,7 +38,6 @@ ly_append_configurations_options( /wd4201 # nonstandard extension used: nameless struct/union. This actually became part of the C++11 std, MS has an open issue: https://developercommunity.visualstudio.com/t/warning-level-4-generates-a-bogus-warning-c4201-no/103064 # Disabling these warnings while they get fixed - /wd4018 # signed/unsigned mismatch /wd4244 # conversion, possible loss of data /wd4245 # conversion, signed/unsigned mismatch /wd4389 # comparison, signed/unsigned mismatch From 97354ce90a9ddd6600271df1e663e21790fc8dc1 Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 18 Jun 2021 16:36:30 -0700 Subject: [PATCH 135/251] Sandbox Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/ViewportTitleDlg.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp index c1e1afb908..cbf2958eea 100644 --- a/Code/Editor/ViewportTitleDlg.cpp +++ b/Code/Editor/ViewportTitleDlg.cpp @@ -451,19 +451,19 @@ void CViewportTitleDlg::AddFOVMenus(QMenu* menu, std::function call { for (size_t i = 0; i < customPresets.size(); ++i) { - if (customPresets[i].isEmpty()) + if (customPresets[static_cast(i)].isEmpty()) { break; } float fov = gSettings.viewports.fDefaultFov; bool ok; - float f = customPresets[i].toDouble(&ok); + float f = customPresets[static_cast(i)].toDouble(&ok); if (ok) { fov = std::max(1.0f, f); fov = std::min(120.0f, f); - QAction* action = menu->addAction(customPresets[i]); + QAction* action = menu->addAction(customPresets[static_cast(i)]); connect(action, &QAction::triggered, action, [fov, callback](){ callback(fov); }); } } @@ -537,13 +537,13 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::function(i)].isEmpty()) { break; } static QRegularExpression regex(QStringLiteral("^(\\d+):(\\d+)$")); - QRegularExpressionMatch matches = regex.match(customPresets[i]); + QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]); if (matches.hasMatch()) { bool ok; @@ -551,7 +551,7 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::functionaddAction(customPresets[i]); + QAction* action = menu->addAction(customPresets[static_cast(i)]); connect(action, &QAction::triggered, action, [width, height, callback]() {callback(width, height); }); } } @@ -668,13 +668,13 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::function(i)].isEmpty()) { break; } static QRegularExpression regex(QStringLiteral("^(\\d+) x (\\d+)$")); - QRegularExpressionMatch matches = regex.match(customPresets[i]); + QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]); if (matches.hasMatch()) { bool ok; @@ -682,7 +682,7 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::functionaddAction(customPresets[i]); + QAction* action = menu->addAction(customPresets[static_cast(i)]); connect(action, &QAction::triggered, action, [width, height, callback](){ callback(width, height); }); } } From 10f950b726ca9e6d8fe7f3c776b6094d9027dcce Mon Sep 17 00:00:00 2001 From: pappeste Date: Fri, 18 Jun 2021 17:45:51 -0700 Subject: [PATCH 136/251] fix w4018 Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Prefab/Benchmark/PrefabBenchmarkFixture.cpp | 4 ++-- .../Prefab/Benchmark/PrefabCreateBenchmarks.cpp | 6 +++--- .../Benchmark/PrefabInstantiateBenchmarks.cpp | 2 +- .../Prefab/Benchmark/PrefabLoadBenchmarks.cpp | 2 +- Code/Legacy/CrySystem/SystemWin32.cpp | 2 +- .../SDKWrapper/AssImpMaterialWrapper.cpp | 2 +- .../Importers/AssImpAnimationImporter.cpp | 4 ++-- .../Importers/AssImpBitangentStreamImporter.cpp | 4 ++-- .../Importers/AssImpBlendShapeImporter.cpp | 8 ++++---- .../Importers/AssImpColorStreamImporter.cpp | 9 ++++----- .../Importers/AssImpMaterialImporter.cpp | 2 +- .../Importers/AssImpTangentStreamImporter.cpp | 4 ++-- .../Importers/AssImpUvMapImporter.cpp | 6 +++--- .../Utilities/AssImpMeshImporterUtilities.cpp | 8 ++++---- .../Code/Source/AWSCoreSystemComponent.cpp | 2 +- .../Attribution/AWSCoreAttributionManager.cpp | 2 +- Gems/AWSMetrics/Code/Source/MetricsManager.cpp | 4 ++-- Gems/AWSMetrics/Code/Source/MetricsQueue.cpp | 2 +- .../AtomFont/Code/Source/FontRenderer.cpp | 4 ++-- .../Code/Source/Family/BlastFamilyImpl.cpp | 2 +- Gems/Blast/Code/Tests/Mocks/BlastMocks.h | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp | 2 +- .../Code/Tests/GradientSignalImageTests.cpp | 8 ++++---- Gems/ImGui/Code/Source/ImGuiManager.cpp | 2 +- .../Code/Source/Shape/ShapeGeometryUtil.cpp | 17 ++++++++--------- .../Editor/Animation/UiAnimViewSequence.cpp | 4 ++-- Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp | 4 ++-- .../LyShine/Code/Source/EditorPropertyTypes.cpp | 3 ++- Gems/LyShine/Code/Source/UiImageComponent.cpp | 12 ++++++------ .../LyShine/Code/Source/UiInteractableState.cpp | 2 +- .../Code/Source/UiParticleEmitterComponent.cpp | 4 ++-- Gems/LyShine/Code/Source/UiTextComponent.cpp | 2 +- Gems/PhysXDebug/Code/Source/SystemComponent.cpp | 4 ++-- 33 files changed, 72 insertions(+), 73 deletions(-) diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp index 7e47fa9569..9925d5bff3 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp @@ -85,7 +85,7 @@ namespace Benchmark void BM_Prefab::CreateEntities(const unsigned int entityCount, AZStd::vector& entities) { - for (int entityIndex = 0; entityIndex < entityCount; ++entityIndex) + for (unsigned int entityIndex = 0; entityIndex < entityCount; ++entityIndex) { AZStd::string entityName = "TestEntity"; entityName = entityName + AZStd::to_string(entityIndex); @@ -101,7 +101,7 @@ namespace Benchmark void BM_Prefab::CreateFakePaths(const unsigned int pathCount) { //setup fake paths - for (int number = 0; number < pathCount; ++number) + for (unsigned int number = 0; number < pathCount; ++number) { AZStd::string path = m_pathString; m_paths.push_back(path + AZStd::to_string(number) + "_" + AZStd::to_string(pathCount)); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp index b809a20944..12efea1cc8 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp @@ -32,7 +32,7 @@ namespace Benchmark state.ResumeTiming(); - for (int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter) + for (unsigned int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter) { newInstances.push_back(m_prefabSystemComponent->CreatePrefab( { entities[instanceCounter] }, @@ -110,7 +110,7 @@ namespace Benchmark AZStd::vector> testInstances; testInstances.resize(numInstancesToAdd); - for (int instanceCounter = 0; instanceCounter < numInstancesToAdd; ++instanceCounter) + for (unsigned int instanceCounter = 0; instanceCounter < numInstancesToAdd; ++instanceCounter) { testInstances[instanceCounter] = (m_prefabSystemComponent->CreatePrefab( { entities[instanceCounter] } @@ -161,7 +161,7 @@ namespace Benchmark state.ResumeTiming(); - for (int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter) + for (unsigned int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter) { nestedInstanceRoot = m_prefabSystemComponent->CreatePrefab( {}, diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp index 3e9f0ab08e..90ff30a30e 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp @@ -33,7 +33,7 @@ namespace Benchmark state.ResumeTiming(); - for (int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter) + for (unsigned int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter) { newInstances[instanceCounter] = m_prefabSystemComponent->InstantiatePrefab(templateToInstantiateId); } diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp index 7e64fa886c..a6c1e27caf 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp @@ -29,7 +29,7 @@ namespace Benchmark state.ResumeTiming(); - for (int templateCounter = 0; templateCounter < numTemplates; ++templateCounter) + for (unsigned int templateCounter = 0; templateCounter < numTemplates; ++templateCounter) { m_prefabLoaderInterface->LoadTemplateFromFile(m_paths[templateCounter]); } diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index 2cc41adc08..3e499f9853 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -410,7 +410,7 @@ void CSystem::debug_GetCallStack(const char** pFunctions, int& nCount) unsigned int numFrames = StackRecorder::Record(frames, nMaxCount, 1); SymbolStorage::StackLine* textLines = (SymbolStorage::StackLine*)AZ_ALLOCA(sizeof(SymbolStorage::StackLine)*nMaxCount); SymbolStorage::DecodeFrames(frames, numFrames, textLines); - for (int i = 0; i < numFrames; i++) + for (unsigned int i = 0; i < numFrames; i++) { pFunctions[i] = textLines[i]; } diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp index c24577a6de..8ea25a2ff0 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp @@ -194,7 +194,7 @@ namespace AZ AZStd::string AssImpMaterialWrapper::GetTextureFileName(MaterialMapType textureType) const { /// Engine currently doesn't support multiple textures. Right now we only use first texture. - int textureIndex = 0; + unsigned int textureIndex = 0; aiString absTexturePath; switch (textureType) { diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp index aadb834aa9..da1db22d5e 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp @@ -612,10 +612,10 @@ namespace AZ ValueToKeyDataMap valueToKeyDataMap; // Key time can be less than zero, normalize to have zero be the lowest time. double keyOffset = 0; - for (int keyIdx = 0; keyIdx < meshMorphAnim->mNumKeys; keyIdx++) + for (unsigned int keyIdx = 0; keyIdx < meshMorphAnim->mNumKeys; keyIdx++) { aiMeshMorphKey& key = meshMorphAnim->mKeys[keyIdx]; - for (int valIdx = 0; valIdx < key.mNumValuesAndWeights; ++valIdx) + for (unsigned int valIdx = 0; valIdx < key.mNumValuesAndWeights; ++valIdx) { int currentValue = key.mValues[valIdx]; KeyData thisKey(key.mWeights[valIdx], key.mTime); diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp index 51e0147599..b9b9af1e65 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp @@ -89,11 +89,11 @@ namespace AZ bitangentStream->SetGenerationMethod(AZ::SceneAPI::DataTypes::TangentGenerationMethod::FromSourceScene); bitangentStream->ReserveContainerSpace(vertexCount); - for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) + for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) { const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]]; - for (int v = 0; v < mesh->mNumVertices; ++v) + for (unsigned int v = 0; v < mesh->mNumVertices; ++v) { if (!mesh->HasTangentsAndBitangents()) { diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp index d139a1c86c..e8eb5ecf68 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp @@ -85,7 +85,7 @@ namespace AZ { int sceneMeshIdx = context.m_sourceNode.GetAssImpNode()->mMeshes[nodeMeshIdx]; const aiMesh* aiMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[sceneMeshIdx]; - for (int animIdx = 0; animIdx < aiMesh->mNumAnimMeshes; animIdx++) + for (unsigned int animIdx = 0; animIdx < aiMesh->mNumAnimMeshes; animIdx++) { aiAnimMesh* aiAnimMesh = aiMesh->mAnimMeshes[animIdx]; animToMeshToAnimMeshIndices[aiAnimMesh->mName.C_Str()].emplace_back(nodeMeshIdx, animIdx); @@ -130,7 +130,7 @@ namespace AZ blendShapeData->ReserveData( aiAnimMesh->mNumVertices, aiAnimMesh->HasTangentsAndBitangents(), uvSetUsedFlags, colorSetUsedFlags); - for (int vertIdx = 0; vertIdx < aiAnimMesh->mNumVertices; ++vertIdx) + for (unsigned int vertIdx = 0; vertIdx < aiAnimMesh->mNumVertices; ++vertIdx) { AZ::Vector3 vertex(AssImpSDKWrapper::AssImpTypeConverter::ToVector3(aiAnimMesh->mVertices[vertIdx])); @@ -184,7 +184,7 @@ namespace AZ } // aiAnimMesh just has a list of positions for vertices. The face indices are on the original mesh. - for (int faceIdx = 0; faceIdx < aiMesh->mNumFaces; ++faceIdx) + for (unsigned int faceIdx = 0; faceIdx < aiMesh->mNumFaces; ++faceIdx) { aiFace face = aiMesh->mFaces[faceIdx]; DataTypes::IBlendShapeData::Face blendFace; @@ -199,7 +199,7 @@ namespace AZ face.mNumIndices); continue; } - for (int idx = 0; idx < face.mNumIndices; ++idx) + for (unsigned int idx = 0; idx < face.mNumIndices; ++idx) { blendFace.vertexIndex[idx] = face.mIndices[idx] + vertexOffset; } diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp index 438e56e8ad..4043f529df 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp @@ -56,7 +56,7 @@ namespace AZ const aiScene* scene = context.m_sourceScene.GetAssImpScene(); // This node has at least one mesh, verify that the color channel counts are the same for all meshes. - const int expectedColorChannels = scene->mMeshes[currentNode->mMeshes[0]]->GetNumColorChannels(); + const unsigned int expectedColorChannels = scene->mMeshes[currentNode->mMeshes[0]]->GetNumColorChannels(); const bool allMeshesHaveSameNumberOfColorChannels = AZStd::all_of(currentNode->mMeshes + 1, currentNode->mMeshes + currentNode->mNumMeshes, [scene, expectedColorChannels](const unsigned int meshIndex) { @@ -80,17 +80,16 @@ namespace AZ const uint64_t vertexCount = GetVertexCountForAllMeshesOnNode(*currentNode, *scene); Events::ProcessingResultCombiner combinedVertexColorResults; - for (int colorSetIndex = 0; colorSetIndex < expectedColorChannels; ++colorSetIndex) + for (unsigned int colorSetIndex = 0; colorSetIndex < expectedColorChannels; ++colorSetIndex) { - AZStd::shared_ptr vertexColors = AZStd::make_shared(); vertexColors->ReserveContainerSpace(vertexCount); - for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) + for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) { const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]]; - for (int v = 0; v < mesh->mNumVertices; ++v) + for (unsigned int v = 0; v < mesh->mNumVertices; ++v) { if (colorSetIndex < mesh->GetNumColorChannels()) { diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp index 4880c8d736..8983c76bac 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp @@ -56,7 +56,7 @@ namespace AZ Events::ProcessingResultCombiner combinedMaterialImportResults; AZStd::unordered_map> materialMap; - for (int idx = 0; idx < context.m_sourceNode.m_assImpNode->mNumMeshes; ++idx) + for (unsigned int idx = 0; idx < context.m_sourceNode.m_assImpNode->mNumMeshes; ++idx) { int meshIndex = context.m_sourceNode.m_assImpNode->mMeshes[idx]; const aiMesh* assImpMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[meshIndex]; diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp index 6f1c364399..fbafd3d24f 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp @@ -91,11 +91,11 @@ namespace AZ tangentStream->SetGenerationMethod(AZ::SceneAPI::DataTypes::TangentGenerationMethod::FromSourceScene); tangentStream->ReserveContainerSpace(vertexCount); - for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) + for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) { const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]]; - for (int v = 0; v < mesh->mNumVertices; ++v) + for (unsigned int v = 0; v < mesh->mNumVertices; ++v) { if (!mesh->HasTangentsAndBitangents()) { diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp index 12e13422cf..fc0ac15244 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp @@ -62,7 +62,7 @@ namespace AZ // so they can be separated by engine code instead. bool foundTextureCoordinates = false; AZStd::array meshesPerTextureCoordinateIndex = {}; - for (int localMeshIndex = 0; localMeshIndex < currentNode->mNumMeshes; ++localMeshIndex) + for (unsigned int localMeshIndex = 0; localMeshIndex < currentNode->mNumMeshes; ++localMeshIndex) { aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[localMeshIndex]]; for (int texCoordIndex = 0; texCoordIndex < meshesPerTextureCoordinateIndex.size(); ++texCoordIndex) @@ -110,7 +110,7 @@ namespace AZ uvMap->ReserveContainerSpace(vertexCount); bool customNameFound = false; AZStd::string name(AZStd::string::format("%s%d", m_defaultNodeName, texCoordIndex)); - for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) + for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex) { const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]]; if(mesh->mTextureCoords[texCoordIndex]) @@ -136,7 +136,7 @@ namespace AZ } } - for (int v = 0; v < mesh->mNumVertices; ++v) + for (unsigned int v = 0; v < mesh->mNumVertices; ++v) { if (mesh->mTextureCoords[texCoordIndex]) { diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp index a9ab292d25..de94018c9b 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp @@ -40,7 +40,7 @@ namespace AZ::SceneAPI::SceneBuilder // This code re-combines them to match previous FBX SDK behavior, // so they can be separated by engine code instead. int vertOffset = 0; - for (int m = 0; m < currentNode->mNumMeshes; ++m) + for (unsigned int m = 0; m < currentNode->mNumMeshes; ++m) { const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[m]]; @@ -50,7 +50,7 @@ namespace AZ::SceneAPI::SceneBuilder assImpMatIndexToLYIndex.insert(AZStd::pair(mesh->mMaterialIndex, lyMeshIndex++)); } - for (int vertIdx = 0; vertIdx < mesh->mNumVertices; ++vertIdx) + for (unsigned int vertIdx = 0; vertIdx < mesh->mNumVertices; ++vertIdx) { AZ::Vector3 vertex(mesh->mVertices[vertIdx].x, mesh->mVertices[vertIdx].y, mesh->mVertices[vertIdx].z); @@ -68,7 +68,7 @@ namespace AZ::SceneAPI::SceneBuilder } } - for (int faceIdx = 0; faceIdx < mesh->mNumFaces; ++faceIdx) + for (unsigned int faceIdx = 0; faceIdx < mesh->mNumFaces; ++faceIdx) { aiFace face = mesh->mFaces[faceIdx]; AZ::SceneAPI::DataTypes::IMeshData::Face meshFace; @@ -82,7 +82,7 @@ namespace AZ::SceneAPI::SceneBuilder face.mNumIndices); continue; } - for (int idx = 0; idx < face.mNumIndices; ++idx) + for (unsigned int idx = 0; idx < face.mNumIndices; ++idx) { meshFace.vertexIndex[idx] = face.mIndices[idx] + vertOffset; } diff --git a/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp b/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp index c24518a4d7..92a5aa493f 100644 --- a/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp +++ b/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp @@ -160,7 +160,7 @@ namespace AWSCore // assigned to a specific CPU starting with the specified CPU. AZ::JobManagerDesc jobManagerDesc{}; AZ::JobManagerThreadDesc threadDesc(m_firstThreadCPU, m_threadPriority, m_threadStackSize); - for (unsigned int i = 0; i < m_threadCount; ++i) + for (int i = 0; i < m_threadCount; ++i) { jobManagerDesc.m_workerThreads.push_back(threadDesc); if (threadDesc.m_cpuId > -1) diff --git a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp index e0b4db9165..85dd1469cb 100644 --- a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp +++ b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp @@ -139,7 +139,7 @@ namespace AWSCore AZStd::chrono::seconds lastSendTimeStamp = AZStd::chrono::seconds(lastSendTimeStampSeconds); AZStd::chrono::seconds secondsSinceLastSend = AZStd::chrono::duration_cast(AZStd::chrono::system_clock::now().time_since_epoch()) - lastSendTimeStamp; - if (secondsSinceLastSend.count() >= delayInSeconds) + if (static_cast(secondsSinceLastSend.count()) >= delayInSeconds) { return true; } diff --git a/Gems/AWSMetrics/Code/Source/MetricsManager.cpp b/Gems/AWSMetrics/Code/Source/MetricsManager.cpp index 5c4d910658..03e31770ee 100644 --- a/Gems/AWSMetrics/Code/Source/MetricsManager.cpp +++ b/Gems/AWSMetrics/Code/Source/MetricsManager.cpp @@ -106,7 +106,7 @@ namespace AWSMetrics AZStd::lock_guard lock(m_metricsMutex); m_metricsQueue.AddMetrics(metricsEvent); - if (m_metricsQueue.GetSizeInBytes() >= m_clientConfiguration->GetMaxQueueSizeInBytes()) + if (m_metricsQueue.GetSizeInBytes() >= static_cast(m_clientConfiguration->GetMaxQueueSizeInBytes())) { // Flush the metrics queue when the accumulated metrics size hits the limit m_waitEvent.release(); @@ -431,7 +431,7 @@ namespace AWSMetrics AZStd::lock_guard lock(m_metricsMutex); m_metricsQueue.AddMetrics(offlineRecords[index]); - if (m_metricsQueue.GetSizeInBytes() >= m_clientConfiguration->GetMaxQueueSizeInBytes()) + if (m_metricsQueue.GetSizeInBytes() >= static_cast(m_clientConfiguration->GetMaxQueueSizeInBytes())) { // Flush the metrics queue when the accumulated metrics size hits the limit m_waitEvent.release(); diff --git a/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp b/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp index ab54fb9e3e..4cc037189a 100644 --- a/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp +++ b/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp @@ -216,7 +216,7 @@ namespace AWSMetrics return false; } - for (int metricsIndex = 0; metricsIndex < doc.Size(); metricsIndex++) + for (rapidjson::SizeType metricsIndex = 0; metricsIndex < doc.Size(); metricsIndex++) { MetricsEvent metrics; if (!metrics.ReadFromJson(doc[metricsIndex])) diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp index 101a506ddc..225b6d5ff6 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp @@ -252,8 +252,8 @@ int AZ::FontRenderer::GetGlyph(GlyphBitmap* glyphBitmap, int* horizontalAdvance, const int textureSlotBufferHeight = glyphBitmap->GetHeight(); // might happen if font characters are too big or cache dimenstions in font.xml is too small "" - const bool charWidthFits = iX + m_glyph->bitmap.width <= textureSlotBufferWidth; - const bool charHeightFits = iY + m_glyph->bitmap.rows <= textureSlotBufferHeight; + const bool charWidthFits = static_cast(iX + m_glyph->bitmap.width) <= textureSlotBufferWidth; + const bool charHeightFits = static_cast(iY + m_glyph->bitmap.rows) <= textureSlotBufferHeight; const bool charFitsInSlot = charWidthFits && charHeightFits; AZ_Error("Font", charFitsInSlot, "Character code %d doesn't fit in font texture; check 'sizeRatio' attribute in font XML or adjust this character's sizing in the font.", characterCode); diff --git a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp index ec4925fe51..2690a12f24 100644 --- a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp +++ b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp @@ -450,7 +450,7 @@ namespace Blast const auto buffer = m_asset.GetAccelerator()->fillDebugRender(-1, mode == DebugRenderAabbTreeSegments); if (buffer.lineCount) { - for (int i = 0; i < buffer.lineCount; ++i) + for (uint32_t i = 0; i < buffer.lineCount; ++i) { auto& line = buffer.lines[i]; AZ::Color color; diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h index 0733862e25..dddd1e275a 100644 --- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h +++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h @@ -562,7 +562,7 @@ namespace Blast public: FakeEntityProvider(uint32_t entityCount) { - for (int i = 0; i < entityCount; ++i) + for (uint32 i = 0; i < entityCount; ++i) { m_entities.push_back(AZStd::make_shared()); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index 833f8a14f3..a6368ac088 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -1555,7 +1555,7 @@ namespace EMotionFX const uint32 geomLODLevel = 0; const uint32 numNodes = mSkeleton->GetNumNodes(); - for (int nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) + for (uint32 nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { // check if this node has a mesh, if not we can skip it Mesh* mesh = GetMesh(geomLODLevel, nodeIndex); diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp index b1aa74c397..ea9a1d380f 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp +++ b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp @@ -116,9 +116,9 @@ namespace UnitTest size_t value = 0; AZStd::hash_combine(value, seed); - for (int x = 0; x < width; ++x) + for (AZ::u32 x = 0; x < width; ++x) { - for (int y = 0; y < height; ++y) + for (AZ::u32 y = 0; y < height; ++y) { AZStd::hash_combine(value, x); AZStd::hash_combine(value, y); @@ -141,9 +141,9 @@ namespace UnitTest const AZ::u8 pixelValue = 255; // Image data should be stored inverted on the y axis relative to our engine, so loop backwards through y. - for (int y = height - 1; y >= 0; --y) + for (int y = static_cast(height) - 1; y >= 0; --y) { - for (int x = 0; x < width; ++x) + for (AZ::u32 x = 0; x < width; ++x) { if ((x == pixelX) && (y == pixelY)) { diff --git a/Gems/ImGui/Code/Source/ImGuiManager.cpp b/Gems/ImGui/Code/Source/ImGuiManager.cpp index ac3247b6a4..427af6d7dc 100644 --- a/Gems/ImGui/Code/Source/ImGuiManager.cpp +++ b/Gems/ImGui/Code/Source/ImGuiManager.cpp @@ -409,7 +409,7 @@ void ImGuiManager::Render() break; case ImGuiResolutionMode::MatchToMaxRenderResolution: - if (backBufferWidth <= static_cast(m_renderResolution.x)) + if (backBufferWidth <= static_cast(m_renderResolution.x)) { renderRes[0] = backBufferWidth; renderRes[1] = backBufferHeight; diff --git a/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp b/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp index cdb97d2702..3b54447fdd 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp @@ -353,10 +353,10 @@ namespace LmbrCentral const AZ::u32 sides, const AZ::u32 segments, const AZ::u32 capSegments, AZ::u32* indices) { - const auto capSegmentTipVerts = capSegments > 0 ? 1 : 0; - const auto totalSegments = segments + capSegments * 2; - const auto numVerts = sides * (totalSegments + 1) + 2 * capSegmentTipVerts; - const auto hasEnds = capSegments > 0; + const AZ::u32 capSegmentTipVerts = capSegments > 0 ? 1 : 0; + const AZ::u32 totalSegments = segments + capSegments * 2; + const AZ::u32 numVerts = sides * (totalSegments + 1) + 2 * capSegmentTipVerts; + const AZ::u32 hasEnds = capSegments > 0; // Start Faces (start point of tube) // Each starting face shares the same vertex at the beginning of the vertex buffer @@ -365,8 +365,7 @@ namespace LmbrCentral // 1 face per side if (hasEnds) { - - for (auto i = 0; i < sides; ++i) + for (AZ::u32 i = 0; i < sides; ++i) { AZ::u32 a = i + 1; AZ::u32 b = a + 1; @@ -383,9 +382,9 @@ namespace LmbrCentral // Middle Faces // 2 triangles per face. // 1 face per side. - for (auto i = 0; i < totalSegments; ++i) + for (AZ::u32 i = 0; i < totalSegments; ++i) { - for (auto j = 0; j < sides; ++j) + for (AZ::u32 j = 0; j < sides; ++j) { // 4 corners for each face // a ------ d @@ -416,7 +415,7 @@ namespace LmbrCentral // 1 face per side if (hasEnds) { - for (auto i = 0; i < sides; ++i) + for (AZ::u32 i = 0; i < sides; ++i) { AZ::u32 a = totalSegments * sides + i + 1; AZ::u32 b = a + 1; diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp index 86554c2004..b4c98c39bf 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp @@ -1093,7 +1093,7 @@ void CUiAnimViewSequence::DeselectAllKeys() CUiAnimViewSequenceNotificationContext context(this); CUiAnimViewKeyBundle selectedKeys = GetSelectedKeys(); - for (int i = 0; i < selectedKeys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < selectedKeys.GetKeyCount(); ++i) { CUiAnimViewKeyHandle keyHandle = selectedKeys.GetKey(i); keyHandle.Select(false); @@ -1237,7 +1237,7 @@ float CUiAnimViewSequence::ClipTimeOffsetForSliding(const float timeOffset) for (pTrackIter = tracks.begin(); pTrackIter != tracks.end(); ++pTrackIter) { CUiAnimViewTrack* pTrack = *pTrackIter; - for (int i = 0; i < pTrack->GetKeyCount(); ++i) + for (unsigned int i = 0; i < pTrack->GetKeyCount(); ++i) { CUiAnimViewKeyHandle keyHandle = pTrack->GetKey(i); diff --git a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp index 1d8de3598e..e46073284b 100644 --- a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp +++ b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp @@ -191,9 +191,9 @@ void SpriteBorderEditor::UpdateSpriteSheetCellInfo(int newNumRows, int newNumCol // Calculate uniformly sized sprite-sheet cell UVs based on the given // row and column cell configuration. - for (int row = 0; row < m_numRows; ++row) + for (unsigned int row = 0; row < m_numRows; ++row) { - for (int col = 0; col < m_numCols; ++col) + for (unsigned int col = 0; col < m_numCols; ++col) { AZ::Vector2 min(col / floatNumCols, row / floatNumRows); AZ::Vector2 max((col + 1) / floatNumCols, (row + 1) / floatNumRows); diff --git a/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp b/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp index 77a9f59732..695412819d 100644 --- a/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp +++ b/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp @@ -17,8 +17,9 @@ LyShine::AZu32ComboBoxVec LyShine::GetEnumSpriteIndexList(AZ::EntityId entityId, int indexCount = 0; EBUS_EVENT_ID_RESULT(indexCount, entityId, UiIndexableImageBus, GetImageIndexCount); + const AZ::u32 indexCountu32 = static_cast(indexCount); - if (indexCount > 0 && (indexMax <= indexCount - 1) && indexMin <= indexMax) + if (indexCount > 0 && (indexMax <= indexCountu32 - 1) && indexMin <= indexMax) { for (AZ::u32 i = indexMin; i <= indexMax; ++i) { diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp index 1e48bdff51..e56d9957b0 100644 --- a/Gems/LyShine/Code/Source/UiImageComponent.cpp +++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp @@ -224,9 +224,9 @@ namespace IDraw2d::Rounding pixelRounding = isPixelAligned ? IDraw2d::Rounding::Nearest : IDraw2d::Rounding::None; float z = 1.0f; int i = 0; - for (int y = 0; y < numY; ++y) + for (uint32 y = 0; y < numY; ++y) { - for (int x = 0; x < numX; x += 1) + for (uint32 x = 0; x < numX; x += 1) { AZ::Vector3 point3(xValues[x], yValues[y], z); point3 = transform * point3; @@ -2030,7 +2030,7 @@ void UiImageComponent::ClipValuesForSlicedLinearFill(uint32 numValues, float* xV float previousPercentage = 0; int previousIndex = startClip; int clampIndex = -1; // to clamp all values greater than m_fillAmount in specified direction. - for (int arrayPos = 1; arrayPos < numValues; ++arrayPos) + for (uint32 arrayPos = 1; arrayPos < numValues; ++arrayPos) { int currentIndex = startClip + arrayPos * clipInc; float thisPercentage = (clipPosition[currentIndex] - clipPosition[startClip]) / totalLength; @@ -2102,7 +2102,7 @@ void UiImageComponent::ClipAndRenderForSlicedRadialFill(uint32 numVertsPerSide, if (m_fillAmount < 0.5f) { // Clips against first half line and then rotating line and adds results to render list. - for (int currentIndex = 0; currentIndex < totalIndices; currentIndex += 3) + for (uint32 currentIndex = 0; currentIndex < totalIndices; currentIndex += 3) { SVF_P2F_C4B_T2F_F4B intermediateVerts[maxTemporaryVerts]; uint16 intermediateIndices[maxTemporaryIndices]; @@ -2118,7 +2118,7 @@ void UiImageComponent::ClipAndRenderForSlicedRadialFill(uint32 numVertsPerSide, else { // Clips against first half line and adds results to render list then clips against the second half line and rotating line and also adds those results to render list. - for (int currentIndex = 0; currentIndex < totalIndices; currentIndex += 3) + for (uint32 currentIndex = 0; currentIndex < totalIndices; currentIndex += 3) { SVF_P2F_C4B_T2F_F4B intermediateVerts[maxTemporaryVerts]; uint16 intermediateIndices[maxTemporaryIndices]; @@ -2201,7 +2201,7 @@ void UiImageComponent::ClipAndRenderForSlicedRadialCornerOrEdgeFill(uint32 numVe int numIndicesToRender = 0; int vertexOffset = 0; - for (int ix = 0; ix < totalIndices; ix += 3) + for (uint32 ix = 0; ix < totalIndices; ix += 3) { int indicesUsed = ClipToLine(verts, &indices[ix], renderVerts, renderIndices, vertexOffset, numIndicesToRender, lineOrigin, lineEnd); numIndicesToRender += indicesUsed; diff --git a/Gems/LyShine/Code/Source/UiInteractableState.cpp b/Gems/LyShine/Code/Source/UiInteractableState.cpp index d3440a9354..7e87782d00 100644 --- a/Gems/LyShine/Code/Source/UiInteractableState.cpp +++ b/Gems/LyShine/Code/Source/UiInteractableState.cpp @@ -616,7 +616,7 @@ UiInteractableStateFont::FontEffectComboBoxVec UiInteractableStateFont::Populate // NOTE: Curently, in order for this to work, when the font is changed we need to do // "RefreshEntireTree" to get the combo box list refreshed. unsigned int numEffects = m_fontFamily ? m_fontFamily->normal->GetNumEffects() : 0; - for (int i = 0; i < numEffects; ++i) + for (unsigned int i = 0; i < numEffects; ++i) { const char* name = m_fontFamily->normal->GetEffectName(i); result.push_back(AZStd::make_pair(i, name)); diff --git a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp index 9668ebf463..a8b678947b 100644 --- a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp +++ b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp @@ -830,7 +830,7 @@ void UiParticleEmitterComponent::Render(LyShine::IRenderGraph* renderGraph) AZ::u32 totalVerticesInserted = 0; // particlesToRender is the max particles we will render, we could render less if some have zero alpha - for (int i = 0; i < particlesToRender; ++i) + for (AZ::u32 i = 0; i < particlesToRender; ++i) { SVF_P2F_C4B_T2F_F4B* firstVertexOfParticle = &m_cachedPrimitive.m_vertices[totalVerticesInserted]; @@ -1827,7 +1827,7 @@ void UiParticleEmitterComponent::ResetParticleBuffers() const int verticesPerParticle = 4; int baseIndex = 0; - for (int i = 0; i < numIndices; i += indicesPerParticle) + for (AZ::u32 i = 0; i < numIndices; i += indicesPerParticle) { m_cachedPrimitive.m_indices[i + 0] = 0 + baseIndex; m_cachedPrimitive.m_indices[i + 1] = 1 + baseIndex; diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp index d95b15622b..87eb4524a2 100644 --- a/Gems/LyShine/Code/Source/UiTextComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp @@ -3527,7 +3527,7 @@ UiTextComponent::FontEffectComboBoxVec UiTextComponent::PopulateFontEffectList() if (m_font) { unsigned int numEffects = m_font->GetNumEffects(); - for (int i = 0; i < numEffects; ++i) + for (unsigned int i = 0; i < numEffects; ++i) { const char* name = m_font->GetEffectName(i); result.push_back(AZStd::make_pair(i, name)); diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 7e1c3630cb..992a2a3697 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -697,7 +697,7 @@ namespace PhysXDebug if (GetCurrentPxScene()) { // Reserve vector capacity - const int numTriangles = rb.getNbTriangles(); + const physx::PxU32 numTriangles = static_cast(rb.getNbTriangles()); m_trianglePoints.reserve(numTriangles * 3); m_triangleColors.reserve(numTriangles * 3); @@ -731,7 +731,7 @@ namespace PhysXDebug if (GetCurrentPxScene()) { - const int numLines = rb.getNbLines(); + const physx::PxU32 numLines = static_cast(rb.getNbLines()); // Reserve vector capacity m_linePoints.reserve(numLines * 2); From eb3e0b0998463b52e877ab4d2dd63d3c72dfe1b6 Mon Sep 17 00:00:00 2001 From: pappeste Date: Thu, 24 Jun 2021 18:40:11 -0700 Subject: [PATCH 137/251] updates after merging development Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp | 2 +- .../SceneBuilder/Importers/AssImpAnimationImporter.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp index 9d35081895..54e53a6ebc 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp @@ -33,7 +33,7 @@ namespace Benchmark AZStd::vector> spawnables; spawnables.reserve(numSpawnables); - for (int spwanableCounter = 0; spwanableCounter < numSpawnables; ++spwanableCounter) + for (unsigned int spwanableCounter = 0; spwanableCounter < numSpawnables; ++spwanableCounter) { AZStd::unique_ptr spawnable = AZStd::make_unique(); AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(*spawnable, prefabDom); diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp index da1db22d5e..150a50138e 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp @@ -445,11 +445,11 @@ namespace AZ AZStd::unordered_set boneList; - for (int meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) + for (unsigned int meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) { aiMesh* mesh = scene->mMeshes[meshIndex]; - for (int boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex) + for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex) { aiBone* bone = mesh->mBones[boneIndex]; From 9f18b6f1be67a6cfadce79047d8a8d77e8adaa74 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 19:58:46 -0700 Subject: [PATCH 138/251] fixes for new code Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../SceneBuilder/Importers/AssImpImporterUtilities.cpp | 4 ++-- Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp index 81feff7d69..861d6dd85c 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp @@ -105,7 +105,7 @@ namespace AZ nodesWithNoMesh.emplace(currentNode->mName.C_Str()); } - for (int childIndex = 0; childIndex < currentNode->mNumChildren; ++childIndex) + for (unsigned int childIndex = 0; childIndex < currentNode->mNumChildren; ++childIndex) { queue.push(currentNode->mChildren[childIndex]); } @@ -176,7 +176,7 @@ namespace AZ return true; } - for (int childIndex = 0; childIndex < node->mNumChildren; ++childIndex) + for (unsigned int childIndex = 0; childIndex < node->mNumChildren; ++childIndex) { const aiNode* childNode = node->mChildren[childIndex]; if (RecursiveHasChildBone(childNode, boneByNameMap)) diff --git a/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp index e9f5d04314..b45cee6948 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp @@ -352,7 +352,7 @@ int UiAVEventsModel::GetNumberOfUsageAndFirstTimeUsed(const char* eventName, flo { CUiAnimViewTrack* pTrack = tracks.GetTrack(currentTrack); - for (int currentKey = 0; currentKey < pTrack->GetKeyCount(); ++currentKey) + for (unsigned int currentKey = 0; currentKey < pTrack->GetKeyCount(); ++currentKey) { CUiAnimViewKeyHandle keyHandle = pTrack->GetKey(currentKey); From 1c181af94e0c3dc637efca8822cb9dbb5f22b11d Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 5 Aug 2021 22:36:43 -0500 Subject: [PATCH 139/251] fixing problems with document tab management Signed-off-by: Guthrie Adams --- .../Window/AtomToolsMainWindow.h | 8 +- .../Source/Window/AtomToolsMainWindow.cpp | 32 ++++- .../Source/Window/MaterialEditorWindow.cpp | 113 +++++----------- .../Code/Source/Window/MaterialEditorWindow.h | 2 - .../Window/ShaderManagementConsoleWindow.cpp | 123 ++++++------------ .../Window/ShaderManagementConsoleWindow.h | 6 +- 6 files changed, 106 insertions(+), 178 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h index 141fa1cad2..82444246fd 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -39,11 +39,13 @@ namespace AtomToolsFramework AZStd::vector GetDockWidgetNames() const override; virtual void CreateMenu(); - virtual void CreateTabBar(); - virtual void AddTabForDocumentId(const AZ::Uuid& documentId); + + 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); + 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(); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp index af4c3571e7..f6e56b1ff6 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -133,7 +133,8 @@ namespace AtomToolsFramework }); } - void AtomToolsMainWindow::AddTabForDocumentId(const AZ::Uuid& documentId) + 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. @@ -149,6 +150,16 @@ namespace AtomToolsFramework 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) @@ -167,12 +178,27 @@ namespace AtomToolsFramework } } - void AtomToolsMainWindow::UpdateTabForDocumentId(const AZ::Uuid& documentId) + 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()) { - return; + // 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; + } + } } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index f93edfd275..9ead0d4a50 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -183,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; @@ -246,7 +263,13 @@ namespace MaterialEditor 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) @@ -264,7 +287,13 @@ 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); const QString status = QString("Material closed: %1").arg(documentPath); @@ -490,82 +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; - } - - AtomToolsMainWindow::AddTabForDocumentId(documentId); - - // 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); - - // 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::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; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 9a713426ea..43151b9c03 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -56,8 +56,6 @@ namespace MaterialEditor void CreateMenu() override; void CreateTabBar() override; - void AddTabForDocumentId(const AZ::Uuid& documentId) override; - void UpdateTabForDocumentId(const AZ::Uuid& documentId) override; QString GetDocumentPath(const AZ::Uuid& documentId) const; void OpenTabContextMenu() override; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 2cc4e67ba0..0a082f3c33 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -86,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; @@ -133,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) @@ -151,7 +175,13 @@ 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::CreateMenu() @@ -291,86 +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; - } - - AtomToolsMainWindow::AddTabForDocumentId(documentId); - - // 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); - - // 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::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; - } - } - } - } - void ShaderManagementConsoleWindow::OpenTabContextMenu() { const QTabBar* tabBar = m_tabWidget->tabBar(); @@ -427,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; @@ -446,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())); @@ -474,6 +425,8 @@ namespace ShaderManagementConsole model->setItem(variantIndex, optionIndex, item); } } + + return model; } } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index 57bd11cb0a..aae31d1000 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -52,10 +52,6 @@ namespace ShaderManagementConsole void CreateMenu() override; void CreateTabBar() override; - - void AddTabForDocumentId(const AZ::Uuid& documentId) override; - void UpdateTabForDocumentId(const AZ::Uuid& documentId) override; - void OpenTabContextMenu() override; void SelectDocumentForTab(const int tabIndex); @@ -64,7 +60,7 @@ namespace ShaderManagementConsole void closeEvent(QCloseEvent* closeEvent) override; - void CreateDocumentContent(const AZ::Uuid& documentId, QStandardItemModel* model); + QStandardItemModel* CreateDocumentContent(const AZ::Uuid& documentId); ShaderManagementConsoleToolBar* m_toolBar = nullptr; From c85e5a688668da4e2c1a4aff6564a0ca8d5fded1 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 5 Aug 2021 21:49:00 -0700 Subject: [PATCH 140/251] Some more build fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Platform/Android/GridMate/Carrier/Utils_Android.cpp | 4 ++-- .../Platform/Linux/GridMate/Session/LANSession_Linux.cpp | 2 ++ .../GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp | 2 ++ Code/Legacy/CrySystem/LocalizedStringManager.cpp | 4 ++-- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp index 87bb0c3cda..f48e2c2da8 100644 --- a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp +++ b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp @@ -18,9 +18,9 @@ namespace GridMate { - string Utils::GetMachineAddress(int familyType) + AZStd::string Utils::GetMachineAddress(int familyType) { - string machineName; + AZStd::string machineName; struct RTMRequest { nlmsghdr m_msghdr; diff --git a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp index 05fb56dfc1..ac887bb624 100644 --- a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp +++ b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp @@ -8,6 +8,8 @@ #include +#include + namespace GridMate { namespace Platform diff --git a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp index 05fb56dfc1..ac887bb624 100644 --- a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp +++ b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp @@ -8,6 +8,8 @@ #include +#include + namespace GridMate { namespace Platform diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp index 6013b44f92..68a8a6659b 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp +++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp @@ -2337,8 +2337,8 @@ void InternalFormatStringMessage(AZStd::string& outString, const AZStd::string& static const char tokens2[3] = { token, token, '\0' }; int maxArgUsed = 0; - int lastPos = 0; - int curPos = 0; + size_t lastPos = 0; + size_t curPos = 0; const int sourceLen = static_cast(sString.length()); while (true) { From f2c482b03dc672c20d59f3b77524e1c107263d92 Mon Sep 17 00:00:00 2001 From: Nemerle Date: Fri, 6 Aug 2021 13:02:23 +0200 Subject: [PATCH 141/251] Fixes for incorrect nullptr placement. Incorrect DataElement overload getting called in AndroidSplashscreens::Reflect Signed-off-by: Nemerle --- Code/Editor/Lib/Tests/test_Main.cpp | 2 +- .../Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Editor/Lib/Tests/test_Main.cpp b/Code/Editor/Lib/Tests/test_Main.cpp index 4faf68181e..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: - ~EditorLibTestEnvironment() override {} + ~EditorLibTestEnvironment() override = default; protected: void SetupEnvironment() override diff --git a/Code/Editor/Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp b/Code/Editor/Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp index fe73253805..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(nullptr, &AndroidSplashscreens::m_landscapeSplashscreens) - ->DataElement(nullptr, &AndroidSplashscreens::m_portraitSplashscreens) + ->DataElement(AZ::Edit::UIHandlers::Default, &AndroidSplashscreens::m_landscapeSplashscreens) + ->DataElement(AZ::Edit::UIHandlers::Default, &AndroidSplashscreens::m_portraitSplashscreens) ; } } From 6e59b1f519ca27c59e61e09dd66152470610c5e0 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Fri, 6 Aug 2021 10:30:57 -0400 Subject: [PATCH 142/251] Remove include of deleted file Signed-off-by: Yuriy Toporovskyy --- Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp | 1 - Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp | 1 - Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp | 1 - 3 files changed, 3 deletions(-) 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/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 From ae9d15c977f1394f5783dd76dadaa407031bbd28 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 6 Aug 2021 09:59:35 -0700 Subject: [PATCH 143/251] Mac/iOS fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp index 5555704040..5b2d2af34f 100644 --- a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp +++ b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp @@ -29,20 +29,19 @@ namespace AZ return errno; } - void ComposeMutexName(char* dest, size_t length, const char* name) + void ComposeName(char* dest, size_t length, const char* name, const char* suffix) { - azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name)); - // sem_open doesn't support paths bigger than 31, so call it s_Mtx. // While this is enough for Profiler, maybe the code should be smarter // and trim the name instead - azsnprintf(dest, length, "/tmp/%s_Mtx", name); + azsnprintf(dest, length, "/tmp/%s_%s", name, suffix); } SharedMemory_Common::CreateResult SharedMemory_Mac::Create(const char* name, unsigned int size, bool openIfCreated) { char fullName[256]; - ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name); + azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name)); + ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Mtx"); m_globalMutex = sem_open(fullName, O_CREAT | O_EXCL, 0600, 1); int error = errno; @@ -59,7 +58,7 @@ namespace AZ } // Create the file mapping. - azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name); + ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Data"); m_mapHandle = shm_open(fullName, O_RDWR | O_CREAT | O_EXCL, 0600); error = errno; if (error == EEXIST) @@ -80,7 +79,8 @@ namespace AZ bool SharedMemory_Mac::Open(const char* name) { char fullName[256]; - ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name); + azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name)); + ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Mtx"); m_globalMutex = sem_open(fullName, 0); AZ_Warning("AZSystem", m_globalMutex != nullptr, "Failed to open OS mutex [%s]\n", m_name); @@ -90,7 +90,7 @@ namespace AZ return false; } - azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name); + ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Data"); m_mapHandle = shm_open(fullName, O_RDWR, 0600); if (m_mapHandle == -1) { From 8adf8fd7a11309bc4388ab5d63538a1b6d8bfbd9 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 6 Aug 2021 10:00:58 -0700 Subject: [PATCH 144/251] PR comments Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/std/string/conversions.h | 8 ++++---- .../Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index 473c327143..c5c9b29cdb 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -338,9 +338,9 @@ namespace AZStd if (srcLen > 0) { char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen); - if (endStr < (dest + destSize) && *(endStr - 1) != '\0') + if (endStr < (dest + destSize)) { - *endStr = '\0'; // copy null terminator + *endStr = '\0'; // null terminator } } } @@ -495,9 +495,9 @@ namespace AZStd if (srcLen > 0) { wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen); - if (endWStr < (dest + destSize) && *(endWStr - 1) != '\0') + if (endWStr < (dest + destSize)) { - *endWStr = '\0'; // copy null terminator + *endWStr = '\0'; // null terminator } } } diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp index 20c126f7a8..d9149bdb44 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp @@ -31,6 +31,7 @@ namespace AZ SharedMemory_Common::CreateResult SharedMemory_Windows::Create(const char* name, unsigned int size, bool openIfCreated) { + azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name)); AZStd::fixed_wstring<256> fullName; ComposeName(fullName, name, L"Mutex"); @@ -67,6 +68,7 @@ namespace AZ bool SharedMemory_Windows::Open(const char* name) { + azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name)); AZStd::fixed_wstring<256> fullName; ComposeName(fullName, name, L"Mutex"); From 03cf71b12d7322ac15e6dbcf9a00cdaef4e8ecea Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 6 Aug 2021 10:01:20 -0700 Subject: [PATCH 145/251] android fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Platform/Android/GridMate/Carrier/Utils_Android.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp index f48e2c2da8..75259fbe64 100644 --- a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp +++ b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp @@ -67,7 +67,7 @@ namespace GridMate char address[INET6_ADDRSTRLEN] = { 0 }; bool isLoopback = false; - string devname; + AZStd::string devname; for (int rtattrlen = IFA_PAYLOAD(nlmp); RTA_OK(rtatp, rtattrlen); rtatp = RTA_NEXT(rtatp, rtattrlen)) { if (rtatp->rta_type == IFA_ADDRESS) From db942e2cf5b70bcf63992ba5631a8a086d534307 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 6 Aug 2021 10:36:53 -0700 Subject: [PATCH 146/251] addresses PR comments Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/ViewportTitleDlg.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp index cbf2958eea..b9c86bf72b 100644 --- a/Code/Editor/ViewportTitleDlg.cpp +++ b/Code/Editor/ViewportTitleDlg.cpp @@ -449,21 +449,21 @@ void CViewportTitleDlg::AddFOVMenus(QMenu* menu, std::function call if (!customPresets.empty()) { - for (size_t i = 0; i < customPresets.size(); ++i) + for (const QString& customPreset : customPresets) { - if (customPresets[static_cast(i)].isEmpty()) + if (customPreset.isEmpty()) { break; } float fov = gSettings.viewports.fDefaultFov; bool ok; - float f = customPresets[static_cast(i)].toDouble(&ok); + float f = customPreset.toDouble(&ok); if (ok) { fov = std::max(1.0f, f); fov = std::min(120.0f, f); - QAction* action = menu->addAction(customPresets[static_cast(i)]); + QAction* action = menu->addAction(customPreset); connect(action, &QAction::triggered, action, [fov, callback](){ callback(fov); }); } } @@ -535,15 +535,15 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::functionaddSeparator(); - for (size_t i = 0; i < customPresets.size(); ++i) + for (const QString& customPreset : customPresets) { - if (customPresets[static_cast(i)].isEmpty()) + if (customPreset.isEmpty()) { break; } static QRegularExpression regex(QStringLiteral("^(\\d+):(\\d+)$")); - QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]); + QRegularExpressionMatch matches = regex.match(customPreset); if (matches.hasMatch()) { bool ok; @@ -551,7 +551,7 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::functionaddAction(customPresets[static_cast(i)]); + QAction* action = menu->addAction(customPreset); connect(action, &QAction::triggered, action, [width, height, callback]() {callback(width, height); }); } } @@ -666,15 +666,15 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::functionaddSeparator(); - for (size_t i = 0; i < customPresets.size(); ++i) + for (const QString& customPreset : customPresets) { - if (customPresets[static_cast(i)].isEmpty()) + if (customPreset.isEmpty()) { break; } static QRegularExpression regex(QStringLiteral("^(\\d+) x (\\d+)$")); - QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]); + QRegularExpressionMatch matches = regex.match(customPreset); if (matches.hasMatch()) { bool ok; @@ -682,7 +682,7 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::functionaddAction(customPresets[static_cast(i)]); + QAction* action = menu->addAction(customPreset); connect(action, &QAction::triggered, action, [width, height, callback](){ callback(width, height); }); } } From d7c1185dc23d42e7a535c5977aa1ee568d5f28ab Mon Sep 17 00:00:00 2001 From: John Date: Fri, 6 Aug 2021 20:09:53 +0100 Subject: [PATCH 147/251] Add previously approved changes. Signed-off-by: John --- .../Code/Source/TestImpactConsoleMain.cpp | 89 ++-- ...tImpactConsoleTestSequenceEventHandler.cpp | 143 ++++--- ...estImpactConsoleTestSequenceEventHandler.h | 73 ++-- .../TestImpactClientFailureReport.h | 125 ------ .../TestImpactClientSequenceReport.h | 240 +++++++++++ .../TestImpactClientTestRun.h | 105 ++++- .../TestImpactClientTestSelection.h | 1 + .../TestImpactFramework/TestImpactRuntime.h | 74 ++-- .../TestEngine/TestImpactTestEngine.cpp | 6 +- .../Source/TestEngine/TestImpactTestEngine.h | 6 +- .../Source/TestImpactClientFailureReport.cpp | 120 ------ .../Source/TestImpactClientSequenceReport.cpp | 312 ++++++++++++++ .../Code/Source/TestImpactClientTestRun.cpp | 100 ++++- .../Runtime/Code/Source/TestImpactRuntime.cpp | 391 +++++++++++++----- .../Code/Source/TestImpactRuntimeUtils.cpp | 12 +- .../Code/Source/TestImpactRuntimeUtils.h | 76 ++-- .../testimpactframework_runtime_files.cmake | 5 +- 17 files changed, 1283 insertions(+), 595 deletions(-) delete mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientFailureReport.h create mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h delete mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientFailureReport.cpp create mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp index 5788da5b2b..8027649a44 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp @@ -77,7 +77,6 @@ namespace TestImpact //! 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) @@ -94,44 +93,30 @@ namespace TestImpact { if (options.GetTestSequenceType() == TestSequenceType::ImpactAnalysis) { - auto [selectedResult, discardedResult] = runtime.SafeImpactAnalysisTestSequence( + auto safeImpactAnalysisSequenceReport = 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; - } + SafeImpactAnalysisTestSequenceStartCallback, + SafeImpactAnalysisTestSequenceCompleteCallback, + TestRunCompleteCallback); + + result = safeImpactAnalysisSequenceReport.GetResult(); } 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( + auto sequenceReport = runtime.RegularTestSequence( options.GetTestTargetTimeout(), options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); + TestSequenceStartCallback, + TestSequenceCompleteCallback, + TestRunCompleteCallback); + + result = sequenceReport.GetResult(); } else { @@ -153,18 +138,20 @@ namespace TestImpact { throw(Exception("Unexpected sequence type")); } - - result = runtime.ImpactAnalysisTestSequence( + + auto impactAnalysisSequenceReport = runtime.ImpactAnalysisTestSequence( changeList.value(), options.GetTestPrioritizationPolicy(), dynamicDependencyMapPolicy, options.GetTestTargetTimeout(), options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); - } + ImpactAnalysisTestSequenceStartCallback, + ImpactAnalysisTestSequenceCompleteCallback, + TestRunCompleteCallback); + result = impactAnalysisSequenceReport.GetResult(); + } + return GetReturnCodeForTestSequenceResult(result); }; @@ -217,53 +204,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( + const auto sequenceReport = runtime.RegularTestSequence( options.GetTestTargetTimeout(), options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); + TestSequenceStartCallback, + TestSequenceCompleteCallback, + TestRunCompleteCallback); - return GetReturnCodeForTestSequenceResult(result); + return GetReturnCodeForTestSequenceResult(sequenceReport.GetResult()); } case TestSequenceType::Seed: { - const auto result = runtime.SeededTestSequence( + const auto sequenceReport = runtime.SeededTestSequence( options.GetTestTargetTimeout(), options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); + TestSequenceStartCallback, + TestSequenceCompleteCallback, + TestRunCompleteCallback); - return GetReturnCodeForTestSequenceResult(result); + return GetReturnCodeForTestSequenceResult(sequenceReport.GetResult()); } 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( + const auto sequenceReport = runtime.SeededTestSequence( options.GetTestTargetTimeout(), options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); + TestSequenceStartCallback, + TestSequenceCompleteCallback, + TestRunCompleteCallback); - return GetReturnCodeForTestSequenceResult(result); + return GetReturnCodeForTestSequenceResult(sequenceReport.GetResult()); } } 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..da7052933c 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp @@ -32,72 +32,73 @@ 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.GetExecutionFailureTests().empty() || + !testRunReport.GetFailingTests().empty() || + !testRunReport.GetTimedOutTests().empty() || + !testRunReport.GetUnexecutedTests().empty()) { std::cout << ":\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetTestRunFailures().size() + << testRunReport.GetFailingTests().size() << ResetColor().c_str() << " test failures\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetExecutionFailures().size() + << testRunReport.GetExecutionFailureTests().size() << ResetColor().c_str() << " execution failures\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetTimedOutTests().size() + << testRunReport.GetTimedOutTests().size() << ResetColor().c_str() << " test timeouts\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetUnexecutedTests().size() + << testRunReport.GetUnexecutedTests().size() << ResetColor().c_str() << " unexecuted tests\n"; - if (!failureReport.GetTestRunFailures().empty()) + if (!testRunReport.GetFailingTests().empty()) { std::cout << "\nTest failures:\n"; - for (const auto& testRunFailure : failureReport.GetTestRunFailures()) + for (const auto& testRunFailure : testRunReport.GetFailingTests()) { - std::cout << " " << testRunFailure.GetTargetName().c_str(); for (const auto& testCaseFailure : testRunFailure.GetTestCaseFailures()) { - std::cout << "." << testCaseFailure.GetName().c_str(); for (const auto& testFailure : testCaseFailure.GetTestFailures()) { - std::cout << "." << testFailure.GetName().c_str() << "\n"; + std::cout << " " + << testRunFailure.GetTargetName().c_str() + << "." << testCaseFailure.GetName().c_str() + << "." << testFailure.GetName().c_str() << "\n"; } } } } - if (!failureReport.GetExecutionFailures().empty()) + if (!testRunReport.GetExecutionFailureTests().empty()) { std::cout << "\nExecution failures:\n"; - for (const auto& executionFailure : failureReport.GetExecutionFailures()) + for (const auto& executionFailure : testRunReport.GetExecutionFailureTests()) { std::cout << " " << executionFailure.GetTargetName().c_str() << "\n"; std::cout << executionFailure.GetCommandString().c_str() << "\n"; } } - if (!failureReport.GetTimedOutTests().empty()) + if (!testRunReport.GetTimedOutTests().empty()) { std::cout << "\nTimed out tests:\n"; - for (const auto& testTimeout : failureReport.GetTimedOutTests()) + for (const auto& testTimeout : testRunReport.GetTimedOutTests()) { std::cout << " " << testTimeout.GetTargetName().c_str() << "\n"; } } - if (!failureReport.GetUnexecutedTests().empty()) + if (!testRunReport.GetUnexecutedTests().empty()) { std::cout << "\nUnexecuted tests:\n"; - for (const auto& unexecutedTest : failureReport.GetUnexecutedTests()) + for (const auto& unexecutedTest : testRunReport.GetUnexecutedTests()) { std::cout << " " << unexecutedTest.GetTargetName().c_str() << "\n"; } @@ -105,50 +106,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 +149,45 @@ namespace TestImpact draftedTests.size()); } - // TestSequenceCompleteCallback - void TestSequenceEventHandler::operator()( - Client::SequenceFailure&& failureReport, - AZStd::chrono::milliseconds duration) + void TestSequenceCompleteCallback(const Client::SequenceReport& 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"; + } + + void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& sequenceReport) + { + std::cout << "Selected test run:\n"; + 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"; } - // SafeTestSequenceCompleteCallback - void TestSequenceEventHandler::operator()( - Client::SequenceFailure&& selectedFailureReport, - Client::SequenceFailure&& discardedFailureReport, - AZStd::chrono::milliseconds selectedDuration, - AZStd::chrono::milliseconds discaredDuration) + void SafeImpactAnalysisTestSequenceCompleteCallback(const Client::SafeImpactAnalysisSequenceReport& sequenceReport) { std::cout << "Selected test run:\n"; - Output::FailureReport(selectedFailureReport, selectedDuration); + 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::TestRun& 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 +214,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..ff757b2d5a 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,33 @@ namespace TestImpact { namespace Console { - //! Event handler for all test sequence types. - class TestSequenceEventHandler - { - public: - explicit TestSequenceEventHandler(SuiteType suiteFilter); - - //! TestSequenceStartCallback. - void operator()(Client::TestRunSelection&& selectedTests); - - //! ImpactAnalysisTestSequenceStartCallback. - void operator()( - Client::TestRunSelection&& selectedTests, - AZStd::vector&& discardedTests, - AZStd::vector&& draftedTests); - - //! SafeImpactAnalysisTestSequenceStartCallback. - void operator()( - Client::TestRunSelection&& selectedTests, - Client::TestRunSelection&& discardedTests, - AZStd::vector&& draftedTests); - - //! TestSequenceCompleteCallback. - void operator()( - Client::SequenceFailure&& failureReport, - AZStd::chrono::milliseconds duration); - - //! SafeTestSequenceCompleteCallback. - void operator()( - Client::SequenceFailure&& selectedFailureReport, - Client::SequenceFailure&& discardedFailureReport, - AZStd::chrono::milliseconds selectedDuration, - AZStd::chrono::milliseconds discaredDuration); - - //! TestRunCompleteCallback. - void operator()(Client::TestRun&& test); - - private: - void ClearState(); - - SuiteType m_suiteFilter; - size_t m_numTests = 0; - size_t m_numTestsComplete = 0; - }; + //! Handler for TestSequenceStartCallback event. + void TestSequenceStartCallback(SuiteType suiteType, const Client::TestRunSelection& selectedTests); + + //! Handler for TestSequenceStartCallback event. + void ImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const AZStd::vector& discardedTests, + const AZStd::vector& draftedTests); + + //! Handler for SafeImpactAnalysisTestSequenceStartCallback event. + void SafeImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const Client::TestRunSelection& discardedTests, + const AZStd::vector& draftedTests); + + //! Handler for TestSequenceCompleteCallback event. + void TestSequenceCompleteCallback(const Client::SequenceReport& sequenceReport); + + //! Handler for ImpactAnalysisTestSequenceCompleteCallback event. + void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& sequenceReport); + + //! Handler for SafeImpactAnalysisTestSequenceCompleteCallback event. + void SafeImpactAnalysisTestSequenceCompleteCallback(const Client::SafeImpactAnalysisSequenceReport& sequenceReport); + + //! Handler for TestRunCompleteCallback event. + void TestRunCompleteCallback(const Client::TestRun& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns); } // namespace Console } // namespace TestImpact 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..73f3827fae --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h @@ -0,0 +1,240 @@ +/* + * 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 TestImpact +{ + namespace Client + { + //! 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 passingTests The set of test runs that executed successfully with no failing tests. + //! @param failing tests The set of test runs that executed successfully but had one or more failing tests. + //! @param executionFailureTests The set of test runs that failed to execute. + //! @param timedOutTests The set of test runs that executed successfully but were terminated prematurely due to timing out. + //! @param unexecutedTests 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&& passingTests, + AZStd::vector&& failingTests, + AZStd::vector&& executionFailureTests, + AZStd::vector&& timedOutTests, + AZStd::vector&& unexecutedTests); + + //! 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 number of passing test runs. + size_t GetNumPassingTests() const; + + //! Returns the number of failing test runs. + size_t GetNumFailingTests() const; + + //! Returns the number of timed out test runs. + size_t GetNumTimedOutTests() const; + + //! Returns the number of unexecuted test runs. + size_t GetNumUnexecutedTests() const; + + //! Returns the set of test runs that executed successfully with no failing tests. + const AZStd::vector& GetPassingTests() const; + + //! Returns the set of test runs that executed successfully but had one or more failing tests. + const AZStd::vector& GetFailingTests() const; + + //! Returns the set of test runs that failed to execute. + const AZStd::vector& GetExecutionFailureTests() const; + + //! Returns the set of test runs that executed successfully but were terminated prematurely due to timing out. + const AZStd::vector& GetTimedOutTests() const; + + //! Returns the set of test runs that were queued up for execution but did not get the opportunity to execute. + const AZStd::vector& GetUnexecutedTests() const; + private: + TestSequenceResult m_result; + AZStd::chrono::high_resolution_clock::time_point m_startTime; + AZStd::chrono::milliseconds m_duration; + AZStd::vector m_passingTests; + AZStd::vector m_failingTests; + AZStd::vector m_executionFailureTests; + AZStd::vector m_timedOutTests; + AZStd::vector m_unexecutedTests; + }; + + //! Report detailing a test run sequence of selected tests. + class SequenceReport + { + public: + //! Constructs the report for a sequence of selected tests. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTests The target names of the selected tests. + //! @param selectedTestRunReport The report for the set of selected test runs. + SequenceReport(SuiteType suiteType, const TestRunSelection& selectedTests, TestRunReport&& selectedTestRunReport); + + //! Returns the tests selected for running in the sequence. + TestRunSelection GetSelectedTests() const; + + //! Returns the report for the selected test runs. + TestRunReport GetSelectedTestRunReport() const; + + //! Returns the start time of the sequence. + AZStd::chrono::high_resolution_clock::time_point GetStartTime() const; + + //! Returns the end time of the sequence. + AZStd::chrono::high_resolution_clock::time_point GetEndTime() const; + + //! Returns the result of the sequence. + virtual TestSequenceResult GetResult() const; + + //! Returns the entire duration the sequence took from start to finish. + virtual AZStd::chrono::milliseconds GetDuration() const; + + //! Get the total number of tests in the sequence that passed. + virtual size_t GetTotalNumPassingTests() const; + + //! Get the total number of tests in the sequence that contain one or more test failures. + virtual size_t GetTotalNumFailingTests() const; + + //! Get the total number of tests in the sequence that timed out whilst in flight. + virtual size_t GetTotalNumTimedOutTests() const; + + //! Get the total number of tests in the sequence that were queued for execution but did not get the oppurtunity to execute. + virtual size_t GetTotalNumUnexecutedTests() const; + + private: + SuiteType m_suite; + TestRunSelection m_selectedTests; + TestRunReport m_selectedTestRunReport; + }; + + //! Report detailing a test run sequence of selected and drafted tests. + class DraftingSequenceReport + : public SequenceReport + { + public: + //! Constructs the report for a sequence of selected and drafted tests. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTests The target names of the selected tests. + //! @param draftedTests The target names of the drafted tests. + //! @param selectedTestRunReport The report for the set of selected test runs. + //! @param draftedTestRunReport The report for the set of drafted test runs. + DraftingSequenceReport( + SuiteType suiteType, + const TestRunSelection& selectedTests, + const AZStd::vector& draftedTests, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport); + + // SequenceReport overrides ... + TestSequenceResult GetResult() const override; + AZStd::chrono::milliseconds GetDuration() const override; + size_t GetTotalNumPassingTests() const override; + size_t GetTotalNumFailingTests() const override; + size_t GetTotalNumTimedOutTests() const override; + size_t GetTotalNumUnexecutedTests() const override; + + //! Returns the tests drafted for running in the sequence. + const AZStd::vector& GetDraftedTests() const; + + //! Returns the report for the drafted test runs. + TestRunReport GetDraftedTestRunReport() const; + + private: + AZStd::vector m_draftedTests; + TestRunReport m_draftedTestRunReport; + }; + + //! Report detailing an impact analysis sequence of selected, discarded and drafted tests. + class ImpactAnalysisSequenceReport + : public DraftingSequenceReport + { + public: + //! Constructs the report for a sequence of selected and drafted tests. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTests The target names of the selected tests. + //! @param discardedTests The target names of the discarded tests. + //! @param draftedTests The target names of the drafted tests. + //! @param selectedTestRunReport The report for the set of selected test runs. + //! @param draftedTestRunReport The report for the set of drafted test runs. + ImpactAnalysisSequenceReport( + SuiteType suiteType, + const TestRunSelection& selectedTests, + const AZStd::vector& discardedTests, + const AZStd::vector& draftedTests, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport); + + //! Returns the tests discarded from running in the sequence. + const AZStd::vector& GetDiscardedTests() const; + private: + AZStd::vector m_discardedTests; + }; + + //! Report detailing an impact analysis sequence of selected, discarded and drafted tests. + class SafeImpactAnalysisSequenceReport + : public DraftingSequenceReport + { + public: + //! Constructs the report for a sequence of selected and drafted tests. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTests The target names of the selected tests. + //! @param discardedTests The target names of the discarded tests. + //! @param draftedTests The target names of the drafted tests. + //! @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( + SuiteType suiteType, + const TestRunSelection& selectedTests, + const TestRunSelection& discardedTests, + const AZStd::vector& draftedTests, + TestRunReport&& selectedTestRunReport, + TestRunReport&& discardedTestRunReport, + TestRunReport&& draftedTestRunReport); + + // DraftingSequenceReport overrides ... + TestSequenceResult GetResult() const override; + AZStd::chrono::milliseconds GetDuration() const override; + size_t GetTotalNumPassingTests() const override; + size_t GetTotalNumFailingTests() const override; + size_t GetTotalNumTimedOutTests() const override; + size_t GetTotalNumUnexecutedTests() const override; + + //! Returns the report for the discarded test runs. + const TestRunSelection GetDiscardedTests() const; + + //! Returns the report for the discarded test runs. + TestRunReport GetDiscardedTestRunReport() const; + + private: + TestRunSelection m_discardedTests; + TestRunReport m_discardedTestRunReport; + }; + } // namespace Client +} // 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..4b7715bf1d 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,118 @@ namespace TestImpact AllTestsPass //!< The test run completed its run and all tests passed. }; + //! Representation of a completed test run. class TestRun { 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. + TestRun( + const AZStd::string& name, + const AZStd::string& commandString, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + TestRunResult result); + + //! 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; }; + + //! 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; + }; + + //! Representation of a test run's failing tests. + class TestRunWithTestFailures + : public TestRun + { + public: + //! 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. + //! @param testFailures The failing tests for this test run. + TestRunWithTestFailures( + const AZStd::string& name, + const AZStd::string& commandString, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + TestRunResult result, + AZStd::vector&& testFailures); + + //! Constructs the client facing representation of a given test target's run. + //! @param testRun The test run this run is to be derived from. + //! @param testFailures The failing tests for this run. + TestRunWithTestFailures(TestRun&& testRun, 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; + }; } // 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/TestImpactRuntime.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRuntime.h index 506aeef53e..69feb48749 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 @@ -108,19 +104,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::SequenceReport 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 +128,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 +147,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 +163,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::SequenceReport 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). @@ -209,8 +205,8 @@ namespace TestImpact void UpdateAndSerializeDynamicDependencyMap(const AZStd::vector& jobs); RuntimeConfig m_config; - SuiteType m_suiteFilter; RepoPath m_sparTIAFile; + SuiteType m_suiteFilter; Policy::ExecutionFailure m_executionFailurePolicy; Policy::FailedTestCoverage m_failedTestCoveragePolicy; Policy::TestFailure m_testFailurePolicy; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp index 61634a8bd3..226301d444 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp @@ -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..ba3a479fdf --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp @@ -0,0 +1,312 @@ +/* + * 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 + { + //! Calculates the final sequence result for a composite of multiple sequences. + 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&& passingTests, + AZStd::vector&& failingTests, + AZStd::vector&& executionFailureTests, + AZStd::vector&& timedOutTests, + AZStd::vector&& unexecutedTests) + : m_startTime(startTime) + , m_result(result) + , m_duration(duration) + , m_passingTests(AZStd::move(passingTests)) + , m_failingTests(AZStd::move(failingTests)) + , m_executionFailureTests(AZStd::move(executionFailureTests)) + , m_timedOutTests(AZStd::move(timedOutTests)) + , m_unexecutedTests(AZStd::move(unexecutedTests)) + { + } + + 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::GetNumPassingTests() const + { + return m_passingTests.size(); + } + + size_t TestRunReport::GetNumFailingTests() const + { + return m_failingTests.size(); + } + + size_t TestRunReport::GetNumTimedOutTests() const + { + return m_timedOutTests.size(); + } + + size_t TestRunReport::GetNumUnexecutedTests() const + { + return m_unexecutedTests.size(); + } + + const AZStd::vector& TestRunReport::GetPassingTests() const + { + return m_passingTests; + } + + const AZStd::vector& TestRunReport::GetFailingTests() const + { + return m_failingTests; + } + + const AZStd::vector& TestRunReport::GetExecutionFailureTests() const + { + return m_executionFailureTests; + } + + const AZStd::vector& TestRunReport::GetTimedOutTests() const + { + return m_timedOutTests; + } + + const AZStd::vector& TestRunReport::GetUnexecutedTests() const + { + return m_unexecutedTests; + } + + SequenceReport::SequenceReport(SuiteType suiteType, const TestRunSelection& selectedTests, TestRunReport&& selectedTestRunReport) + : m_suite(suiteType) + , m_selectedTests(selectedTests) + , m_selectedTestRunReport(AZStd::move(selectedTestRunReport)) + { + } + + TestSequenceResult SequenceReport::GetResult() const + { + return m_selectedTestRunReport.GetResult(); + } + + AZStd::chrono::high_resolution_clock::time_point SequenceReport::GetStartTime() const + { + return m_selectedTestRunReport.GetStartTime(); + } + + AZStd::chrono::high_resolution_clock::time_point SequenceReport::GetEndTime() const + { + return GetStartTime() + GetDuration(); + } + + AZStd::chrono::milliseconds SequenceReport::GetDuration() const + { + return m_selectedTestRunReport.GetDuration(); + } + + TestRunSelection SequenceReport::GetSelectedTests() const + { + return m_selectedTests; + } + + TestRunReport SequenceReport::GetSelectedTestRunReport() const + { + return m_selectedTestRunReport; + } + + size_t SequenceReport::GetTotalNumPassingTests() const + { + return m_selectedTestRunReport.GetNumPassingTests(); + } + + size_t SequenceReport::GetTotalNumFailingTests() const + { + return m_selectedTestRunReport.GetNumFailingTests(); + } + + size_t SequenceReport::GetTotalNumTimedOutTests() const + { + return m_selectedTestRunReport.GetNumTimedOutTests(); + } + + size_t SequenceReport::GetTotalNumUnexecutedTests() const + { + return m_selectedTestRunReport.GetNumUnexecutedTests(); + } + + DraftingSequenceReport::DraftingSequenceReport( + SuiteType suiteType, + const TestRunSelection& selectedTests, + const AZStd::vector& draftedTests, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport) + : SequenceReport(suiteType, selectedTests, AZStd::move(selectedTestRunReport)) + , m_draftedTests(draftedTests) + , m_draftedTestRunReport(AZStd::move(draftedTestRunReport)) + { + } + + TestSequenceResult DraftingSequenceReport::GetResult() const + { + return CalculateMultiTestSequenceResult({SequenceReport::GetResult(), m_draftedTestRunReport.GetResult()}); + } + + AZStd::chrono::milliseconds DraftingSequenceReport::GetDuration() const + { + return SequenceReport::GetDuration() + m_draftedTestRunReport.GetDuration(); + } + + size_t DraftingSequenceReport::GetTotalNumPassingTests() const + { + return SequenceReport::GetTotalNumPassingTests() + m_draftedTestRunReport.GetNumPassingTests(); + } + + size_t DraftingSequenceReport::GetTotalNumFailingTests() const + { + return SequenceReport::GetTotalNumFailingTests() + m_draftedTestRunReport.GetNumFailingTests(); + } + + size_t DraftingSequenceReport::GetTotalNumTimedOutTests() const + { + return SequenceReport::GetTotalNumTimedOutTests() + m_draftedTestRunReport.GetNumTimedOutTests(); + } + + size_t DraftingSequenceReport::GetTotalNumUnexecutedTests() const + { + return SequenceReport::GetTotalNumUnexecutedTests() + m_draftedTestRunReport.GetNumUnexecutedTests(); + } + + const AZStd::vector& DraftingSequenceReport::GetDraftedTests() const + { + return m_draftedTests; + } + + TestRunReport DraftingSequenceReport::GetDraftedTestRunReport() const + { + return m_draftedTestRunReport; + } + + ImpactAnalysisSequenceReport::ImpactAnalysisSequenceReport( + SuiteType suiteType, + const TestRunSelection& selectedTests, + const AZStd::vector& discardedTests, + const AZStd::vector& draftedTests, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport) + : DraftingSequenceReport( + suiteType, + selectedTests, + draftedTests, + AZStd::move(selectedTestRunReport), + AZStd::move(draftedTestRunReport)) + , m_discardedTests(discardedTests) + { + } + + const AZStd::vector& ImpactAnalysisSequenceReport::GetDiscardedTests() const + { + return m_discardedTests; + } + + SafeImpactAnalysisSequenceReport::SafeImpactAnalysisSequenceReport( + SuiteType suiteType, + const TestRunSelection& selectedTests, + const TestRunSelection& discardedTests, + const AZStd::vector& draftedTests, + TestRunReport&& selectedTestRunReport, + TestRunReport&& discardedTestRunReport, + TestRunReport&& draftedTestRunReport) + : DraftingSequenceReport( + suiteType, + selectedTests, + draftedTests, + AZStd::move(selectedTestRunReport), + AZStd::move(draftedTestRunReport)) + , m_discardedTests(discardedTests) + , m_discardedTestRunReport(AZStd::move(discardedTestRunReport)) + { + } + + TestSequenceResult SafeImpactAnalysisSequenceReport::GetResult() const + { + return CalculateMultiTestSequenceResult({ DraftingSequenceReport::GetResult(), m_discardedTestRunReport.GetResult() }); + } + + AZStd::chrono::milliseconds SafeImpactAnalysisSequenceReport::GetDuration() const + { + return DraftingSequenceReport::GetDuration() + m_discardedTestRunReport.GetDuration(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumPassingTests() const + { + return DraftingSequenceReport::GetTotalNumPassingTests() + m_discardedTestRunReport.GetNumPassingTests(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumFailingTests() const + { + return DraftingSequenceReport::GetTotalNumFailingTests() + m_discardedTestRunReport.GetNumFailingTests(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumTimedOutTests() const + { + return DraftingSequenceReport::GetTotalNumTimedOutTests() + m_discardedTestRunReport.GetNumTimedOutTests(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumUnexecutedTests() const + { + return DraftingSequenceReport::GetTotalNumUnexecutedTests() + m_discardedTestRunReport.GetNumUnexecutedTests(); + } + + const TestRunSelection SafeImpactAnalysisSequenceReport::GetDiscardedTests() const + { + return m_discardedTests; + } + + TestRunReport SafeImpactAnalysisSequenceReport::GetDiscardedTestRunReport() const + { + return m_discardedTestRunReport; + } + } // namespace Client +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp index 582927baa5..0a258c5dac 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp @@ -7,14 +7,22 @@ */ #include + namespace TestImpact { namespace Client { - TestRun::TestRun(const AZStd::string& name, TestRunResult result, AZStd::chrono::milliseconds duration) + TestRun::TestRun( + 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) { } @@ -23,6 +31,21 @@ namespace TestImpact return m_targetName; } + const AZStd::string& TestRun::GetCommandString() const + { + return m_commandString; + } + + AZStd::chrono::high_resolution_clock::time_point TestRun::GetStartTime() const + { + return m_startTime; + } + + AZStd::chrono::high_resolution_clock::time_point TestRun::GetEndTime() const + { + return m_startTime + m_duration; + } + AZStd::chrono::milliseconds TestRun::GetDuration() const { return m_duration; @@ -32,5 +55,78 @@ namespace TestImpact { return m_result; } + + 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; + } + + static size_t CalculateNumTestRunFailures(const AZStd::vector& testFailures) + { + size_t numTestFailures = 0; + for (const auto& testCase : testFailures) + { + numTestFailures += testCase.GetTestFailures().size(); + } + + return numTestFailures; + } + + TestRunWithTestFailures::TestRunWithTestFailures( + const AZStd::string& name, + const AZStd::string& commandString, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + TestRunResult result, + AZStd::vector&& testFailures) + : TestRun(name, commandString, startTime, duration, result) + , m_testCaseFailures(AZStd::move(testFailures)) + { + m_numTestFailures = CalculateNumTestRunFailures(m_testCaseFailures); + } + + TestRunWithTestFailures::TestRunWithTestFailures(TestRun&& testRun, AZStd::vector&& testFailures) + : TestRun(AZStd::move(testRun)) + , m_testCaseFailures(AZStd::move(testFailures)) + { + m_numTestFailures = CalculateNumTestRunFailures(m_testCaseFailures); + } + + size_t TestRunWithTestFailures::GetNumTestFailures() const + { + return m_numTestFailures; + } + + const AZStd::vector& TestRunWithTestFailures::GetTestCaseFailures() const + { + return m_testCaseFailures; + } } // 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..478b63e8b2 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp @@ -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::TestRun 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()); @@ -298,6 +329,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 +341,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)) { @@ -353,17 +386,17 @@ namespace TestImpact } } - TestSequenceResult Runtime::RegularTestSequence( + Client::SequenceReport 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 +411,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,27 +430,124 @@ 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::SequenceReport( + 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( + //! 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 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( + 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 globalTimeout, + AZStd::optional testSequenceStartCallback, + AZStd::optional> testSequenceEndCallback, + AZStd::optional testCompleteCallback, + AZStd::optional& jobs)>> updateCoverage) + { + 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); + + // Run the selected test targets and collect the test run results + const Timer selectedTestRunTimer; + const auto [selectedResult, selectedTestJobs] = testRunner(includedSelectedTestTargets, testRunCompleteHandler, globalTimeout); + const auto selectedTestRunDuration = selectedTestRunTimer.GetElapsedMs(); + + // Carry the remaining global sequence time over to the drafted test run + if (globalTimeout.has_value()) + { + const auto elapsed = selectedTestRunDuration; + sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + } + + // Run the drafted test targets and collect the test run results + Timer draftedTestRunTimer; + const auto [draftedResult, draftedTestJobs] = testRunner(draftedTestTargets, testRunCompleteHandler, globalTimeout); + const auto draftedTestRunDuration = draftedTestRunTimer.GetElapsedMs(); + + // Generate the sequence report for the client + const auto sequenceReport = Client::ImpactAnalysisSequenceReport( + suiteType, + selectedTests, + discardedTests, + draftedTests, + GenerateTestRunReport(selectedResult, selectedTestRunTimer.GetStartTimePointRelative(sequenceTimer), selectedTestRunDuration, selectedTestJobs), + GenerateTestRunReport(draftedResult, draftedTestRunTimer.GetStartTimePointRelative(sequenceTimer), draftedTestRunDuration, draftedTestJobs)); + + // 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(selectedTestJobs, draftedTestJobs)); + } + + return sequenceReport; + } + + 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(); @@ -423,71 +558,94 @@ namespace TestImpact // The subset of selected test targets that are not on the configuration's exclude list and those that are auto [includedSelectedTestTargets, excludedSelectedTestTargets] = SelectTestTargetsByExcludeList(selectedTestTargets); - // 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); - - if (testSequenceStartCallback.has_value()) - { - (*testSequenceStartCallback)( - Client::TestRunSelection(ExtractTestTargetNames(includedSelectedTestTargets), ExtractTestTargetNames(excludedSelectedTestTargets)), - ExtractTestTargetNames(discardedTestTargets), - ExtractTestTargetNames(draftedTestTargets)); - } - - if (dynamicDependencyMapPolicy == Policy::DynamicDependencyMap::Update) + // 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_suiteFilter, + sequenceTimer, + instrumentedTestRun, + includedSelectedTestTargets, + excludedSelectedTestTargets, + discardedTestTargets, + draftedTestTargets, + globalTimeout, + testSequenceStartCallback, + testSequenceEndCallback, + testCompleteCallback, + updateCoverage); + } + else + { + return ImpactAnalysisTestSequenceWrapper( + m_suiteFilter, + sequenceTimer, + regularTestRun, + includedSelectedTestTargets, + excludedSelectedTestTargets, + discardedTestTargets, + draftedTestTargets, + 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; + auto sequenceTimeout = globalTimeout; // Draft in the test targets that have no coverage entries in the dynamic dependency map AZStd::vector draftedTestTargets = m_dynamicDependencyMap->GetNotCoveringTests(); @@ -501,40 +659,46 @@ 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 + // 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); + + // Run the selected test targets and collect the test run results + const Timer selectedTestRunTimer; const auto [selectedResult, selectedTestJobs] = m_testEngine->InstrumentedRun( - testTargetsToRun, + includedSelectedTestTargets, m_testShardingPolicy, m_executionFailurePolicy, - Policy::IntegrityFailure::Continue, + m_integrationFailurePolicy, m_testFailurePolicy, m_targetOutputCapture, testTargetTimeout, - globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); - - const auto selectedDuraton = timer.Elapsed(); + sequenceTimeout, + AZStd::ref(testRunCompleteHandler)); + const auto selectedTestRunDuration = selectedTestRunTimer.GetElapsedMs(); // Carry the remaining global sequence time over to the discarded test run if (globalTimeout.has_value()) { - const auto elapsed = timer.Elapsed(); - globalTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + const auto elapsed = selectedTestRunDuration; + sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); } - // Regular run of the discarded test targets + // Run the discarded test targets and collect the test run results + const Timer discardedTestRunTimer; const auto [discardedResult, discardedTestJobs] = m_testEngine->RegularRun( includedDiscardedTestTargets, m_testShardingPolicy, @@ -542,35 +706,63 @@ namespace TestImpact m_testFailurePolicy, m_targetOutputCapture, testTargetTimeout, - globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); + sequenceTimeout, + AZStd::ref(testRunCompleteHandler)); + const auto discardedTestRunDuration = discardedTestRunTimer.GetElapsedMs(); - const auto discardedDuraton = timer.Elapsed(); + // Carry the remaining global sequence time over to the drafted test run + if (globalTimeout.has_value()) + { + const auto elapsed = selectedTestRunDuration + discardedTestRunDuration; + sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + } + // Run the drafted test targets and collect the test run results + const Timer draftedTestRunTimer; + const auto [draftedResult, draftedTestJobs] = m_testEngine->InstrumentedRun( + draftedTestTargets, + m_testShardingPolicy, + m_executionFailurePolicy, + m_integrationFailurePolicy, + m_testFailurePolicy, + m_targetOutputCapture, + testTargetTimeout, + sequenceTimeout, + AZStd::ref(testRunCompleteHandler)); + const auto draftedTestRunDuration = draftedTestRunTimer.GetElapsedMs(); + + // Generate the sequence report for the client + const auto sequenceReport = Client::SafeImpactAnalysisSequenceReport( + m_suiteFilter, + selectedTests, + discardedTests, + draftedTests, + GenerateTestRunReport(selectedResult, selectedTestRunTimer.GetStartTimePointRelative(sequenceTimer), selectedTestRunDuration, selectedTestJobs), + GenerateTestRunReport(discardedResult, discardedTestRunTimer.GetStartTimePointRelative(sequenceTimer), discardedTestRunDuration, discardedTestJobs), + GenerateTestRunReport(draftedResult, draftedTestRunTimer.GetStartTimePointRelative(sequenceTimer), draftedTestRunDuration, draftedTestJobs)); + + // 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(selectedTestJobs, draftedTestJobs)); + return sequenceReport; } - TestSequenceResult Runtime::SeededTestSequence( + Client::SequenceReport 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 +775,44 @@ 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::SequenceReport( + 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..0c61c5f426 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp @@ -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..33e15bfd20 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,16 +36,17 @@ 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. //! @tparam TestJob The test engine job type. template - Client::TestRunFailure GenerateTestRunFailure(const TestJob& testJob) + AZStd::vector GenerateTestCaseFailures(const TestJob& testJob) { + AZStd::vector testCaseFailures; + if (testJob.GetTestRun().has_value()) { - AZStd::vector testCaseFailures; for (const auto& testSuite : testJob.GetTestRun()->GetTestSuites()) { AZStd::vector testFailures; @@ -56,57 +57,66 @@ namespace TestImpact testFailures.push_back(Client::TestFailure(testCase.m_name, "No error message retrieved")); } } - + if (!testFailures.empty()) { testCaseFailures.push_back(Client::TestCaseFailure(testSuite.m_name, AZStd::move(testFailures))); } } - - return Client::TestRunFailure(Client::TestRunFailure(testJob.GetTestTarget()->GetName(), AZStd::move(testCaseFailures))); - } - else - { - return Client::TestRunFailure(testJob.GetTestTarget()->GetName(), { }); } + + return testCaseFailures; } - //! 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::TestRun 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.push_back(clientTestRun); break; } case Client::TestRunResult::NotRun: { - unexecutedTestRuns.push_back(testJob.GetTestTarget()->GetName()); + unexecutedTests.push_back(clientTestRun); break; } case Client::TestRunResult::Timeout: { - timedOutTestRuns.push_back(testJob.GetTestTarget()->GetName()); + timedOutTests.push_back(clientTestRun); break; } case Client::TestRunResult::AllTestsPass: { + passingTests.push_back(clientTestRun); break; } case Client::TestRunResult::TestFailures: { - testRunFailures.push_back(GenerateTestRunFailure(testJob)); + failingTests.emplace_back(AZStd::move(clientTestRun), GenerateTestCaseFailures(testJob)); break; } default: @@ -116,11 +126,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/testimpactframework_runtime_files.cmake b/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake index 090bb68fcc..e28bb5ba7b 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake +++ b/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake @@ -19,7 +19,7 @@ set(FILES Include/TestImpactFramework/TestImpactTestSequence.h Include/TestImpactFramework/TestImpactClientTestSelection.h Include/TestImpactFramework/TestImpactClientTestRun.h - Include/TestImpactFramework/TestImpactClientFailureReport.h + Include/TestImpactFramework/TestImpactClientSequenceReport.h Include/TestImpactFramework/TestImpactFileUtils.h Source/Artifact/TestImpactArtifactException.h Source/Artifact/Factory/TestImpactBuildTargetDescriptorFactory.cpp @@ -123,7 +123,8 @@ set(FILES Source/TestImpactRuntimeUtils.h Source/TestImpactClientTestSelection.cpp Source/TestImpactClientTestRun.cpp - Source/TestImpactClientFailureReport.cpp + Source/TestImpactClientSequenceReport.cpp Source/TestImpactChangeListSerializer.cpp + Source/TestImpactChangeListSerializerInternal.h Source/TestImpactRepoPath.cpp ) From 522e284b3d684a5bb22287ce1f9f942b03a5ee23 Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Fri, 6 Aug 2021 12:27:27 -0700 Subject: [PATCH 148/251] fix for failing periodic test Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- ...nvasComponent_OnEntityActivatedDeactivated_PrintMessage.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 From 7b0118268c294f0c8f7d9337a6e8c8896e7824fb Mon Sep 17 00:00:00 2001 From: John Date: Fri, 6 Aug 2021 20:40:37 +0100 Subject: [PATCH 149/251] Remove missing header from cmake. Signed-off-by: John --- .../Runtime/Code/testimpactframework_runtime_files.cmake | 1 - 1 file changed, 1 deletion(-) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake b/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake index e28bb5ba7b..76673d9f40 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake +++ b/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake @@ -125,6 +125,5 @@ set(FILES Source/TestImpactClientTestRun.cpp Source/TestImpactClientSequenceReport.cpp Source/TestImpactChangeListSerializer.cpp - Source/TestImpactChangeListSerializerInternal.h Source/TestImpactRepoPath.cpp ) From d6744690ee281aeda4dfc0759412d2711db13a98 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 6 Aug 2021 15:10:21 -0700 Subject: [PATCH 150/251] platform.h cleanup Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Include/IObjectManager.h | 1 + Code/Editor/Objects/ObjectLoader.h | 2 + .../PerforcePlugin/PerforceSourceControl.cpp | 1 + Code/Legacy/CryCommon/AndroidSpecific.h | 1 - Code/Legacy/CryCommon/AppleSpecific.h | 7 - Code/Legacy/CryCommon/BitFiddling.h | 11 - Code/Legacy/CryCommon/CryArray.h | 18 +- Code/Legacy/CryCommon/CryAssert.h | 3 +- Code/Legacy/CryCommon/CrySizer.h | 4 +- .../Legacy/CryCommon/CryThreadImpl_pthreads.h | 8 +- Code/Legacy/CryCommon/CryThreadImpl_windows.h | 2 +- Code/Legacy/CryCommon/CryThread_pthreads.h | 2 +- Code/Legacy/CryCommon/CryThread_windows.h | 2 +- Code/Legacy/CryCommon/IFunctorBase.h | 1 + Code/Legacy/CryCommon/IMaterial.h | 1 + Code/Legacy/CryCommon/ISystem.h | 2 +- Code/Legacy/CryCommon/Linux32Specific.h | 1 - Code/Legacy/CryCommon/Linux64Specific.h | 1 - Code/Legacy/CryCommon/LinuxSpecific.h | 17 - Code/Legacy/CryCommon/MTPseudoRandom.cpp | 2 +- Code/Legacy/CryCommon/ProjectDefines.h | 188 ++----- Code/Legacy/CryCommon/Win32specific.h | 1 - Code/Legacy/CryCommon/Win64specific.h | 1 - Code/Legacy/CryCommon/WinBase.cpp | 41 -- Code/Legacy/CryCommon/platform.h | 471 ++---------------- Code/Legacy/CryCommon/platform_impl.cpp | 53 -- Code/Legacy/CryCommon/smartptr.h | 13 +- Code/Legacy/CrySystem/IDebugCallStack.cpp | 2 +- Code/Legacy/CrySystem/SystemInit.cpp | 2 +- Code/Legacy/CrySystem/SystemWin32.cpp | 41 +- .../CrySystem/ViewSystem/ViewSystem.cpp | 2 +- Code/Legacy/CrySystem/XML/xml.cpp | 2 +- .../Source/Animation/UiAnimationSystem.cpp | 8 +- Gems/Maestro/Code/Source/Cinematics/Movie.cpp | 8 +- 34 files changed, 144 insertions(+), 776 deletions(-) diff --git a/Code/Editor/Include/IObjectManager.h b/Code/Editor/Include/IObjectManager.h index ce9d69681b..efc1955a56 100644 --- a/Code/Editor/Include/IObjectManager.h +++ b/Code/Editor/Include/IObjectManager.h @@ -14,6 +14,7 @@ #include #include #include +#include // forward declarations. class CEntityObject; diff --git a/Code/Editor/Objects/ObjectLoader.h b/Code/Editor/Objects/ObjectLoader.h index ccfaeb78f0..fc526970dd 100644 --- a/Code/Editor/Objects/ObjectLoader.h +++ b/Code/Editor/Objects/ObjectLoader.h @@ -15,6 +15,8 @@ #include "Util/GuidUtil.h" #include "ErrorReport.h" +#include + class CPakFile; class CErrorRecord; struct IObjectManager; diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index 581f9a576d..1ea70e8c22 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -9,6 +9,7 @@ #include "CryFile.h" #include "PerforceSourceControl.h" #include "PasswordDlg.h" +#include #include #include diff --git a/Code/Legacy/CryCommon/AndroidSpecific.h b/Code/Legacy/CryCommon/AndroidSpecific.h index 0cb4a6786c..a0f57553ca 100644 --- a/Code/Legacy/CryCommon/AndroidSpecific.h +++ b/Code/Legacy/CryCommon/AndroidSpecific.h @@ -35,7 +35,6 @@ // to what some structs/classes need. #define CRY_FORCE_MALLOC_NEW_ALIGN -#define DEBUG_BREAK raise(SIGTRAP) #define RC_EXECUTABLE "rc" #define USE_CRT 1 #define SIZEOF_PTR 4 diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index 4d17c18bac..ed76de8986 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -18,7 +18,6 @@ #endif -#define DEBUG_BREAK __builtin_trap() #define RC_EXECUTABLE "rc" ////////////////////////////////////////////////////////////////////////// @@ -52,12 +51,6 @@ #define __COUNTER__ __LINE__ #endif -#ifdef __FUNC__ -#undef __FUNC__ -#endif - -#define __FUNC__ __func__ - typedef void* LPVOID; #define VOID void #define PVOID void* diff --git a/Code/Legacy/CryCommon/BitFiddling.h b/Code/Legacy/CryCommon/BitFiddling.h index 901dd0a49a..342aad9a82 100644 --- a/Code/Legacy/CryCommon/BitFiddling.h +++ b/Code/Legacy/CryCommon/BitFiddling.h @@ -36,7 +36,6 @@ ILINE uint32 countLeadingZeros32(uint32 x) { DWORD result = 32 ^ 31; // assumes result is unmodified if _BitScanReverse returns 0 _BitScanReverse(&result, x); - PREFAST_SUPPRESS_WARNING(6102); result ^= 31; // needed because the index is from LSB (whereas all other implementations are from MSB) return result; } @@ -73,16 +72,6 @@ inline bool IsPowerOfTwo(TInteger x) return (x & (x - 1)) == 0; } -// compile time version of IsPowerOfTwo, useful for STATIC_CHECK -template -struct IsPowerOfTwoCompileTime -{ - enum - { - IsPowerOfTwo = ((nValue & (nValue - 1)) == 0) - }; -}; - inline uint32 NextPower2(uint32 n) { n--; diff --git a/Code/Legacy/CryCommon/CryArray.h b/Code/Legacy/CryCommon/CryArray.h index b304df28af..5b4684fdd2 100644 --- a/Code/Legacy/CryCommon/CryArray.h +++ b/Code/Legacy/CryCommon/CryArray.h @@ -15,24 +15,10 @@ //--------------------------------------------------------------------------- // Convenient iteration macros -#define for_iter(IT, it, b, e) for (IT it = (b), _e = (e); it != _e; ++it) -#define for_container(CT, it, cont) for_iter (CT::iterator, it, (cont).begin(), (cont).end()) #define for_ptr(T, it, b, e) for (T* it = (b), * _e = (e); it != _e; ++it) -#define for_array_ptr(T, it, arr) for_ptr (T, it, (arr).begin(), (arr).end()) - -#define for_array(i, arr) for (int i = 0, _e = (arr).size(); i < _e; i++) -#define for_all(cont) for_array (_i, cont) cont[_i] - -//--------------------------------------------------------------------------- -// Stack array helper -#define ALIGNED_STACK_ARRAY(T, name, size, alignment) \ - PREFAST_SUPPRESS_WARNING(6255) \ - T * name = (T*) alloca((size) * sizeof(T) + alignment - 1); \ - name = Align(name, alignment); - -#define STACK_ARRAY(T, name, size) \ - ALIGNED_STACK_ARRAY(T, name, size, alignof(T)) \ +#define for_array_ptr(T, it, arr) for_ptr (T, it, (arr).begin(), (arr).end()) +#define for_array(i, arr) for (int i = 0, _e = (arr).size(); i < _e; i++) //--------------------------------------------------------------------------- // Specify semantics for moving objects. diff --git a/Code/Legacy/CryCommon/CryAssert.h b/Code/Legacy/CryCommon/CryAssert.h index 1cb5d37c43..1494654d87 100644 --- a/Code/Legacy/CryCommon/CryAssert.h +++ b/Code/Legacy/CryCommon/CryAssert.h @@ -71,7 +71,6 @@ #if defined(USE_CRY_ASSERT) && CRYASSERT_H_TRAIT_USE_CRY_ASSERT_MESSAGE void CryAssertTrace(const char*, ...); bool CryAssert(const char*, const char*, unsigned int, bool*); -void CryDebugBreak(); #define CRY_ASSERT(condition) CRY_ASSERT_MESSAGE(condition, NULL) @@ -86,7 +85,7 @@ void CryDebugBreak(); CryAssertTrace parenthese_message; \ if (CryAssert(#condition, __FILE__, __LINE__, &s_bIgnoreAssert)) \ { \ - DEBUG_BREAK; \ + AZ::Debug::Trace::Break(); \ } \ } \ } while (0) diff --git a/Code/Legacy/CryCommon/CrySizer.h b/Code/Legacy/CryCommon/CrySizer.h index 9301360bd5..583de5bee8 100644 --- a/Code/Legacy/CryCommon/CrySizer.h +++ b/Code/Legacy/CryCommon/CrySizer.h @@ -581,7 +581,7 @@ protected: // use this to push (and automatically pop) the sizer component name at the beginning of the // getSize() function -#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, false) -#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, true) +#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, false) +#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, true) #endif // CRYINCLUDE_CRYCOMMON_CRYSIZER_H diff --git a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h index c94d4fca90..c3dee7339f 100644 --- a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h +++ b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h @@ -14,13 +14,7 @@ #include "CryThread_pthreads.h" -#if PLATFORM_SUPPORTS_THREADLOCAL -THREADLOCAL CrySimpleThreadSelf -* CrySimpleThreadSelf::m_Self = NULL; -#else -TLS_DEFINE(CrySimpleThreadSelf*, g_CrySimpleThreadSelf) -#endif - +AZ_THREAD_LOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL; ////////////////////////////////////////////////////////////////////////// // CryEvent(Timed) implementation diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h index 5cf970414d..4ddbaedac5 100644 --- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h +++ b/Code/Legacy/CryCommon/CryThreadImpl_windows.h @@ -20,7 +20,7 @@ struct SThreadNameDesc DWORD dwFlags; }; -THREADLOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL; +AZ_THREAD_LOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL; ////////////////////////////////////////////////////////////////////////// CryEvent::CryEvent() diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h index 72b29344ec..2c6b389dbb 100644 --- a/Code/Legacy/CryCommon/CryThread_pthreads.h +++ b/Code/Legacy/CryCommon/CryThread_pthreads.h @@ -672,7 +672,7 @@ protected: m_Self = pSelf; } private: - static THREADLOCAL CrySimpleThreadSelf* m_Self; + static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self; #else diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h index cc09cc530b..98517133c1 100644 --- a/Code/Legacy/CryCommon/CryThread_windows.h +++ b/Code/Legacy/CryCommon/CryThread_windows.h @@ -189,7 +189,7 @@ public: virtual ~CrySimpleThreadSelf(); protected: void StartThread(unsigned (__stdcall * func)(void*), void* argList); - static THREADLOCAL CrySimpleThreadSelf* m_Self; + static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self; private: CrySimpleThreadSelf(const CrySimpleThreadSelf&); CrySimpleThreadSelf& operator = (const CrySimpleThreadSelf&); diff --git a/Code/Legacy/CryCommon/IFunctorBase.h b/Code/Legacy/CryCommon/IFunctorBase.h index 2a8af50d33..1ac37a0e47 100644 --- a/Code/Legacy/CryCommon/IFunctorBase.h +++ b/Code/Legacy/CryCommon/IFunctorBase.h @@ -14,6 +14,7 @@ #define CRYINCLUDE_CRYCOMMON_IFUNCTORBASE_H #pragma once +#include // Base class for functor storage. // Not intended for direct usage. diff --git a/Code/Legacy/CryCommon/IMaterial.h b/Code/Legacy/CryCommon/IMaterial.h index 1faee0eef9..f1967324d8 100644 --- a/Code/Legacy/CryCommon/IMaterial.h +++ b/Code/Legacy/CryCommon/IMaterial.h @@ -37,6 +37,7 @@ struct IRenderMesh; #include #include #include +#include #ifdef MAX_SUB_MATERIALS // This checks that the values are in sync in the different files. diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index d934995b4d..7cea690687 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -1419,7 +1419,7 @@ namespace Detail } DummyStaticInstance; \ if (!(gEnv->pConsole != 0 ? gEnv->pConsole->Register(&DummyStaticInstance) : 0)) \ { \ - DEBUG_BREAK; \ + AZ::Debug::Trace::Break(); \ CryFatalError("Can not register dummy CVar"); \ } \ } while (0) diff --git a/Code/Legacy/CryCommon/Linux32Specific.h b/Code/Legacy/CryCommon/Linux32Specific.h index b3f06a80b7..e66838f431 100644 --- a/Code/Legacy/CryCommon/Linux32Specific.h +++ b/Code/Legacy/CryCommon/Linux32Specific.h @@ -18,7 +18,6 @@ #define _CPU_X86 //#define _CPU_SSE -#define DEBUG_BREAK raise(SIGTRAP) #define RC_EXECUTABLE "rc" #define USE_CRT 1 #define SIZEOF_PTR 4 diff --git a/Code/Legacy/CryCommon/Linux64Specific.h b/Code/Legacy/CryCommon/Linux64Specific.h index 11b526ee4b..0aa9321025 100644 --- a/Code/Legacy/CryCommon/Linux64Specific.h +++ b/Code/Legacy/CryCommon/Linux64Specific.h @@ -20,7 +20,6 @@ #define _CPU_AMD64 #define _CPU_SSE -#define DEBUG_BREAK ::raise(SIGTRAP) #define RC_EXECUTABLE "rc" #define USE_CRT 1 #define SIZEOF_PTR 8 diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h index 5fc1f7b801..cbffae5957 100644 --- a/Code/Legacy/CryCommon/LinuxSpecific.h +++ b/Code/Legacy/CryCommon/LinuxSpecific.h @@ -42,23 +42,6 @@ #include #include -#ifdef __FUNC__ -#undef __FUNC__ -#endif -#if defined(__GNUC__) || defined(__clang__) -#define __FUNC__ __func__ -#else -#define __FUNC__ \ - ({ \ - static char __f[sizeof(__PRETTY_FUNCTION__) + 1]; \ - strcpy(__f, __PRETTY_FUNCTION__); \ - char* __p = (char*)strchr(__f, '('); \ - *__p = 0; \ - while (*(__p) != ' ' && __p != (__f - 1)) {--__p; } \ - (__p + 1); \ - }) -#endif - typedef void* LPVOID; #define VOID void #define PVOID void* diff --git a/Code/Legacy/CryCommon/MTPseudoRandom.cpp b/Code/Legacy/CryCommon/MTPseudoRandom.cpp index 6f163e682f..f8a3950ff0 100644 --- a/Code/Legacy/CryCommon/MTPseudoRandom.cpp +++ b/Code/Legacy/CryCommon/MTPseudoRandom.cpp @@ -63,7 +63,7 @@ void CMTRand_int32::seed(const uint32* array, int size) // init by array } for (int k = n - 1; k; --k) { - PREFAST_SUPPRESS_WARNING(6385) PREFAST_SUPPRESS_WARNING(6386) m_nState[i] = (m_nState[i] ^ ((m_nState[i - 1] ^ (m_nState[i - 1] >> 30)) * 1566083941UL)) - i; + m_nState[i] = (m_nState[i] ^ ((m_nState[i - 1] ^ (m_nState[i - 1] >> 30)) * 1566083941UL)) - i; if ((++i) == n) { m_nState[0] = m_nState[n - 1]; diff --git a/Code/Legacy/CryCommon/ProjectDefines.h b/Code/Legacy/CryCommon/ProjectDefines.h index 3d635c491c..eda5bb8b5f 100644 --- a/Code/Legacy/CryCommon/ProjectDefines.h +++ b/Code/Legacy/CryCommon/ProjectDefines.h @@ -16,10 +16,6 @@ #include "BaseTypes.h" #include -#if defined(_RELEASE) && !defined(RELEASE) - #define RELEASE -#endif - // Section dictionary #if defined(AZ_RESTRICTED_PLATFORM) #define PROJECTDEFINES_H_SECTION_STATS_AGENT 1 @@ -31,57 +27,51 @@ #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_STATS_AGENT #include AZ_RESTRICTED_FILE(ProjectDefines_h) #elif defined(WIN32) || defined(WIN64) -#if !defined(_RELEASE) || defined(PERFORMANCE_BUILD) -#define ENABLE_STATS_AGENT -#endif + #if !defined(_RELEASE) || defined(PERFORMANCE_BUILD) + #define ENABLE_STATS_AGENT + #endif #endif -// The following definitions are used by Sandbox and RC to determine which platform support is needed -#define TOOLS_SUPPORT_POWERVR -#define TOOLS_SUPPORT_ETC2COMP // Type used for vertex indices // WARNING: If you change this typedef, you need to update AssetProcessorPlatformConfig.ini to convert cgf and abc files to the proper index format. #if defined(RESOURCE_COMPILER) -typedef uint32 vtx_idx; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED + typedef uint32 vtx_idx; + #define AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(MOBILE) -typedef uint16 vtx_idx; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED + typedef uint16 vtx_idx; + #define AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_VTX_IDX #include AZ_RESTRICTED_FILE(ProjectDefines_h) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #else -// Uncomment one of the two following typedefs: -typedef uint32 vtx_idx; -//typedef uint16 vtx_idx; + // Uncomment one of the two following typedefs: + typedef uint32 vtx_idx; + //typedef uint16 vtx_idx; #endif -// 0=off, 1=on -#define TERRAIN_USE_CIE_COLORSPACE 0 - // When non-zero, const cvar accesses (by name) are logged in release-mode on consoles. // This can be used to find non-optimal usage scenario's, where the constant should be used directly instead. // Since read accesses tend to be used in flow-control logic, constants allow for better optimization by the compiler. #define LOG_CONST_CVAR_ACCESS 0 #if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS -#define RELEASE_LOGGING + #define RELEASE_LOGGING #endif #if defined(_RELEASE) && !defined(RELEASE_LOGGING) -#define EXCLUDE_NORMAL_LOG + #define EXCLUDE_NORMAL_LOG #endif // Add the "REMOTE_ASSET_PROCESSOR" define except in release // this makes it so that asset processor functions. Without this, all assets must be present and on local media // with this, the asset processor can be used to remotely process assets. #if !defined(_RELEASE) -# define REMOTE_ASSET_PROCESSOR + #define REMOTE_ASSET_PROCESSOR #endif #if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) @@ -93,132 +83,68 @@ typedef uint32 vtx_idx; #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_TRAITS #include AZ_RESTRICTED_FILE(ProjectDefines_h) #else -#define PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS 1 -#if !defined(LINUX) && !defined(APPLE) -#define PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM 1 -#endif -#if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE) -#define PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES 1 -#endif -#define PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION 1 -#if defined(WIN32) -#define PROJECTDEFINES_H_TRAIT_USE_SVO_GI 1 -#endif -#if defined(APPLE) || defined(LINUX) -#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS 1 -#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS 1 -#endif -#endif - -#define USE_GLOBAL_BUCKET_ALLOCATOR - -#ifdef IS_PROSDK -# define USING_TAGES_SECURITY // Wrapper for TGVM security -# if defined(LINUX) || defined(APPLE) -# error LINUX and Mac does not support evaluation version -# endif -#endif - -#ifdef USING_TAGES_SECURITY -# define TAGES_EXPORT __declspec(dllexport) -#else -# define TAGES_EXPORT -#endif // USING_TAGES_SECURITY -// test ------------------------------------- - -#define _DATAPROBE - - - -//This feature allows automatic crash submission to JIRA, but does not work outside of O3DE -//Note: This #define will be commented out during code export -#define ENABLE_CRASH_HANDLER - -#if !defined(PHYSICS_STACK_SIZE) -# define PHYSICS_STACK_SIZE (128U << 10) + #define PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS 1 + #if !defined(LINUX) && !defined(APPLE) + #define PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM 1 + #endif + #if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE) + #define PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES 1 + #endif + #define PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION 1 + #if defined(WIN32) + #define PROJECTDEFINES_H_TRAIT_USE_SVO_GI 1 + #endif + #if defined(APPLE) || defined(LINUX) + #define AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS 1 + #define AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS 1 + #endif #endif #if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !defined(RESOURCE_COMPILER) -#ifndef ENABLE_PROFILING_CODE - #define ENABLE_PROFILING_CODE -#endif -#if !(defined(SANDBOX_EXPORTS) || defined(PLUGIN_EXPORTS) || (defined(AZ_MONOLITHIC_BUILD) && PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS)) - #define ENABLE_PROFILING_MARKERS -#endif - -//lightweight profilers, disable for submissions, disables displayinfo inside 3dengine as well -#ifndef ENABLE_LW_PROFILERS - #define ENABLE_LW_PROFILERS -#endif -#endif - -#if defined(ENABLE_PROFILING_CODE) -#define ENABLE_ART_RT_TIME_ESTIMATE -#endif - -#if defined(ENABLE_PROFILING_CODE) && !defined(_RELEASE) - #define FMOD_STREAMING_DEBUGGING 1 -#endif + #ifndef ENABLE_PROFILING_CODE + #define ENABLE_PROFILING_CODE + #endif -#if defined(WIN32) || defined(WIN64) || defined(APPLE) || defined(AZ_PLATFORM_LINUX) -#define FLARES_SUPPORT_EDITING + //lightweight profilers, disable for submissions, disables displayinfo inside 3dengine as well + #ifndef ENABLE_LW_PROFILERS + #define ENABLE_LW_PROFILERS + #endif #endif // Reflect texture slot information - only used in the editor #if defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC) -#define SHADER_REFLECT_TEXTURE_SLOTS 1 + #define SHADER_REFLECT_TEXTURE_SLOTS 1 #else -#define SHADER_REFLECT_TEXTURE_SLOTS 0 + #define SHADER_REFLECT_TEXTURE_SLOTS 0 #endif -// these enable and disable certain net features to give compatibility between PCs and consoles / profile and performance builds -#define PC_CONSOLE_NET_COMPATIBLE 0 -#define PROFILE_PERFORMANCE_NET_COMPATIBLE 0 - -#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !PROFILE_PERFORMANCE_NET_COMPATIBLE -#define USE_LAGOMETER (1) -#else -#define USE_LAGOMETER (0) -#endif - -// enable this in order to support old style material names in old data ("engine/material.mtl" or "mygame/material.mtl" as opposed to just "material.mtl") -// previously, material names could have the game folder in it, but this is not necessary anymore and would not work with things like gems -// note that if you use any older projects such as GameSDK this should remain enabled -#define SUPPORT_LEGACY_MATERIAL_NAMES - -// Enable additional structures and code for sprite motion blur. Currently non-functional and disabled -// #define PARTICLE_MOTION_BLUR - -// a special ticker thread to run during load and unload of levels -#define USE_NETWORK_STALL_TICKER_THREAD - #if !defined(MOBILE) -//--------------------------------------------------------------------- -// Enable Tessellation Features -// (displacement mapping, subdivision, water tessellation) -//--------------------------------------------------------------------- -// Modules : 3DEngine, Renderer -// Depends on: DX11 - -// Global tessellation feature flag + //--------------------------------------------------------------------- + // Enable Tessellation Features + // (displacement mapping, subdivision, water tessellation) + //--------------------------------------------------------------------- + // Modules : 3DEngine, Renderer + // Depends on: DX11 + + // Global tessellation feature flag #define TESSELLATION #ifdef TESSELLATION -// Specific features flags + // Specific features flags #define WATER_TESSELLATION #define PARTICLES_TESSELLATION #if PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION -// Mesh tessellation (displacement, smoothing, subd) + // Mesh tessellation (displacement, smoothing, subd) #define MESH_TESSELLATION -// Mesh tessellation also in motion blur passes + // Mesh tessellation also in motion blur passes #define MOTIONBLUR_TESSELLATION #endif -// Dependencies + // Dependencies #ifdef MESH_TESSELLATION #define MESH_TESSELLATION_ENGINE #endif - #ifndef NULL_RENDERER + #ifndef NULL_RENDERER #ifdef WATER_TESSELLATION #define WATER_TESSELLATION_RENDERER #endif @@ -230,7 +156,7 @@ typedef uint32 vtx_idx; #endif #if defined(WATER_TESSELLATION_RENDERER) || defined(PARTICLES_TESSELLATION_RENDERER) || defined(MESH_TESSELLATION_RENDERER) -// Common tessellation flag enabling tessellation stages in renderer + // Common tessellation flag enabling tessellation stages in renderer #define TESSELLATION_RENDERER #endif #endif // !NULL_RENDERER @@ -249,14 +175,8 @@ typedef uint32 vtx_idx; #endif #if defined(ENABLE_PROFILING_CODE) -# define USE_DISK_PROFILER -# define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined -#endif - -#if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER) - #define GPU_PARTICLES 1 -#else - #define GPU_PARTICLES 0 + #define USE_DISK_PROFILER + #define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined #endif // The maximum number of joints in an animation diff --git a/Code/Legacy/CryCommon/Win32specific.h b/Code/Legacy/CryCommon/Win32specific.h index 650a4946a0..0519bb1022 100644 --- a/Code/Legacy/CryCommon/Win32specific.h +++ b/Code/Legacy/CryCommon/Win32specific.h @@ -23,7 +23,6 @@ #define ILINE __forceinline #endif -#define DEBUG_BREAK _asm { int 3 } #define RC_EXECUTABLE "rc.exe" #define DEPRECATED __declspec(deprecated) #define TYPENAME(x) typeid(x).name() diff --git a/Code/Legacy/CryCommon/Win64specific.h b/Code/Legacy/CryCommon/Win64specific.h index a3cb11ce32..b1e86f9250 100644 --- a/Code/Legacy/CryCommon/Win64specific.h +++ b/Code/Legacy/CryCommon/Win64specific.h @@ -19,7 +19,6 @@ #define _CPU_SSE #define ILINE __forceinline -#define DEBUG_BREAK CryDebugBreak() #define RC_EXECUTABLE "rc.exe" #define DEPRECATED __declspec(deprecated) #define TYPENAME(x) typeid(x).name() diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 15146fbac1..2861b4470e 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -1127,20 +1127,6 @@ void CrySleep(unsigned int dwMilliseconds) Sleep(dwMilliseconds); } -////////////////////////////////////////////////////////////////////////// -void CryLowLatencySleep(unsigned int dwMilliseconds) -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_6 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - CrySleep(dwMilliseconds); -#endif -} - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType) @@ -1284,14 +1270,6 @@ int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType) #endif } -////////////////////////////////////////////////////////////////////////// -short CryGetAsyncKeyState(int vKey) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CryGetAsyncKeyState not implemented yet"); - return 0; -} - #if defined(LINUX) || defined(APPLE) || defined(DEFINE_CRY_INTERLOCKED_INCREMENT) //[K01]: http://www.memoryhole.net/kyle/2007/05/atomic_incrementing.html //http://forums.devx.com/archive/index.php/t-160558.html @@ -1382,10 +1360,6 @@ threadID CryGetCurrentThreadId() return GetCurrentThreadId(); } -void CryDebugBreak() -{ - __builtin_trap(); -} #endif//LINUX APPLE #if defined(APPLE) || defined(LINUX) @@ -1398,11 +1372,6 @@ DLL_EXPORT void OutputDebugString(const char* outputString) #endif } -DLL_EXPORT void DebugBreak() -{ - CryDebugBreak(); -} - #endif // This code does not have a long life span and will be replaced soon @@ -1626,16 +1595,6 @@ DWORD GetFileAttributes(LPCSTR lpFileName) return (ret == 0) ? FILE_ATTRIBUTE_NORMAL : ret;//return file attribute normal as the default value, must only be set if no other attributes have been found } -uint32 CryGetFileAttributes(const char* lpFileName) -{ - - string fn = lpFileName; - adaptFilenameToLinux(fn); - const char* buffer = fn.c_str(); - return GetFileAttributes(buffer); - -} - __finddata64_t::~__finddata64_t() { if (m_Dir != FS_DIR_NULL) diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 6aad8dd043..fb96056beb 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -7,136 +7,31 @@ */ -// Description : Platform dependend stuff. +// Description : Platform dependent stuff. // Include this file instead of windows h #pragma once #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION -#define PLATFORM_H_SECTION_1 1 -#define PLATFORM_H_SECTION_2 2 #define PLATFORM_H_SECTION_3 3 -#define PLATFORM_H_SECTION_4 4 #define PLATFORM_H_SECTION_5 5 #define PLATFORM_H_SECTION_6 6 #define PLATFORM_H_SECTION_7 7 #define PLATFORM_H_SECTION_8 8 -#define PLATFORM_H_SECTION_9 9 #define PLATFORM_H_SECTION_10 10 #define PLATFORM_H_SECTION_11 11 #define PLATFORM_H_SECTION_12 12 #define PLATFORM_H_SECTION_13 13 #define PLATFORM_H_SECTION_14 14 -#define PLATFORM_H_SECTION_15 15 #endif -// certain C++ features are not available in some compiler versions -// turn them off here: -// #define _ALLOW_KEYWORD_MACROS -// #define _DISALLOW_INITIALIZER_LISTS -// #define _DISALLOW_ENUM_CLASS - -#if defined(_MSC_VER) - #define _ALLOW_KEYWORD_MACROS - - #define alignof _alignof - #if !defined(_HAS_EXCEPTIONS) - #define _HAS_EXCEPTIONS 0 - #endif -#elif defined(__GNUC__) - #define alignof __alignof__ -#endif - -// Alignment|InitializerList support. -#define _ALLOW_INITIALIZER_LISTS - #if (defined(LINUX) && !defined(ANDROID)) || defined(APPLE) -#define _FILE_OFFSET_BITS 64 // define large file support > 2GB + #define _FILE_OFFSET_BITS 64 // define large file support > 2GB #endif #include -#include - -#if defined(_MSC_VER) // We want the class name to be included, but __FUNCTION__ doesn't contain that on GCC/clang - #define __FUNC__ __FUNCTION__ -#else - #define __FUNC__ __PRETTY_FUNCTION__ -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_1 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(_DEBUG) && !defined(LINUX) && !defined(APPLE) - #include -#endif - -#define RESTRICT_POINTER __restrict - -// we have to use it because of VS doesn't support restrict reference variables -#if defined(APPLE) || defined(LINUX) - #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) - #define GCC411_OR_LATER - #endif - #define RESTRICT_REFERENCE __restrict -#else - #define RESTRICT_REFERENCE -#endif - - -#ifndef CHECK_REFERENCE_COUNTS //define that in your StdAfx.h to override per-project -# define CHECK_REFERENCE_COUNTS 0 //default value -#endif - -#if CHECK_REFERENCE_COUNTS -# define CHECK_REFCOUNT_CRASH(x) { if (!(x)) {*((int*)0) = 0; } \ -} -#else -# define CHECK_REFCOUNT_CRASH(x) -#endif - -#ifndef GARBAGE_MEMORY_ON_FREE //define that in your StdAfx.h to override per-project -# define GARBAGE_MEMORY_ON_FREE 0 //default value -#endif - -#if GARBAGE_MEMORY_ON_FREE -# ifndef GARBAGE_MEMORY_RANDOM //define that in your StdAfx.h to override per-project -# define GARBAGE_MEMORY_RANDOM 1 //0 to change it to progressive pattern -# endif -#endif - -////////////////////////////////////////////////////////////////////////// -// Available predefined compiler macros for Visual C++. -// _MSC_VER // Indicates MS Visual C compiler version -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_2 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// _WIN32, _WIN64 // Indicates target OS -#endif -// _M_IX86, _M_PPC // Indicates target processor -// _DEBUG // Building in Debug mode -// _DLL // Linking with DLL runtime libs -// _MT // Linking with multi-threaded runtime libs -////////////////////////////////////////////////////////////////////////// - -// -// Translate some predefined macros. -// - -// NDEBUG disables std asserts, etc. -// Define it automatically if not compiling with Debug libs, or with ADEBUG flag. -#if !defined(_DEBUG) && !defined(ADEBUG) && !defined(NDEBUG) - #define NDEBUG -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_3 #include AZ_RESTRICTED_FILE(platform_h) @@ -147,44 +42,6 @@ #define CONSOLE #endif -//render thread settings, as this is accessed inside 3dengine and renderer and needs to be compile time defined, we need to do it here -//enable this macro to strip out the overhead for render thread -// #define STRIP_RENDER_THREAD -#ifdef STRIP_RENDER_THREAD - #define RT_COMMAND_BUF_COUNT 1 -#else -//can be enhanced to triple buffering, FlushFrame needs to be adjusted and RenderObj would become 132 bytes - #define RT_COMMAND_BUF_COUNT 2 -#endif - - -// We use WIN macros without _. -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_4 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -#if defined(_WIN32) && !defined(LINUX32) && !defined(LINUX64) && !defined(APPLE) && !defined(WIN32) - #define WIN32 -#endif -#if defined(_WIN64) && !defined(WIN64) - #define WIN64 -#endif -#endif - -// In Win32 Release we use static linkage -#ifdef WIN32 - #if !defined(_RELEASE) || defined(RESOURCE_COMPILER) || defined(EDITOR) || defined(_FORCEDLL) -// All windows targets not in Release built as DLLs. - #ifndef _USRDLL - #define _USRDLL - #endif - #endif - -#endif //WIN32 - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_5 #include AZ_RESTRICTED_FILE(platform_h) @@ -205,19 +62,17 @@ #define PRId64 "lld" #define PRIu64 "llu" #endif - #define PLATFORM_I64(x) x##ll #else #include - #define PLATFORM_I64(x) x##i64 #endif #if !defined(PRISIZE_T) -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_6 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_6 + #include AZ_RESTRICTED_FILE(platform_h) + #endif + #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(WIN64) #define PRISIZE_T "I64u" //size_t defined as unsigned __int64 #elif defined(WIN32) || defined(LINUX32) @@ -228,13 +83,14 @@ #error "Please defined PRISIZE_T for this platform" #endif #endif + #if !defined(PRI_THREADID) -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_7 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_7 + #include AZ_RESTRICTED_FILE(platform_h) + #endif + #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(MAC) || defined(IOS) && defined(__LP64__) && defined(__LP64__) #define PRI_THREADID "lld" #elif defined(LINUX64) || defined(ANDROID) @@ -243,6 +99,7 @@ #define PRI_THREADID "d" #endif #endif + #include "ProjectDefines.h" // to get some defines available in every CryEngine project // Function attribute for printf/scanf-style parameters. @@ -277,47 +134,6 @@ #define PRINTF_EMPTY_FORMAT "" #endif -#if defined(IOS) -#define USE_PTHREAD_TLS -#endif - -// Storage class modifier for thread local storage. -// THEADLOCAL should NOT be defined to empty because that creates some -// really hard to find issues. -#if !defined(USE_PTHREAD_TLS) -# define THREADLOCAL AZ_TRAIT_COMPILER_THREAD_LOCAL -#endif //!defined(USE_PTHREAD_TLS) - - - -////////////////////////////////////////////////////////////////////////// -// define Read Write Barrier macro needed for lockless programming -////////////////////////////////////////////////////////////////////////// -#if defined(__arm__) -/** - * (ARMv7) Full memory barriar. - * - * None of GCC 4.6/4.8 or clang 3.3/3.4 have a builtin intrinsic for ARM's ldrex/strex or dmb - * instructions. This is a placeholder until supplied by the toolchain. - */ -inline void __dmb() -{ - // The linux kernel uses "dmb ish" to only sync with local monitor (arch/arm/include/asm/barrier.h): - //#define dmb(option) __asm__ __volatile__ ("dmb " #option : : : "memory") - //#define smp_mb() dmb(ish) - __asm__ __volatile__ ("dmb ish" : : : "memory"); -} - -#define READ_WRITE_BARRIER {__dmb(); } -#else - #define READ_WRITE_BARRIER -#endif -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// define macro to prevent memory reoderings of reads/and writes -//TODO implement for all GCC platforms, else there are potential crashes with strict aliasing - #define MEMORY_RW_REORDERING_BARRIER do { /*not implemented*/} while (0) //default stack size for threads, currently only used on pthread platforms #if defined(AZ_RESTRICTED_PLATFORM) @@ -325,7 +141,7 @@ inline void __dmb() #include AZ_RESTRICTED_FILE(platform_h) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(LINUX) || defined(APPLE) #if !defined(_DEBUG) #define SIMPLE_THREAD_STACK_SIZE_KB (256) @@ -362,22 +178,6 @@ inline void __dmb() #else #define _HELP(x) "" #endif -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Globally Used Defines. -////////////////////////////////////////////////////////////////////////// -// CPU Types: _CPU_X86,_CPU_AMD64,_CPU_G5 -// Platform: WIN23,WIN64,LINUX32,LINUX64,MAC -// CPU supported functionality: _CPU_SSE -////////////////////////////////////////////////////////////////////////// - - - #if defined(_MSC_VER) - #define PREFAST_SUPPRESS_WARNING(W) __pragma(warning(suppress: W)) - #else - #define PREFAST_SUPPRESS_WARNING(W) - #endif #ifdef _PREFAST_ # define PREFAST_ASSUME(cond) __analysis_assume(cond) @@ -385,49 +185,23 @@ inline void __dmb() # define PREFAST_ASSUME(cond) #endif - #if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_9 + #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_10 #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED #else - #if defined(WIN32) && !defined(WIN64) - #include "Win32specific.h" - #endif - #if defined(WIN64) #include "Win64specific.h" + #elif defined(LINUX64) + #include "Linux64Specific.h" + #elif defined(MAC) + #include "MacSpecific.h" + #elif defined(ANDROID) + #include "AndroidSpecific.h" + #elif defined(IOS) + #include "iOSSpecific.h" #endif #endif -#if defined(LINUX64) && !defined(ANDROID) -#include "Linux64Specific.h" -#endif - -#if defined(LINUX32) && !defined(ANDROID) -#include "Linux32Specific.h" -#endif - -#if defined(ANDROID) -#include "AndroidSpecific.h" -#endif - - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_10 - #include AZ_RESTRICTED_FILE(platform_h) -#endif - -#if defined(MAC) -#include "MacSpecific.h" -#endif - -#if defined(IOS) -#include "iOSSpecific.h" -#endif - #if !defined(TARGET_DEFAULT_ALIGN) # error "No default alignment specified for target architecture" @@ -480,12 +254,6 @@ ILINE DestinationType alias_cast(SourceType pPtr) #define DEPRECATED #endif -////////////////////////////////////////////////////////////////////////// -// compile time error stuff -////////////////////////////////////////////////////////////////////////// -#undef STATIC_CHECK -#define STATIC_CHECK(expr, msg) static_assert(expr, #msg) - // Assert dialog box macros #include "CryAssert.h" @@ -500,30 +268,8 @@ ILINE DestinationType alias_cast(SourceType pPtr) // Platform dependent functions that emulate Win32 API. // Mostly used only for debugging! ////////////////////////////////////////////////////////////////////////// -void CryDebugBreak(); void CrySleep(unsigned int dwMilliseconds); -void CryLowLatencySleep(unsigned int dwMilliseconds); int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType); -short CryGetAsyncKeyState(int vKey); -unsigned int CryGetFileAttributes(const char* lpFileName); - -inline void CryHeapCheck() -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_11 - #include AZ_RESTRICTED_FILE(platform_h) -#elif !defined(LINUX) && !defined(APPLE) // todo: this might be readded with later xdks? -#if !defined(NDEBUG) - int Result = -#endif - _heapchk(); - assert(Result != _HEAPBADBEGIN); - assert(Result != _HEAPBADNODE); - assert(Result != _HEAPBADPTR); - assert(Result != _HEAPEMPTY); - assert(Result == _HEAPOK); -#endif -} //--------------------------------------------------------------------------- // Useful function to clean the structure. @@ -554,77 +300,6 @@ inline D check_cast(S const& s) return d; } -// Convert one type to another, asserting there is no conversion loss. -// Usage: DestType dest; check_convert(dest, src); -template -inline D& check_convert(D& d, S const& s) -{ - d = D(s); - assert(S(d) == s); - return d; -} - -// Convert one type to another, asserting there is no conversion loss. -// Usage: DestType dest; check_convert(dest) = src; -template -struct CheckConvert -{ - CheckConvert(D& d) - : dest(&d) {} - - template - D& operator=(S const& s) - { - return check_convert(*dest, s); - } - -protected: - D* dest; -}; - -template -inline CheckConvert check_convert(D& d) -{ - return d; -} - -//--------------------------------------------------------------------------- -// Use NoCopy as a base class to easily prevent copy init & assign for any class. -struct NoCopy -{ - NoCopy() {} -private: - NoCopy(const NoCopy&); - NoCopy& operator =(const NoCopy&); -}; - -//--------------------------------------------------------------------------- -// ZeroInit: base class to zero the memory of the derived class before initialization, so local objects initialize the same as static. -// Usage: -// class MyClass: ZeroInit {...} -// class MyChild: public MyClass, ZeroInit {...} // ZeroInit must be the last base class - -template -struct ZeroInit -{ -#if defined(__clang__) || defined(__GNUC__) - bool __dummy; // Dummy var to create non-zero size, ensuring proper placement in TDerived -#endif - - ZeroInit(bool bZero = true) - { - // Optional bool arg to selectively disable zeroing. - if (bZero) - { - // Infer offset of this base class by static casting to derived class. - // Zero only the additional memory of the derived class. - TDerived* struct_end = static_cast(this) + 1; - size_t memory_size = (char*)struct_end - (char*)this; - memset(this, 0, memory_size); - } - } -}; - //--------------------------------------------------------------------------- // Quick const-manipulation macros @@ -705,29 +380,19 @@ threadID CryGetCurrentThreadId(); #include "CryFixedString.h" #endif -// need this in a common header file and any other file would be too misleading -enum ETriState -{ - eTS_false, - eTS_true, - eTS_maybe -}; - - #ifdef __GNUC__ - #define NO_INLINE __attribute__ ((noinline)) -# define NO_INLINE_WEAK __attribute__ ((noinline)) __attribute__((weak)) // marks a function as no_inline, but also as weak to prevent multiple-defined errors - -# define __PACKED __attribute__ ((packed)) - #else - #define NO_INLINE _declspec(noinline) -# define NO_INLINE_WEAK _declspec(noinline) inline - -# define __PACKED - #endif +#ifdef __GNUC__ + #define NO_INLINE __attribute__ ((noinline)) + #define NO_INLINE_WEAK __attribute__ ((noinline)) __attribute__((weak)) // marks a function as no_inline, but also as weak to prevent multiple-defined errors + #define __PACKED __attribute__ ((packed)) +#else + #define NO_INLINE _declspec(noinline) + #define NO_INLINE_WEAK _declspec(noinline) inline + #define __PACKED +#endif // Fallback for Alignment macro of GCC/CLANG (must be after the class definition) #if !defined(_ALIGN) - #define _ALIGN(num) AZ_POP_DISABLE_WARNING + #define _ALIGN(num) AZ_POP_DISABLE_WARNING #endif // Fallback for Alignment macro of MSVC (must be before the class definition) @@ -735,60 +400,13 @@ enum ETriState #define _MS_ALIGN(num) AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option") #endif -#if defined(WIN32) || defined(WIN64) -extern "C" { -__declspec(dllimport) unsigned long __stdcall TlsAlloc(); -__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long dwTlsIndex); -__declspec(dllimport) int __stdcall TlsSetValue(unsigned long dwTlsIndex, void* lpTlsValue); -} - - #define TLS_DECLARE(type, var) extern int var##idx; - #define TLS_DEFINE(type, var) \ - int var##idx; \ - struct Init##var { \ - Init##var() { var##idx = TlsAlloc(); } \ - }; \ - Init##var g_init##var; - #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) \ - int var##idx; \ - struct Init##var { \ - Init##var() { var##idx = TlsAlloc(); TlsSetValue(var##idx, reinterpret_cast(value)); } \ - }; \ - Init##var g_init##var; - #define TLS_GET(type, var) (type)TlsGetValue(var##idx) - #define TLS_SET(var, val) TlsSetValue(var##idx, reinterpret_cast(val)) -#elif defined(USE_PTHREAD_TLS) - #define TLS_DECLARE(_TYPE, _VAR) extern SCryPthreadTLS<_TYPE> _VAR##TLSKey; - #define TLS_DEFINE(_TYPE, _VAR) SCryPthreadTLS<_TYPE> _VAR##TLSKey; - #define TLS_DEFINE_DEFAULT_VALUE(_TYPE, _VAR, _DEFAULT) SCryPthreadTLS<_TYPE> _VAR##TLSKey = _DEFAULT; - #define TLS_GET(_TYPE, _VAR) _VAR##TLSKey.Get() - #define TLS_SET(_VAR, _VALUE) _VAR##TLSKey.Set(_VALUE) -#elif defined(THREADLOCAL) - #define TLS_DECLARE(type, var) extern THREADLOCAL type var; -#if defined(LINUX) || defined(MAC) - #define TLS_DEFINE(type, var) THREADLOCAL type var = 0; -#else - #define TLS_DEFINE(type, var) THREADLOCAL type var; -#endif // defined(LINUX) || defined(MAC) - #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) THREADLOCAL type var = value; - #define TLS_GET(type, var) (var) - #define TLS_SET(var, val) (var = (val)) -#else // defined(THREADLOCAL) - #error "There's no support for thread local storage" -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_13 #include AZ_RESTRICTED_FILE(platform_h) #elif !defined(LINUX) && !defined(APPLE) -typedef int socklen_t; + typedef int socklen_t; #endif - -// Include MultiThreading support. -#include "CryThread.h" -#include "MultiThread.h" - // In RELEASE disable printf and fprintf #if defined(_RELEASE) && !defined(RELEASE_LOGGING) #if defined(AZ_RESTRICTED_PLATFORM) @@ -797,19 +415,4 @@ typedef int socklen_t; #endif #endif -#define _STRINGIFY(x) #x -#define STRINGIFY(x) _STRINGIFY(x) - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_15 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) - #define MESSAGE(msg) message(__FILE__ "(" STRINGIFY(__LINE__) "): " msg) -#else - #define MESSAGE(msg) -#endif - void InitRootDir(char szExeFileName[] = nullptr, uint nExeSize = 0, char szExeRootName[] = nullptr, uint nRootSize = 0); diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index a677ba30b6..a919b9a002 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -204,17 +204,6 @@ void __stl_debug_message(const char* format_str, ...) #include "CryAssert_impl.h" -////////////////////////////////////////////////////////////////////////// -void CryDebugBreak() -{ -#if defined(WIN32) && !defined(RELEASE) - if (IsDebuggerPresent()) -#endif - { - DebugBreak(); - } -} - ////////////////////////////////////////////////////////////////////////// void CrySleep(unsigned int dwMilliseconds) { @@ -222,21 +211,6 @@ void CrySleep(unsigned int dwMilliseconds) Sleep(dwMilliseconds); } -////////////////////////////////////////////////////////////////////////// -void CryLowLatencySleep(unsigned int dwMilliseconds) -{ - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYLOWLATENCYSLEEP - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - CrySleep(dwMilliseconds); -#endif -} - ////////////////////////////////////////////////////////////////////////// int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const char* lpCaption, [[maybe_unused]] unsigned int uType) { @@ -302,16 +276,6 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], [[ma } } -////////////////////////////////////////////////////////////////////////// -short CryGetAsyncKeyState([[maybe_unused]] int vKey) -{ -#ifdef WIN32 - return GetAsyncKeyState(vKey); -#else - return 0; -#endif -} - ////////////////////////////////////////////////////////////////////////// LONG CryInterlockedIncrement(int volatile* lpAddend) { @@ -417,23 +381,6 @@ void CryLeaveCriticalSection(void* cs) LeaveCriticalSection((CRITICAL_SECTION*)cs); } -////////////////////////////////////////////////////////////////////////// -uint32 CryGetFileAttributes(const char* lpFileName) -{ - WIN32_FILE_ATTRIBUTE_DATA data; - BOOL res; -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYGETFILEATTRIBUTES - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - res = GetFileAttributesEx(lpFileName, GetFileExInfoStandard, &data); -#endif - return res ? data.dwFileAttributes : -1; -} - ////////////////////////////////////////////////////////////////////////// bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes) { diff --git a/Code/Legacy/CryCommon/smartptr.h b/Code/Legacy/CryCommon/smartptr.h index 246e18d541..6953348d47 100644 --- a/Code/Legacy/CryCommon/smartptr.h +++ b/Code/Legacy/CryCommon/smartptr.h @@ -13,6 +13,7 @@ #include #include +#include void CryFatalError(const char*, ...) PRINTF_PARAMS(1, 2); #if defined(APPLE) @@ -171,13 +172,13 @@ public: void AddRef() { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); + AZ_Assert(m_nRefCounter >= 0, "Invalid ref count"); ++m_nRefCounter; } void Release() { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); + AZ_Assert(m_nRefCounter > 0, "Invalid ref count"); if (--m_nRefCounter == 0) { delete static_cast(this); @@ -215,13 +216,13 @@ public: void AddRef() { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); + AZ_Assert(m_nRefCounter >= 0, "Invalid ref count"); ++m_nRefCounter; } void Release() { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); + AZ_Assert(m_nRefCounter > 0, "Invalid ref count"); if (--m_nRefCounter == 0) { delete this; @@ -272,13 +273,13 @@ public: void AddRef() { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); + AZ_Assert(m_nRefCounter >= 0, "Invalid ref count"); ++m_nRefCounter; } void Release() { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); + AZ_Assert(m_nRefCounter > 0, "Invalid ref count"); if (--m_nRefCounter == 0) { assert(m_pDeleteFnc); diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp index 4ca481be88..85b9ff4b79 100644 --- a/Code/Legacy/CrySystem/IDebugCallStack.cpp +++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp @@ -227,7 +227,7 @@ void IDebugCallStack::FatalError(const char* description) #if defined(WIN32) || !defined(_RELEASE) int* p = 0x0; - PREFAST_SUPPRESS_WARNING(6011) * p = 1; // we're intentionally crashing here + *p = 1; // we're intentionally crashing here #endif } diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp index cce3cf4aec..8ea653fb81 100644 --- a/Code/Legacy/CrySystem/SystemInit.cpp +++ b/Code/Legacy/CrySystem/SystemInit.cpp @@ -252,7 +252,7 @@ static void CmdCrashTest(IConsoleCmdArgs* pArgs) case 1: { int* p = 0; - PREFAST_SUPPRESS_WARNING(6011) * p = 0xABCD; + *p = 0xABCD; } break; case 2: diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index 2cc41adc08..1f5dc7d0b0 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -355,32 +355,25 @@ void CSystem::FatalError(const char* format, ...) IDebugCallStack::instance()->FatalError(szBuffer); #endif - CryDebugBreak(); - // app can not continue -#ifdef _DEBUG - -#if defined(WIN32) && !defined(WIN64) - DEBUG_BREAK; -#endif - -#else - -#if defined(WIN32) || defined(WIN64) - _flushall(); - // on windows, _exit does all sorts of things which can cause cleanup to fail during a crash, we need to terminate instead. - TerminateProcess(GetCurrentProcess(), 1); -#endif + AZ::Debug::Trace::Break(); -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemWin32_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - _exit(1); -#endif +#ifdef _DEBUG + #if defined(WIN32) || defined(WIN64) + _flushall(); + // on windows, _exit does all sorts of things which can cause cleanup to fail during a crash, we need to terminate instead. + TerminateProcess(GetCurrentProcess(), 1); + #endif + + #if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_2 + #include AZ_RESTRICTED_FILE(SystemWin32_cpp) + #endif + #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #else + _exit(1); + #endif #endif } diff --git a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp index a82e78c08c..3280c8daa9 100644 --- a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp @@ -26,7 +26,7 @@ if (count > 0) \ { \ const size_t memSize = count * sizeof(IViewSystemListener*); \ - PREFAST_SUPPRESS_WARNING(6255) IViewSystemListener * *pArray = (IViewSystemListener**) alloca(memSize); \ + IViewSystemListener* *pArray = (IViewSystemListener**) alloca(memSize); \ memcpy(pArray, &*m_listeners.begin(), memSize); \ while (count--) \ { \ diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp index 0493a64ca8..4fec4d3fd9 100644 --- a/Code/Legacy/CrySystem/XML/xml.cpp +++ b/Code/Legacy/CrySystem/XML/xml.cpp @@ -1390,7 +1390,7 @@ protected: { ((XmlParserImp*)userData)->onEndElement(name); } - static void characterData(void* userData, const char* s, int len) PREFAST_SUPPRESS_WARNING(6262) + static void characterData(void* userData, const char* s, int len) { char str[32700]; if (len > sizeof(str) - 1) diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp index d61090f79d..c28c13ba94 100644 --- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp +++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp @@ -26,12 +26,12 @@ ////////////////////////////////////////////////////////////////////////// // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(eUiAnimNodeType_ ## name) == g_animNodeEnumToStringMap.end()); \ - g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = STRINGIFY(name); \ - g_animNodeStringToEnumMap[string(STRINGIFY(name))] = eUiAnimNodeType_ ## name; + g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = AZ_STRINGIZE(name); \ + g_animNodeStringToEnumMap[string(AZ_STRINGIZE(name))] = eUiAnimNodeType_ ## name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(eUiAnimParamType_ ## name) == g_animParamEnumToStringMap.end()); \ - g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = STRINGIFY(name); \ - g_animParamStringToEnumMap[string(STRINGIFY(name))] = eUiAnimParamType_ ## name; + g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = AZ_STRINGIZE(name); \ + g_animParamStringToEnumMap[string(AZ_STRINGIZE(name))] = eUiAnimParamType_ ## name; namespace { diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp index b781dd6c82..589a084426 100644 --- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp @@ -74,12 +74,12 @@ static SMovieSequenceAutoComplete s_movieSequenceAutoComplete; ////////////////////////////////////////////////////////////////////////// // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(AnimNodeType::name) == g_animNodeEnumToStringMap.end()); \ - g_animNodeEnumToStringMap[AnimNodeType::name] = STRINGIFY(name); \ - g_animNodeStringToEnumMap[string(STRINGIFY(name))] = AnimNodeType::name; + g_animNodeEnumToStringMap[AnimNodeType::name] = AZ_STRINGIZE(name); \ + g_animNodeStringToEnumMap[string(AZ_STRINGIZE(name))] = AnimNodeType::name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(AnimParamType::name) == g_animParamEnumToStringMap.end()); \ - g_animParamEnumToStringMap[AnimParamType::name] = STRINGIFY(name); \ - g_animParamStringToEnumMap[string(STRINGIFY(name))] = AnimParamType::name; + g_animParamEnumToStringMap[AnimParamType::name] = AZ_STRINGIZE(name); \ + g_animParamStringToEnumMap[string(AZ_STRINGIZE(name))] = AnimParamType::name; namespace { From dcfeae1cc9ad9327552fbf48d78ca3bd594601f9 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 6 Aug 2021 16:24:06 -0700 Subject: [PATCH 151/251] warnings not previously detected (#2954) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Gems/LyShine/Code/Editor/Animation/UiAnimUndoManager.cpp | 2 +- Gems/LyShine/Code/Editor/AssetTreeEntry.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/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; From 360d0bdd0bde6fe56b1fdccc9bf017e221f3fd98 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 6 Aug 2021 16:42:38 -0700 Subject: [PATCH 152/251] removing more unused stuff Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../GridMate/Carrier/SocketDriver.cpp | 42 +++++----- Code/Legacy/CryCommon/AndroidSpecific.h | 13 --- Code/Legacy/CryCommon/AppleSpecific.h | 67 --------------- Code/Legacy/CryCommon/BaseTypes.h | 47 +++++------ Code/Legacy/CryCommon/BitFiddling.h | 40 --------- Code/Legacy/CryCommon/CompileTimeAssert.h | 56 ------------- Code/Legacy/CryCommon/CryArray.h | 2 +- Code/Legacy/CryCommon/CryCustomTypes.h | 4 +- Code/Legacy/CryCommon/CryHeaders.h | 2 +- Code/Legacy/CryCommon/CryLibrary.h | 1 - Code/Legacy/CryCommon/CryRandomInternal.h | 27 +++--- Code/Legacy/CryCommon/CryWindows.h | 19 ----- Code/Legacy/CryCommon/IMaterial.h | 2 +- Code/Legacy/CryCommon/ISystem.h | 83 +++++++++--------- Code/Legacy/CryCommon/ITexture.h | 4 +- Code/Legacy/CryCommon/Linux32Specific.h | 8 -- Code/Legacy/CryCommon/Linux64Specific.h | 8 -- Code/Legacy/CryCommon/LinuxSpecific.h | 84 ------------------- Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 2 - Code/Legacy/CryCommon/MacSpecific.h | 34 -------- Code/Legacy/CryCommon/Options.h | 2 +- Code/Legacy/CryCommon/StringUtils.h | 4 +- Code/Legacy/CryCommon/UnicodeBinding.h | 42 +++++----- Code/Legacy/CryCommon/UnicodeEncoding.h | 4 +- Code/Legacy/CryCommon/UnicodeFunctions.h | 4 +- Code/Legacy/CryCommon/UnicodeIterator.h | 4 +- Code/Legacy/CryCommon/Win32specific.h | 8 -- Code/Legacy/CryCommon/Win64specific.h | 8 -- Code/Legacy/CryCommon/crycommon_files.cmake | 2 - Code/Legacy/CryCommon/iOSSpecific.h | 2 - Code/Legacy/CryCommon/platform.h | 1 - Code/Legacy/CryCommon/stridedptr.h | 4 +- Code/Legacy/CrySystem/CrySystem_precompiled.h | 2 +- .../CrySystem/LevelSystem/LevelSystem.cpp | 4 - Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp | 2 +- Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp | 2 +- 36 files changed, 139 insertions(+), 501 deletions(-) delete mode 100644 Code/Legacy/CryCommon/CompileTimeAssert.h delete mode 100644 Code/Legacy/CryCommon/CryWindows.h diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp index b75de6f383..a72c6b54f6 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp @@ -1528,7 +1528,7 @@ namespace GridMate if (0 != WSAIoctl( m_socket, SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, &functionTableId, sizeof(GUID), (void**)&m_RIO_FN_TABLE, sizeof(m_RIO_FN_TABLE), &dwBytes, 0, 0)) { - AZ_Error("GridMate", false, "Could not initialize RIO: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not initialize RIO: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } else @@ -1543,13 +1543,13 @@ namespace GridMate if ((m_events[WakeupOnSend] = WSACreateEvent()) == WSA_INVALID_EVENT) { - AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if ((m_events[ReceiveEvent] = WSACreateEvent()) == WSA_INVALID_EVENT) { - AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } RIO_NOTIFICATION_COMPLETION typeRecv; @@ -1559,13 +1559,13 @@ namespace GridMate m_RIORecvQueue = m_RIO_FN_TABLE.RIOCreateCompletionQueue(maxOutstandingReceive, &typeRecv); if (m_RIORecvQueue == RIO_INVALID_CQ) { - AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if ((m_events[SendEvent] = WSACreateEvent()) == WSA_INVALID_EVENT) { - AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } RIO_NOTIFICATION_COMPLETION typeSend; @@ -1575,7 +1575,7 @@ namespace GridMate m_RIOSendQueue = m_RIO_FN_TABLE.RIOCreateCompletionQueue(maxOutstandingSend, &typeSend); if (m_RIOSendQueue == RIO_INVALID_CQ) { - AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1583,7 +1583,7 @@ namespace GridMate maxReceiveDataBuffers, maxOutstandingSend, maxSendDataBuffers, m_RIORecvQueue, m_RIOSendQueue, pContext); if (m_requestQueue == RIO_INVALID_RQ) { - AZ_Error("GridMate", m_requestQueue != NULL, "Could not RIOCreateRequestQueue: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", m_requestQueue != NULL, "Could not RIOCreateRequestQueue: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1596,24 +1596,24 @@ namespace GridMate //Setup Recv raw buffer and RIO record if (nullptr == (m_rawRecvBuffer = AllocRIOBuffer(bufferSize, m_RIORecvBufferCount, &recvAllocated))) { - AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (recvBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawRecvBuffer, bufferSize * m_RIORecvBufferCount))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } //Setup Recv address raw buffer and RIO record if (nullptr == (m_rawRecvAddressBuffer = AllocRIOBuffer(sizeof(SOCKADDR_INET), m_RIORecvBufferCount, &recvAddrsAllocated))) { - AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (recvAddressBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawRecvAddressBuffer, sizeof(SOCKADDR_INET) * m_RIORecvBufferCount))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1640,7 +1640,7 @@ namespace GridMate //Start Receive Handler if (false == m_RIO_FN_TABLE.RIOReceiveEx(m_requestQueue, &m_RIORecvBuffer[i], 1, NULL, &m_RIORecvAddressBuffer[i], NULL, NULL, 0, pBuffer)) { - AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } } @@ -1650,25 +1650,25 @@ namespace GridMate //setup send raw buffer and RIO record if (nullptr == (m_rawSendBuffer = AllocRIOBuffer(bufferSize, m_RIOSendBufferCount, &sendAllocated))) { - AZ_Error("GridMate", false, "Could not allocate buffer: %u", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate buffer: %u", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (sendBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawSendBuffer, m_RIOSendBufferCount * bufferSize))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } //setup send address raw buffer and RIO record if (nullptr == (m_rawSendAddressBuffer = AllocRIOBuffer(sizeof(SOCKADDR_INET), m_RIOSendBufferCount, &sendAddrsAllocated))) { - AZ_Error("GridMate", false, "Could not allocate send address buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate send address buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (sendAddressBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawSendAddressBuffer, m_RIOSendBufferCount * sizeof(SOCKADDR_INET)))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1726,7 +1726,7 @@ namespace GridMate if (!m_RIO_FN_TABLE.RIOSendEx(m_requestQueue, &m_RIOSendBuffer[m_workerNextSendBuffer], bufferCount, NULL, &m_RIOSendAddressBuffer[m_workerNextSendBuffer], NULL, NULL, 0, 0)) { - const DWORD lastError = ::WSAGetLastError(); + const DWORD lastError = GridMate::Platform::GetSocketError(); if (lastError == WSAENOBUFS) { continue; //spin until free @@ -1836,7 +1836,7 @@ namespace GridMate if (false == m_RIO_FN_TABLE.RIOReceiveEx(m_requestQueue, &m_RIORecvBuffer[m_RIONextRecvBuffer], bufferCount, NULL, &m_RIORecvAddressBuffer[m_RIONextRecvBuffer], NULL, NULL, 0, 0)) { - AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", GridMate::Platform::GetSocketError()); } if (recvd) @@ -1867,7 +1867,7 @@ namespace GridMate { if (!WSAResetEvent(m_events[Index - WSA_WAIT_EVENT_0])) { - AZ_Assert(false, "WSAResetEvent failed with error = %d\n", ::WSAGetLastError()); + AZ_Assert(false, "WSAResetEvent failed with error = %d\n", GridMate::Platform::GetSocketError()); } }; @@ -1926,7 +1926,7 @@ namespace GridMate } else if (isFailed(Index)) { - AZ_Assert(false, "WSAWaitForMultipleEvents failed with error = %d\n", ::WSAGetLastError()); + AZ_Assert(false, "WSAWaitForMultipleEvents failed with error = %d\n", GridMate::Platform::GetSocketError()); return false; } else @@ -1945,7 +1945,7 @@ namespace GridMate { if (!SetEvent(m_events[WakeupOnSend])) //Wake thread { - AZ_Assert(false, "SetEvent failed with error = %d\n", ::WSAGetLastError()); + AZ_Assert(false, "SetEvent failed with error = %d\n", GridMate::Platform::GetSocketError()); } } diff --git a/Code/Legacy/CryCommon/AndroidSpecific.h b/Code/Legacy/CryCommon/AndroidSpecific.h index a0f57553ca..cf4359ba47 100644 --- a/Code/Legacy/CryCommon/AndroidSpecific.h +++ b/Code/Legacy/CryCommon/AndroidSpecific.h @@ -30,15 +30,6 @@ #define MOBILE #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. -#define CRY_FORCE_MALLOC_NEW_ALIGN - -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 4 - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -120,10 +111,6 @@ typedef unsigned char byte; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #include "LinuxSpecific.h" // these functions do not exist int the wchar.h header diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index ed76de8986..87aea0fbb5 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -17,9 +17,6 @@ #pragma diagnostic ignore "-W#pragma-messages" #endif - -#define RC_EXECUTABLE "rc" - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -260,10 +257,6 @@ typedef uint64 __uint64; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #define BST_UNCHECKED 0x0000 @@ -296,17 +289,6 @@ enum IDCONTINUE = 11 }; -#define ES_MULTILINE 0x0004L -#define ES_AUTOVSCROLL 0x0040L -#define ES_AUTOHSCROLL 0x0080L -#define ES_WANTRETURN 0x1000L - -#define LB_ERR (-1) - -#define LB_ADDSTRING 0x0180 -#define LB_GETCOUNT 0x018B -#define LB_SETTOPINDEX 0x0197 - #define MB_OK 0x00000000L #define MB_OKCANCEL 0x00000001L #define MB_ABORTRETRYIGNORE 0x00000002L @@ -326,22 +308,16 @@ enum #define MB_APPLMODAL 0x00000000L -#define MF_STRING 0x00000000L - #define MK_LBUTTON 0x0001 #define MK_RBUTTON 0x0002 #define MK_SHIFT 0x0004 #define MK_CONTROL 0x0008 #define MK_MBUTTON 0x0010 -#define MK_ALT ( 0x20 ) - #define SM_MOUSEPRESENT 0x00000000L #define SM_CMOUSEBUTTONS 43 -#define USER_TIMER_MINIMUM 0x0000000A - #define VK_TAB 0x09 #define VK_SHIFT 0x10 #define VK_MENU 0x12 @@ -349,11 +325,6 @@ enum #define VK_SPACE 0x20 #define VK_DELETE 0x2E -#define VK_NUMPAD1 0x61 -#define VK_NUMPAD2 0x62 -#define VK_NUMPAD3 0x63 -#define VK_NUMPAD4 0x64 - #define VK_OEM_COMMA 0xBC // ',' any country #define VK_OEM_PERIOD 0xBE // '.' any country #define VK_OEM_3 0xC0 // '`~' for US @@ -496,36 +467,6 @@ typedef HANDLE HMENU; #endif //__cplusplus -inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength) -{ - char path[PATH_MAX]; - - if (realpath(relPath, path) == NULL) - { - return NULL; - } - const size_t len = std::min(strlen(path), maxLength - 1); - memcpy(absPath, path, len); - absPath[len] = 0; - return absPath; -} - -typedef union _LARGE_INTEGER -{ - struct - { - DWORD LowPart; - LONG HighPart; - }; - struct - { - DWORD LowPart; - LONG HighPart; - } u; - - long long QuadPart; -} LARGE_INTEGER; - extern bool QueryPerformanceCounter(LARGE_INTEGER*); extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency); @@ -566,14 +507,6 @@ inline int closesocket(int s) return ::close(s); } -inline int WSAGetLastError() -{ - return errno; -} - -//we take the definition of the pthread_t type directly from the pthread file -#define THREADID_NULL 0 - template char (*RtlpNumberOf( T (&)[N] ))[N]; diff --git a/Code/Legacy/CryCommon/BaseTypes.h b/Code/Legacy/CryCommon/BaseTypes.h index e8b6ae8ab7..0c588184a5 100644 --- a/Code/Legacy/CryCommon/BaseTypes.h +++ b/Code/Legacy/CryCommon/BaseTypes.h @@ -11,12 +11,9 @@ #define CRYINCLUDE_CRYCOMMON_BASETYPES_H #pragma once -#include "CompileTimeAssert.h" - - -COMPILE_TIME_ASSERT(sizeof(char) == 1); -COMPILE_TIME_ASSERT(sizeof(float) == 4); -COMPILE_TIME_ASSERT(sizeof(int) >= 4); +static_assert(sizeof(char) == 1); +static_assert(sizeof(float) == 4); +static_assert(sizeof(int) >= 4); typedef unsigned char uchar; @@ -36,35 +33,35 @@ typedef signed long slong; typedef unsigned long long ulonglong; typedef signed long long slonglong; -COMPILE_TIME_ASSERT(sizeof(uchar) == sizeof(schar)); -COMPILE_TIME_ASSERT(sizeof(ushort) == sizeof(sshort)); -COMPILE_TIME_ASSERT(sizeof(uint) == sizeof(sint)); -COMPILE_TIME_ASSERT(sizeof(ulong) == sizeof(slong)); -COMPILE_TIME_ASSERT(sizeof(ulonglong) == sizeof(slonglong)); +static_assert(sizeof(uchar) == sizeof(schar)); +static_assert(sizeof(ushort) == sizeof(sshort)); +static_assert(sizeof(uint) == sizeof(sint)); +static_assert(sizeof(ulong) == sizeof(slong)); +static_assert(sizeof(ulonglong) == sizeof(slonglong)); -COMPILE_TIME_ASSERT(sizeof(uchar) <= sizeof(ushort)); -COMPILE_TIME_ASSERT(sizeof(ushort) <= sizeof(uint)); -COMPILE_TIME_ASSERT(sizeof(uint) <= sizeof(ulong)); -COMPILE_TIME_ASSERT(sizeof(ulong) <= sizeof(ulonglong)); +static_assert(sizeof(uchar) <= sizeof(ushort)); +static_assert(sizeof(ushort) <= sizeof(uint)); +static_assert(sizeof(uint) <= sizeof(ulong)); +static_assert(sizeof(ulong) <= sizeof(ulonglong)); typedef schar int8; typedef schar sint8; typedef uchar uint8; -COMPILE_TIME_ASSERT(sizeof(uint8) == 1); -COMPILE_TIME_ASSERT(sizeof(sint8) == 1); +static_assert(sizeof(uint8) == 1); +static_assert(sizeof(sint8) == 1); typedef sshort int16; typedef sshort sint16; typedef ushort uint16; -COMPILE_TIME_ASSERT(sizeof(uint16) == 2); -COMPILE_TIME_ASSERT(sizeof(sint16) == 2); +static_assert(sizeof(uint16) == 2); +static_assert(sizeof(sint16) == 2); typedef sint int32; typedef sint sint32; typedef uint uint32; -COMPILE_TIME_ASSERT(sizeof(uint32) == 4); -COMPILE_TIME_ASSERT(sizeof(sint32) == 4); +static_assert(sizeof(uint32) == 4); +static_assert(sizeof(sint32) == 4); typedef slonglong int64; @@ -72,14 +69,14 @@ typedef slonglong int64; #define O3DE_INT64_DEFINED typedef slonglong sint64; typedef ulonglong uint64; -COMPILE_TIME_ASSERT(sizeof(uint64) == 8); -COMPILE_TIME_ASSERT(sizeof(sint64) == 8); +static_assert(sizeof(uint64) == 8); +static_assert(sizeof(sint64) == 8); #endif typedef float f32; typedef double f64; -COMPILE_TIME_ASSERT(sizeof(f32) == 4); -COMPILE_TIME_ASSERT(sizeof(f64) == 8); +static_assert(sizeof(f32) == 4); +static_assert(sizeof(f64) == 8); #endif // CRYINCLUDE_CRYCOMMON_BASETYPES_H diff --git a/Code/Legacy/CryCommon/BitFiddling.h b/Code/Legacy/CryCommon/BitFiddling.h index 342aad9a82..36173c5e53 100644 --- a/Code/Legacy/CryCommon/BitFiddling.h +++ b/Code/Legacy/CryCommon/BitFiddling.h @@ -12,7 +12,6 @@ #pragma once -#include "CompileTimeAssert.h" #include // Section dictionary @@ -188,45 +187,6 @@ ILINE int32 Isel32(int32 v, int32 alt) return ((static_cast(v) >> 31) & alt) | ((static_cast(~v) >> 31) & v); } -template -struct CompileTimeIntegerLog2 -{ - static const uint32 result = 1 + CompileTimeIntegerLog2<(ILOG >> 1)>::result; -}; -template <> -struct CompileTimeIntegerLog2<1> -{ - static const uint32 result = 0; -}; -template <> -struct CompileTimeIntegerLog2<0>; // keep it undefined, we cannot represent "minus infinity" result - -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<1>::result == 0); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<2>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<3>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<4>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<5>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<255>::result == 7); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<256>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<257>::result == 8); - -template -struct CompileTimeIntegerLog2_RoundUp -{ - static const uint32 result = CompileTimeIntegerLog2::result + ((ILOG & (ILOG - 1)) != 0); -}; -template <> -struct CompileTimeIntegerLog2_RoundUp<0>; // we can return 0, but let's keep it undefined (same as CompileTimeIntegerLog2<0>) - -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<1>::result == 0); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<2>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<3>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<4>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<5>::result == 3); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<255>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<256>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<257>::result == 9); - // Character-to-bitfield mapping inline uint32 AlphaBit(char c) diff --git a/Code/Legacy/CryCommon/CompileTimeAssert.h b/Code/Legacy/CryCommon/CompileTimeAssert.h deleted file mode 100644 index 80a2ecf6bf..0000000000 --- a/Code/Legacy/CryCommon/CompileTimeAssert.h +++ /dev/null @@ -1,56 +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 - * - */ - -// Inspired by the Boost library's BOOST_STATIC_ASSERT(), -// see http://www.boost.org/doc/libs/1_49_0/doc/html/boost_staticassert/how.html -// or http://www.boost.org/libs/static_assert - -#ifndef CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H -#define CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H -#pragma once - -#if defined(__cplusplus) -/* -template -struct COMPILE_TIME_ASSERT_FAIL; - -template <> -struct COMPILE_TIME_ASSERT_FAIL -{ -}; - -template -struct COMPILE_TIME_ASSERT_TEST -{ - enum { dummy = i }; -}; - -#define COMPILE_TIME_ASSERT_BUILD_NAME2(x, y) x##y -#define COMPILE_TIME_ASSERT_BUILD_NAME1(x, y) COMPILE_TIME_ASSERT_BUILD_NAME2(x, y) -#define COMPILE_TIME_ASSERT_BUILD_NAME(x, y) COMPILE_TIME_ASSERT_BUILD_NAME1(x, y) - -#ifndef __RECODE__ - #define COMPILE_TIME_ASSERT(expr) \ - typedef COMPILE_TIME_ASSERT_TEST)> \ - COMPILE_TIME_ASSERT_BUILD_NAME(compile_time_assert_test_, __LINE__) - // note: for MS Visual Studio we could use __COUNTER__ instead of __LINE__ -#else - #define COMPILE_TIME_ASSERT(expr) -#endif // __RECODE__ - -#else - -#define COMPILE_TIME_ASSERT(expr) -*/ -#endif - -#define COMPILE_TIME_ASSERT_MSG(expr, msg) static_assert(expr, msg) -#define COMPILE_TIME_ASSERT(expr) COMPILE_TIME_ASSERT_MSG(expr, "Compile Time Assert") - - -#endif // CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H diff --git a/Code/Legacy/CryCommon/CryArray.h b/Code/Legacy/CryCommon/CryArray.h index 5b4684fdd2..ac935e5c45 100644 --- a/Code/Legacy/CryCommon/CryArray.h +++ b/Code/Legacy/CryCommon/CryArray.h @@ -771,7 +771,7 @@ namespace NArray AP& allocator() { - COMPILE_TIME_ASSERT(sizeof(AP) == sizeof(A)); + static_assert(sizeof(AP) == sizeof(A)); return *(AP*)this; } const AP& allocator() const diff --git a/Code/Legacy/CryCommon/CryCustomTypes.h b/Code/Legacy/CryCommon/CryCustomTypes.h index 9594f5a333..3b5b62e2f6 100644 --- a/Code/Legacy/CryCommon/CryCustomTypes.h +++ b/Code/Legacy/CryCommon/CryCustomTypes.h @@ -708,8 +708,8 @@ protected: static inline S FromFloat(float fIn) { - COMPILE_TIME_ASSERT(sizeof(S) <= 4); - COMPILE_TIME_ASSERT(nEXP_BITS > 0 && nEXP_BITS <= 8 && nEXP_BITS < sizeof(S) * 8 - 4); + static_assert(sizeof(S) <= 4); + static_assert(nEXP_BITS > 0 && nEXP_BITS <= 8 && nEXP_BITS < sizeof(S) * 8 - 4); // Clamp to allowed range. float fClamped = clamp_tpl(fIn * fROUNDER(), fMIN(), fMAX()); diff --git a/Code/Legacy/CryCommon/CryHeaders.h b/Code/Legacy/CryCommon/CryHeaders.h index 6b4ea0ba3a..4d037b52d9 100644 --- a/Code/Legacy/CryCommon/CryHeaders.h +++ b/Code/Legacy/CryCommon/CryHeaders.h @@ -17,7 +17,7 @@ #ifdef MAX_SUB_MATERIALS // This checks that the values are in sync in the different files. -COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128); +static_assert(MAX_SUB_MATERIALS == 128); #else #define MAX_SUB_MATERIALS 128 #endif diff --git a/Code/Legacy/CryCommon/CryLibrary.h b/Code/Legacy/CryCommon/CryLibrary.h index ca1ca5d067..787085af00 100644 --- a/Code/Legacy/CryCommon/CryLibrary.h +++ b/Code/Legacy/CryCommon/CryLibrary.h @@ -63,7 +63,6 @@ using DetachEnvironmentFunction = void(*)(); #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif - #include HMODULE CryLoadLibrary(const char* libName); diff --git a/Code/Legacy/CryCommon/CryRandomInternal.h b/Code/Legacy/CryCommon/CryRandomInternal.h index 9499ba0774..ca74041189 100644 --- a/Code/Legacy/CryCommon/CryRandomInternal.h +++ b/Code/Legacy/CryCommon/CryRandomInternal.h @@ -13,7 +13,6 @@ #include // std::numeric_limits #include // std::make_unsigned #include "BaseTypes.h" // uint32, uint64 -#include "CompileTimeAssert.h" #include "Cry_Vector2.h" #include "Cry_Vector3.h" #include "Cry_Vector4.h" @@ -24,10 +23,10 @@ namespace CryRandom_Internal template struct BoundedRandomUint { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); - COMPILE_TIME_ASSERT(sizeof(T) == size); - COMPILE_TIME_ASSERT(sizeof(T) <= sizeof(uint32)); + static_assert(std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_signed); + static_assert(sizeof(T) == size); + static_assert(sizeof(T) <= sizeof(uint32)); inline static T Get(R& randomGenerator, const T maxValue) { @@ -41,9 +40,9 @@ namespace CryRandom_Internal template struct BoundedRandomUint { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); - COMPILE_TIME_ASSERT(sizeof(T) == sizeof(uint64)); + static_assert(std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_signed); + static_assert(sizeof(T) == sizeof(uint64)); inline static T Get(R& randomGenerator, const T maxValue) { @@ -65,11 +64,11 @@ namespace CryRandom_Internal template struct BoundedRandom { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); + static_assert(std::numeric_limits::is_integer); typedef typename std::make_unsigned::type UT; - COMPILE_TIME_ASSERT(sizeof(T) == sizeof(UT)); - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); + static_assert(sizeof(T) == sizeof(UT)); + static_assert(std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_signed); inline static T Get(R& randomGenerator, T minValue, T maxValue) { @@ -84,7 +83,7 @@ namespace CryRandom_Internal template struct BoundedRandom { - COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_integer); inline static T Get(R& randomGenerator, const T minValue, const T maxValue) { @@ -139,7 +138,7 @@ namespace CryRandom_Internal inline VT GetRandomUnitVector(R& randomGenerator) { typedef typename VT::value_type T; - COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_integer); VT res; T lenSquared; diff --git a/Code/Legacy/CryCommon/CryWindows.h b/Code/Legacy/CryCommon/CryWindows.h deleted file mode 100644 index 77684384c6..0000000000 --- a/Code/Legacy/CryCommon/CryWindows.h +++ /dev/null @@ -1,19 +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 : Specific header to handle Windows.h include - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H -#define CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H -#pragma once - -#include - -#endif // CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H diff --git a/Code/Legacy/CryCommon/IMaterial.h b/Code/Legacy/CryCommon/IMaterial.h index f1967324d8..c5cd5712dc 100644 --- a/Code/Legacy/CryCommon/IMaterial.h +++ b/Code/Legacy/CryCommon/IMaterial.h @@ -41,7 +41,7 @@ struct IRenderMesh; #ifdef MAX_SUB_MATERIALS // This checks that the values are in sync in the different files. -COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128); +static_assert(MAX_SUB_MATERIALS == 128); #else #define MAX_SUB_MATERIALS 128 #endif diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index 7cea690687..2820a2fd8d 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -24,7 +24,6 @@ #endif #include "CryAssert.h" -#include "CompileTimeAssert.h" #include @@ -1428,10 +1427,10 @@ namespace Detail # define DeclareConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) } # define DeclareStaticConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) } -# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, strname, defaultValue); } -# define DefineConstIntCVar(name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, (#name), defaultValue); } +# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, strname, defaultValue); } +# define DefineConstIntCVar(name, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, (#name), defaultValue); } // DefineConstIntCVar2 is deprecated, any such instance can be converted to the 3 variant by removing the quotes around the first parameter -# define DefineConstIntCVar3(name, _var_, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(_var_)); REGISTER_DUMMY_CVAR(int, name, defaultValue); } +# define DefineConstIntCVar3(name, _var_, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(_var_)); REGISTER_DUMMY_CVAR(int, name, defaultValue); } # define AllocateConstIntCVar(scope, name) # define DefineConstFloatCVar(name, flags, help) { REGISTER_DUMMY_CVAR(float, (#name), name ## Default); } @@ -1543,33 +1542,33 @@ static void AssertConsoleExists(void) #define ILLEGAL_DEV_FLAGS (VF_NET_SYNCED | VF_CHEAT | VF_CHEAT_ALWAYS_CHECK | VF_CHEAT_NOCHECK | VF_READONLY | VF_CONST_CVAR) #if defined(_RELEASE) -#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val -#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val /* _onchangefunction consumed; callback not available */ -#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val -#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val -#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val -#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val +#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val +#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val /* _onchangefunction consumed; callback not available */ +#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val +#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val +#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val +#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val #define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) /* consumed; command not available */ #else -#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) #endif // defined(_RELEASE) // //////////////////////////////////////////////////////////////////////////////// @@ -1586,19 +1585,19 @@ static void AssertConsoleExists(void) // TODO Registering all cvars for Dedicated server as well. Currently CrySystems have no concept of Dedicated server with cmake. // If we introduce server specific targets for CrySystems, we can add DEDICATED_SERVER flags to those and add the flag back in here. #if defined(_RELEASE) -#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) #else #define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) #define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction) diff --git a/Code/Legacy/CryCommon/ITexture.h b/Code/Legacy/CryCommon/ITexture.h index 5b9b43ceb5..170e3b6709 100644 --- a/Code/Legacy/CryCommon/ITexture.h +++ b/Code/Legacy/CryCommon/ITexture.h @@ -314,8 +314,8 @@ public: void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { - COMPILE_TIME_ASSERT(eTT_MaxTexType <= 255); - COMPILE_TIME_ASSERT(eTF_MaxFormat <= 255); + static_assert(eTT_MaxTexType <= 255); + static_assert(eTF_MaxFormat <= 255); /*LATER*/ } diff --git a/Code/Legacy/CryCommon/Linux32Specific.h b/Code/Legacy/CryCommon/Linux32Specific.h index e66838f431..6812ddb818 100644 --- a/Code/Legacy/CryCommon/Linux32Specific.h +++ b/Code/Legacy/CryCommon/Linux32Specific.h @@ -18,10 +18,6 @@ #define _CPU_X86 //#define _CPU_SSE -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 4 - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -97,10 +93,6 @@ typedef unsigned char byte; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #include "LinuxSpecific.h" diff --git a/Code/Legacy/CryCommon/Linux64Specific.h b/Code/Legacy/CryCommon/Linux64Specific.h index 0aa9321025..4dcb5f1e84 100644 --- a/Code/Legacy/CryCommon/Linux64Specific.h +++ b/Code/Legacy/CryCommon/Linux64Specific.h @@ -20,10 +20,6 @@ #define _CPU_AMD64 #define _CPU_SSE -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 8 - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -103,10 +99,6 @@ typedef uint8 byte; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #include "LinuxSpecific.h" diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h index cbffae5957..a587350cb2 100644 --- a/Code/Legacy/CryCommon/LinuxSpecific.h +++ b/Code/Legacy/CryCommon/LinuxSpecific.h @@ -182,7 +182,6 @@ typedef int64 __int64; typedef uint64 __uint64; #endif -#define THREADID_NULL -1 typedef unsigned long int threadID; #define TRUE 1 @@ -213,27 +212,6 @@ typedef unsigned long int threadID; #define _wtof(str) wcstod(str, 0) -/*static unsigned char toupper(unsigned char c) -{ - return c & ~0x40; -} -*/ -typedef union _LARGE_INTEGER -{ - struct - { - DWORD LowPart; - LONG HighPart; - }; - struct - { - DWORD LowPart; - LONG HighPart; - } u; - long long QuadPart; -} LARGE_INTEGER; - - // stdlib.h stuff #define _MAX_DRIVE 3 // max. length of drive component #define _MAX_DIR 256 // max. length of path component @@ -257,21 +235,6 @@ typedef union _LARGE_INTEGER #define _O_SEQUENTIAL 0x0020 /* file access is primarily sequential */ #define _O_RANDOM 0x0010 /* file access is primarily random */ -// curses.h stubs for PDcurses keys -#define PADENTER KEY_MAX + 1 -#define CTL_HOME KEY_MAX + 2 -#define CTL_END KEY_MAX + 3 -#define CTL_PGDN KEY_MAX + 4 -#define CTL_PGUP KEY_MAX + 5 - -// stubs for virtual keys, isn't used on Linux -#define VK_UP 0 -#define VK_DOWN 0 -#define VK_RIGHT 0 -#define VK_LEFT 0 -#define VK_CONTROL 0 -#define VK_SCROLL 0 - enum { IDOK = 1, @@ -285,17 +248,6 @@ enum IDCONTINUE = 11 }; -#define ES_MULTILINE 0x0004L -#define ES_AUTOVSCROLL 0x0040L -#define ES_AUTOHSCROLL 0x0080L -#define ES_WANTRETURN 0x1000L - -#define LB_ERR (-1) - -#define LB_ADDSTRING 0x0180 -#define LB_GETCOUNT 0x018B -#define LB_SETTOPINDEX 0x0197 - #define MB_OK 0x00000000L #define MB_OKCANCEL 0x00000001L #define MB_ABORTRETRYIGNORE 0x00000002L @@ -315,22 +267,16 @@ enum #define MB_APPLMODAL 0x00000000L -#define MF_STRING 0x00000000L - #define MK_LBUTTON 0x0001 #define MK_RBUTTON 0x0002 #define MK_SHIFT 0x0004 #define MK_CONTROL 0x0008 #define MK_MBUTTON 0x0010 -#define MK_ALT ( 0x20 ) - #define SM_MOUSEPRESENT 0x00000000L #define SM_CMOUSEBUTTONS 43 -#define USER_TIMER_MINIMUM 0x0000000A - #define VK_TAB 0x09 #define VK_SHIFT 0x10 #define VK_MENU 0x12 @@ -338,11 +284,6 @@ enum #define VK_SPACE 0x20 #define VK_DELETE 0x2E -#define VK_NUMPAD1 0x61 -#define VK_NUMPAD2 0x62 -#define VK_NUMPAD3 0x63 -#define VK_NUMPAD4 0x64 - #define VK_OEM_COMMA 0xBC // ',' any country #define VK_OEM_PERIOD 0xBE // '.' any country #define VK_OEM_3 0xC0 // '`~' for US @@ -529,36 +470,11 @@ inline int64 CryGetTicksPerSec() inline int _CrtCheckMemory() { return 1; }; -inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength) -{ - char path[PATH_MAX]; - - if (realpath(relPath, path) == NULL) - { - return NULL; - } - const size_t len = std::min(strlen(path), maxLength - 1); - memcpy(absPath, path, len); - absPath[len] = 0; - return absPath; -} - typedef void* HGLRC; typedef void* HDC; typedef void* PROC; typedef void* PIXELFORMATDESCRIPTOR; -#define SCOPED_ENABLE_FLOAT_EXCEPTIONS - -// Linux_Win32Wrapper.h now included directly by platform.h -//#include "Linux_Win32Wrapper.h" - -#define closesocket close -inline int WSAGetLastError() -{ - return errno; -} - template char (*RtlpNumberOf( T (&)[N] ))[N]; diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 23cd7faf7f..2de17e6b28 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -490,8 +490,6 @@ extern void adaptFilenameToLinux(char* rAdjustedFilename); extern const int comparePathNames(const char* cpFirst, const char* cpSecond, unsigned int len);//returns 0 if identical extern void replaceDoublePathFilename(char* szFileName);//removes "\.\" to "\" and "/./" to "/" -////////////////////////////////////////////////////////////////////////// -extern char* _fullpath(char* absPath, const char* relPath, size_t maxLength); ////////////////////////////////////////////////////////////////////////// extern void _makepath(char* path, const char* drive, const char* dir, const char* filename, const char* ext); diff --git a/Code/Legacy/CryCommon/MacSpecific.h b/Code/Legacy/CryCommon/MacSpecific.h index 30bcd6c6db..0533a1b556 100644 --- a/Code/Legacy/CryCommon/MacSpecific.h +++ b/Code/Legacy/CryCommon/MacSpecific.h @@ -24,40 +24,6 @@ #define _CPU_SSE #define PLATFORM_64BIT -#define USE_CRT 1 -#define SIZEOF_PTR 8 - typedef uint64_t threadID; - -// curses.h stubs for PDcurses keys -#define PADENTER KEY_MAX + 1 -#define CTL_HOME KEY_MAX + 2 -#define CTL_END KEY_MAX + 3 -#define CTL_PGDN KEY_MAX + 4 -#define CTL_PGUP KEY_MAX + 5 - -// stubs for virtual keys, isn't used on Mac -#define VK_UP 0 -#define VK_DOWN 0 -#define VK_RIGHT 0 -#define VK_LEFT 0 -#define VK_CONTROL 0 -#define VK_SCROLL 0 - -#define MAC_NOT_IMPLEMENTED assert(false); - - -typedef enum -{ - eDAContinue, - eDAIgnore, - eDAIgnoreAll, - eDABreak, - eDAStop, - eDAReportAsBug -} EDialogAction; - -extern EDialogAction MacOSXHandleAssert(const char* condition, const char* file, int line, const char* reason, bool); - #endif // CRYINCLUDE_CRYCOMMON_MACSPECIFIC_H diff --git a/Code/Legacy/CryCommon/Options.h b/Code/Legacy/CryCommon/Options.h index 925f1f747e..935c8bd371 100644 --- a/Code/Legacy/CryCommon/Options.h +++ b/Code/Legacy/CryCommon/Options.h @@ -80,7 +80,7 @@ private: typedef Struc TThis; typedef Int TInt; \ TInt Mask() const { return *(const TInt*)this; } \ TInt& Mask() { return *(TInt*)this; } \ - Struc(TInt init = 0) { COMPILE_TIME_ASSERT(sizeof(TThis) == sizeof(TInt)); Mask() = init; } \ + Struc(TInt init = 0) { static_assert(sizeof(TThis) == sizeof(TInt)); Mask() = init; } \ #define BIT_VAR(Var) \ TInt _##Var : 1; \ diff --git a/Code/Legacy/CryCommon/StringUtils.h b/Code/Legacy/CryCommon/StringUtils.h index ffd1001f95..d6c3d829d2 100644 --- a/Code/Legacy/CryCommon/StringUtils.h +++ b/Code/Legacy/CryCommon/StringUtils.h @@ -65,7 +65,7 @@ namespace CryStringUtils_Internal template inline bool strcpy_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); + static_assert(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); if (!dst || dst_size_in_bytes < sizeof(TChar)) { @@ -97,7 +97,7 @@ namespace CryStringUtils_Internal template inline bool strcat_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); + static_assert(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); if (!dst || dst_size_in_bytes < sizeof(TChar)) { diff --git a/Code/Legacy/CryCommon/UnicodeBinding.h b/Code/Legacy/CryCommon/UnicodeBinding.h index e6e82aaf49..7a058650b5 100644 --- a/Code/Legacy/CryCommon/UnicodeBinding.h +++ b/Code/Legacy/CryCommon/UnicodeBinding.h @@ -211,7 +211,7 @@ namespace Unicode >::type >::type CharType; static const size_t FixedSize = extent::value; - COMPILE_TIME_ASSERT(!is_array::value || FixedSize > 0); + static_assert(!is_array::value || FixedSize > 0); static const bool isConstArray = is_array::value && is_const::type>::value; static const bool isBufferArray = is_array::value && !isConstArray; static const bool isPointer = is_pointer::value; @@ -393,7 +393,7 @@ namespace Unicode sizeof(CharType) == 1 ? eEncoding_UTF8 : sizeof(CharType) == 2 ? eEncoding_UTF16 : eEncoding_UTF32; - COMPILE_TIME_ASSERT(value != eEncoding_UTF32 || sizeof(CharType) == 4); + static_assert(value != eEncoding_UTF32 || sizeof(CharType) == 4); }; // SBindCharacter: @@ -408,7 +408,7 @@ namespace Unicode template struct SBindCharacter { - COMPILE_TIME_ASSERT(is_arithmetic::value); + static_assert(is_arithmetic::value); typedef typename remove_cv::type UnqualifiedType; typedef typename conditional::type type; }; @@ -417,7 +417,7 @@ namespace Unicode { typedef typename conditional::type type; typedef typename SDependentType::type ActuallyQChar; // Force two-phase name lookup on QChar. - COMPILE_TIME_ASSERT(sizeof(ActuallyQChar) == sizeof(type)); // In case Qt ever changes QChar. + static_assert(sizeof(ActuallyQChar) == sizeof(type)); // In case Qt ever changes QChar. }; // SBindPointer: @@ -425,7 +425,7 @@ namespace Unicode template struct SBindPointer { - COMPILE_TIME_ASSERT(is_pointer::value || is_array::value); + static_assert(is_pointer::value || is_array::value); typedef typename conditional< is_pointer::value, typename remove_pointer::type, @@ -458,8 +458,8 @@ namespace Unicode { // Allow casts from pointer-to-integral to unrelated pointer-to-integral, provided they are of the same size. typedef typename remove_pointer::type TargetChar; - COMPILE_TIME_ASSERT(is_integral::value && is_integral::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); + static_assert(is_integral::value && is_integral::value); + static_assert(sizeof(SourceChar) == sizeof(TargetChar)); return reinterpret_cast(ptr); } template @@ -467,8 +467,8 @@ namespace Unicode { // Allow casts from pointer-to-QChar to unrelated pointer-to-integral, provided they are of the same size. typedef typename remove_pointer::type TargetChar; - COMPILE_TIME_ASSERT(is_integral::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); + static_assert(is_integral::value); + static_assert(sizeof(SourceChar) == sizeof(TargetChar)); return reinterpret_cast(ptr); } template @@ -612,7 +612,7 @@ namespace Unicode template inline void Feed(const InputStringType& in, Sink& out, integral_constant) { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); + static_assert(is_array::value && extent::value > 0); typedef typename SBindPointer::type PointerType; const size_t length = extent::value - 1; PointerType ptr = SafeCast(in); @@ -630,7 +630,7 @@ namespace Unicode template inline void Feed(const InputStringType& in, Sink& out, integral_constant) { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); + static_assert(is_array::value && extent::value > 0); typedef typename SBindPointer::type PointerType; typedef typename SBindPointer::BoundCharType CharType; const size_t length = extent::value; @@ -652,7 +652,7 @@ namespace Unicode template inline void Feed(const InputStringType& in, Sink& out, integral_constant) { - COMPILE_TIME_ASSERT(is_pointer::value); + static_assert(is_pointer::value); typedef typename SBindPointer::type PointerType; typedef typename SBindPointer::BoundCharType CharType; PointerType ptr = SafeCast(in); @@ -677,7 +677,7 @@ namespace Unicode template inline void Feed(const InputCharType& in, Sink& out, integral_constant) { - COMPILE_TIME_ASSERT(is_arithmetic::value); + static_assert(is_arithmetic::value); const uint32 item = static_cast(in); out(item); } @@ -711,7 +711,7 @@ namespace Unicode template inline size_t EncodedLength(const InputStringType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); + static_assert(is_array::value && extent::value > 0); return extent::value - 1; } @@ -720,7 +720,7 @@ namespace Unicode template inline size_t EncodedLength(const InputStringType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); + static_assert(is_array::value && extent::value > 0); typedef typename remove_extent::type CharType; return SCharacterTrait::StrNLen(in, extent::value); } @@ -738,7 +738,7 @@ namespace Unicode template inline size_t EncodedLength(const InputStringType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_pointer::value); + static_assert(is_pointer::value); typedef typename remove_pointer::type CharType; return in ? SCharacterTrait::StrLen(in) : 0; } @@ -748,7 +748,7 @@ namespace Unicode template inline size_t EncodedLength([[maybe_unused]] const InputCharType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_arithmetic::value); + static_assert(is_arithmetic::value); return 1; } @@ -775,7 +775,7 @@ namespace Unicode template inline const void* EncodedPointer(const InputStringType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); + static_assert(is_array::value && extent::value > 0); return in; // We can just let the array type decay to a pointer. } @@ -784,7 +784,7 @@ namespace Unicode template inline const void* EncodedPointer(const InputStringType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); + static_assert(is_array::value && extent::value > 0); return in; // We can just let the array type decay to a pointer. } @@ -793,7 +793,7 @@ namespace Unicode template inline const void* EncodedPointer(const InputStringType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_pointer::value); + static_assert(is_pointer::value); return in; // Implied } @@ -802,7 +802,7 @@ namespace Unicode template inline const void* EncodedPointer(const InputCharType& in, integral_constant) { - COMPILE_TIME_ASSERT(is_arithmetic::value); + static_assert(is_arithmetic::value); return ∈ // Take the address of the parameter (which is kept on the stack of the caller). } diff --git a/Code/Legacy/CryCommon/UnicodeEncoding.h b/Code/Legacy/CryCommon/UnicodeEncoding.h index a3e20b639c..fb2d398cb6 100644 --- a/Code/Legacy/CryCommon/UnicodeEncoding.h +++ b/Code/Legacy/CryCommon/UnicodeEncoding.h @@ -17,7 +17,7 @@ #pragma once #include "BaseTypes.h" // For uint8, uint16, uint32 -#include "CompileTimeAssert.h" // For COMPILE_TIME_ASSERT macro + namespace Unicode { // Supported encoding/conversion types. @@ -631,7 +631,7 @@ namespace Unicode struct SRecoveryFallbackHelper { // A compilation error here means RecoveryMethod value was unexpected here - COMPILE_TIME_ASSERT( + static_assert( RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace || RecoveryMethod == eErrorRecovery_FallbackWin1252ThenDiscard || diff --git a/Code/Legacy/CryCommon/UnicodeFunctions.h b/Code/Legacy/CryCommon/UnicodeFunctions.h index 48debe9706..31fc7991c3 100644 --- a/Code/Legacy/CryCommon/UnicodeFunctions.h +++ b/Code/Legacy/CryCommon/UnicodeFunctions.h @@ -266,7 +266,7 @@ namespace Unicode inline size_t LengthSafe(const InputStringType& source) { // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding::value); + static_assert(SIsSafeEncoding::value); // Bind methods. const EBind bindMethod = SBindObject::value; @@ -379,7 +379,7 @@ namespace Unicode inline size_t ConvertSafe(OutputStringType& target, const InputStringType& source) { // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding::value); + static_assert(SIsSafeEncoding::value); // Bind methods. const EBind inputBindMethod = SBindObject::value; diff --git a/Code/Legacy/CryCommon/UnicodeIterator.h b/Code/Legacy/CryCommon/UnicodeIterator.h index d939eaa721..c28378ea44 100644 --- a/Code/Legacy/CryCommon/UnicodeIterator.h +++ b/Code/Legacy/CryCommon/UnicodeIterator.h @@ -27,7 +27,7 @@ namespace Unicode template inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, const integral_constant) { - COMPILE_TIME_ASSERT( + static_assert( Encoding == eEncoding_ASCII || Encoding == eEncoding_UTF32 || Encoding == eEncoding_Latin1 || @@ -88,7 +88,7 @@ namespace Unicode template inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, const integral_constant) { - COMPILE_TIME_ASSERT( + static_assert( Encoding == eEncoding_ASCII || Encoding == eEncoding_UTF32 || Encoding == eEncoding_Latin1 || diff --git a/Code/Legacy/CryCommon/Win32specific.h b/Code/Legacy/CryCommon/Win32specific.h index 0519bb1022..62d32138b4 100644 --- a/Code/Legacy/CryCommon/Win32specific.h +++ b/Code/Legacy/CryCommon/Win32specific.h @@ -23,10 +23,7 @@ #define ILINE __forceinline #endif -#define RC_EXECUTABLE "rc.exe" #define DEPRECATED __declspec(deprecated) -#define TYPENAME(x) typeid(x).name() -#define SIZEOF_PTR 4 #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 @@ -54,8 +51,6 @@ ////////////////////////////////////////////////////////////////////////// #include "BaseTypes.h" -#define THREADID_NULL -1 - typedef unsigned char BYTE; typedef unsigned int threadID; typedef unsigned long DWORD; @@ -111,14 +106,11 @@ int64 CryGetTicksPerSec(); __declspec(align(num)) #define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name; #ifndef FILE_ATTRIBUTE_NORMAL #define FILE_ATTRIBUTE_NORMAL 0x00000080 #endif -#define FP16_TERRAIN #define TARGET_DEFAULT_ALIGN (0x4U) diff --git a/Code/Legacy/CryCommon/Win64specific.h b/Code/Legacy/CryCommon/Win64specific.h index b1e86f9250..47c9c1aad9 100644 --- a/Code/Legacy/CryCommon/Win64specific.h +++ b/Code/Legacy/CryCommon/Win64specific.h @@ -19,10 +19,7 @@ #define _CPU_SSE #define ILINE __forceinline -#define RC_EXECUTABLE "rc.exe" #define DEPRECATED __declspec(deprecated) -#define TYPENAME(x) typeid(x).name() -#define SIZEOF_PTR 8 #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 @@ -51,7 +48,6 @@ ////////////////////////////////////////////////////////////////////////// #include "BaseTypes.h" -#define THREADID_NULL -1 typedef long LONG; typedef unsigned char BYTE; typedef unsigned long threadID; @@ -93,10 +89,6 @@ int64 CryGetTicksPerSec(); __declspec(align(num)) #define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name; - -#define SIZEOF_PTR 8 #ifndef FILE_ATTRIBUTE_NORMAL #define FILE_ATTRIBUTE_NORMAL 0x00000080 diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index 0392f11c89..18cbd16f4b 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -68,7 +68,6 @@ set(FILES LCGRandom.h CryTypeInfo.cpp BaseTypes.h - CompileTimeAssert.h MemoryAccess.h AnimKey.h BitFiddling.h @@ -165,7 +164,6 @@ set(FILES CryThread_windows.h CryThreadImpl_pthreads.h CryThreadImpl_windows.h - CryWindows.h Linux32Specific.h Linux64Specific.h Linux_Win32Wrapper.h diff --git a/Code/Legacy/CryCommon/iOSSpecific.h b/Code/Legacy/CryCommon/iOSSpecific.h index d2503a7441..ac2461b55b 100644 --- a/Code/Legacy/CryCommon/iOSSpecific.h +++ b/Code/Legacy/CryCommon/iOSSpecific.h @@ -47,11 +47,9 @@ #define VK_SCROLL 0 -//#define USE_CRT 1 #if !defined(PLATFORM_64BIT) #error "IOS build only supports the 64bit architecture" #else -#define SIZEOF_PTR 8 typedef uint64_t threadID; #endif diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index fb96056beb..9ff461543f 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -263,7 +263,6 @@ ILINE DestinationType alias_cast(SourceType pPtr) #define assert CRY_ASSERT #endif -#include "CompileTimeAssert.h" ////////////////////////////////////////////////////////////////////////// // Platform dependent functions that emulate Win32 API. // Mostly used only for debugging! diff --git a/Code/Legacy/CryCommon/stridedptr.h b/Code/Legacy/CryCommon/stridedptr.h index 737a1e40b7..8a74aa97b1 100644 --- a/Code/Legacy/CryCommon/stridedptr.h +++ b/Code/Legacy/CryCommon/stridedptr.h @@ -66,9 +66,9 @@ private: # if !defined(eLittleEndian) # error eLittleEndian is not defined, please include CryEndian.h. # endif - COMPILE_TIME_ASSERT(metautils::is_const::value || !metautils::is_const::value); + static_assert(metautils::is_const::value || !metautils::is_const::value); // note: we allow xint32 -> xint16 converting - COMPILE_TIME_ASSERT( + static_assert( (metautils::is_same::type, typename metautils::remove_const::type>::value || ((metautils::is_same::type, sint32>::value || metautils::is_same::type, uint32>::value || diff --git a/Code/Legacy/CrySystem/CrySystem_precompiled.h b/Code/Legacy/CrySystem/CrySystem_precompiled.h index f59adccb7b..daf1c335e4 100644 --- a/Code/Legacy/CrySystem/CrySystem_precompiled.h +++ b/Code/Legacy/CrySystem/CrySystem_precompiled.h @@ -68,7 +68,7 @@ #endif #ifdef WIN32 -#include +#include #include #undef GetCharWidth #undef GetUserName diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index ffaf0e7210..b1fd9de7c0 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -33,10 +33,6 @@ #include -#ifdef WIN32 -#include -#endif - namespace LegacyLevelSystem { static constexpr const char* ArchiveExtension = ".pak"; diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp index bd31fb3ba4..be44c4b212 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp @@ -194,7 +194,7 @@ void XMLBinary::XMLBinaryReader::CheckHeader(const BinaryFileHeader& header, siz // Check the signature of the file to make sure that it is a binary XML file. { static const char signature[] = "CryXmlB"; - COMPILE_TIME_ASSERT(sizeof(signature) == sizeof(header.szSignature)); + static_assert(sizeof(signature) == sizeof(header.szSignature)); if (memcmp(header.szSignature, signature, sizeof(header.szSignature)) != 0) { result = eResult_NotBinXml; diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp index 1500717ddc..9490e9aae0 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp @@ -109,7 +109,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, BinaryFileHeader header; static const char signature[] = "CryXmlB"; - COMPILE_TIME_ASSERT(sizeof(signature) == sizeof(header.szSignature)); + static_assert(sizeof(signature) == sizeof(header.szSignature)); memcpy(header.szSignature, signature, sizeof(header.szSignature)); nTheoreticalPosition += sizeof(header); align(nTheoreticalPosition, nAlignment); From 64cff38f8294338371555ef737008be3879f2a28 Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Sun, 8 Aug 2021 16:46:42 -0700 Subject: [PATCH 153/251] Addressing PR feedback and fixed a small issue with the draw item count display Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../Code/Include/Atom/RHI/ShaderResourceGroupDebug.h | 12 +++++++++++- .../RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp | 6 +++--- Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp | 12 ++++++------ .../RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp | 6 +++--- .../RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp | 4 +++- 5 files changed, 26 insertions(+), 14 deletions(-) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h index b81f9e0c0b..d9ea77d823 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h @@ -14,8 +14,18 @@ namespace AZ struct DrawItem; class ShaderResourceGroup; + /// Given a ShaderResourceGroup and a reference ConstantsData input, this function will fetch the ConstantsData on the SRG and compare it + /// to the reference ConstantsData. It will print the names of any constants that are different between the two. + /// The parameter updateReferenceData can be used to set the reference data to the SRG's constant data after the comparison. This is + /// useful for keeping track of differences in between calls to the function, such as between frames. void PrintConstantDataDiff(const ShaderResourceGroup& shaderResourceGroup, ConstantsData& referenceData, bool updateReferenceData = false); - void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData = false); + + /// Given a DrawItem, an SRG binding slot on that draw item and a reference ConstantsData input, this function will fetch the ConstantsData + /// from the draw item's SRG at the binding slot and compare it to the reference ConstantsData. It will print the names of any constants + /// that are different between the two. + /// The parameter updateReferenceData can be used to set the reference data to the draw item's constant data after the comparison. This is + /// useful for keeping track of differences in between calls to the function, such as between frames. + void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, uint32_t srgBindingSlot, bool updateReferenceData = false); } } diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp index f14d1d4c4e..8be053e4ef 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp @@ -151,11 +151,11 @@ namespace AZ void ConstantsLayout::DebugPrintNames(AZStd::array_view constantList) const { AZStd::string output; - for (const ShaderInputConstantIndex& constandIdx : constantList) + for (const ShaderInputConstantIndex& constantIdx : constantList) { - if (constandIdx.GetIndex() < m_inputs.size()) + if (constantIdx.GetIndex() < m_inputs.size()) { - output += m_inputs[constandIdx.GetIndex()].m_name.GetCStr(); + output += m_inputs[constantIdx.GetIndex()].m_name.GetCStr(); output += " - "; } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp index d4caa3dd66..1524883e54 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp @@ -408,26 +408,26 @@ namespace AZ bool ConstantsData::ConstantIsEqual(const ConstantsData& other, ShaderInputConstantIndex inputIndex) const { - AZStd::array_view myConstans = GetConstantRaw(inputIndex); - AZStd::array_view otherConstans = other.GetConstantRaw(inputIndex); + AZStd::array_view myConstant = GetConstantRaw(inputIndex); + AZStd::array_view otherConstant = other.GetConstantRaw(inputIndex); // If they point to the same data, they are equal - if (myConstans == otherConstans) + if (myConstant == otherConstant) { return true; } // If they point to data of different size, they are not equal - if (myConstans.size() != otherConstans.size()) + if (myConstant.size() != otherConstant.size()) { return false; } // If they point to differing data of same size, compare the data // Note: due to small size of data this loop will be faster than a mem compare - for(uint32_t i = 0; i < myConstans.size(); ++i) + for(uint32_t i = 0; i < myConstant.size(); ++i) { - if (myConstans[i] != otherConstans[i]) + if (myConstant[i] != otherConstant[i]) { return false; } diff --git a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp index 4bd8d0aab8..54399eba88 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp @@ -36,10 +36,10 @@ namespace AZ } } - void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData) + void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, uint32_t srgBindingSlot, bool updateReferenceData) { - s32 srgIndex = -1; - for (u32 i = 0; i < drawItem.m_shaderResourceGroupCount; ++i) + int srgIndex = -1; + for (uint32_t i = 0; i < drawItem.m_shaderResourceGroupCount; ++i) { if (drawItem.m_shaderResourceGroups[i]->GetBindingSlot() == srgBindingSlot) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index 13f2215c8b..2e61542c36 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -166,11 +166,14 @@ namespace AZ // clean up data m_drawListView = {}; m_combinedDrawList.clear(); + m_drawItemCount = 0; // draw list from view was sorted and if it's the only draw list then we can use it directly if (viewDrawList.size() > 0 && drawLists.size() == 0) { m_drawListView = viewDrawList; + m_drawItemCount += viewDrawList.size(); + PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); return; } @@ -178,7 +181,6 @@ namespace AZ drawLists.push_back(viewDrawList); // combine draw items from mutiple draw lists to one draw list and sort it. - m_drawItemCount = 0; for (auto drawList : drawLists) { m_drawItemCount += drawList.size(); From 5f1e973b3f6953233869544de32bdbc856d9bf63 Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Sun, 8 Aug 2021 23:34:09 -0700 Subject: [PATCH 154/251] Removing condition from View SRG compilation Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../RPI/Code/Include/Atom/RPI.Public/View.h | 6 -- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 88 ++++++++----------- 2 files changed, 36 insertions(+), 58 deletions(-) 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; From 733dc31518f106972b5d2e902c8ce49c08a84cac Mon Sep 17 00:00:00 2001 From: Benjamin Jillich Date: Thu, 5 Aug 2021 16:37:47 +0200 Subject: [PATCH 155/251] Fixed emfx unit tests Signed-off-by: Benjamin Jillich --- .../RCExt/Actor/ActorGroupExporter.cpp | 2 -- .../Code/EMotionFX/Rendering/Common/Camera.h | 1 + .../EMotionFX/Rendering/Common/RenderUtil.cpp | 24 ++++++++++--------- .../Rendering/Common/ScaleManipulator.h | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Actor.h | 2 +- .../Code/EMotionFX/Source/ActorInstance.cpp | 2 +- .../Source/RenderPlugin/RenderWidget.cpp | 2 +- .../Components/EditorActorComponent.cpp | 4 ++-- .../Code/Tests/Integration/CanAddActor.cpp | 2 +- .../Code/Tests/TestAssetCode/ActorFactory.h | 2 +- .../Code/Tests/TestAssets/Rin/rin.actor | 4 ++-- 11 files changed, 24 insertions(+), 23 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp index ba8168476c..a498ed2cb7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp @@ -49,8 +49,6 @@ namespace EMotionFX if (serializeContext) { // Increasing the version number of the actor group exporter will make sure all actor products will be force re-generated. - // Version history: - // v3: Introduced Actor_Nodes2 (replaced Actor_Nodes) and Actor_Node2 (replaced Actor_Node) serializeContext->Class()->Version(3); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h index 0c7b19384e..6a95621b0d 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" diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index 8464cb2b2a..9c0a4af895 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -240,8 +240,8 @@ namespace MCommon // render selection gizmo around the given AABB void RenderUtil::RenderSelection(const AZ::Aabb& box, const MCore::RGBAColor& color, bool directlyRender) { - const AZ::Vector3 min = box.GetMin(); - const AZ::Vector3 max = box.GetMax(); + 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; @@ -249,15 +249,17 @@ namespace MCommon 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.h index 8cfd3ec541..6d2f167893 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" diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h index 1c1173a9a2..faf5b6b94d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index 162d826ca4..b80aab3c50 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -635,7 +635,7 @@ namespace EMotionFX } // Expand the bounding volume by a tolerance area in case set. - if (m_boundsExpandBy > 0.0f) + if (!AZ::IsClose(m_boundsExpandBy, 0.0f)) { const AZ::Vector3 center = m_aabb.GetCenter(); const AZ::Vector3 halfExtents = m_aabb.GetExtents() * 0.5f; 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 fb0ce4fdbf..25ae2ba2d4 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 diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index ed5333da9c..160cbe8ee4 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -67,7 +67,7 @@ namespace EMotionFX "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 (Expensive)") + ->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", @@ -75,7 +75,7 @@ namespace EMotionFX "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, 0.0f) + ->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") 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/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/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 From 659e486cd791f7da4d1cf12fdd08fa2048bdb8b2 Mon Sep 17 00:00:00 2001 From: hultonha <82228511+hultonha@users.noreply.github.com> Date: Mon, 9 Aug 2021 11:56:19 +0100 Subject: [PATCH 156/251] Add an integration test to validate pick mode crash (#2935) * add an integration test to validate pick mode crash Signed-off-by: hultonha * update to test after review feedback Signed-off-by: hultonha --- .../UnitTest/AzToolsFrameworkTestHelpers.cpp | 29 +++++++++++++ .../UnitTest/AzToolsFrameworkTestHelpers.h | 26 ++++++----- .../Framework/AzToolsFramework/CMakeLists.txt | 2 + ...EditorTransformComponentSelectionTests.cpp | 43 +++++++++++++++++++ 4 files changed, 89 insertions(+), 11 deletions(-) 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; From 12505da6fcf9e3970dc97e4ae43b93bac587908a Mon Sep 17 00:00:00 2001 From: John Jones-Steele Date: Mon, 9 Aug 2021 16:01:18 +0100 Subject: [PATCH 157/251] Changed locale handling and added tests Signed-off-by: John Jones-Steele --- Code/Editor/CryEdit.cpp | 3 -- .../Application/AzQtApplication.cpp | 2 - .../AzQtComponents/Gallery/main.cpp | 2 - .../Tests/FloatToStringConversionTests.cpp | 40 +++++++++++++++++++ .../ProjectManager/Source/Application.cpp | 2 - 5 files changed, 40 insertions(+), 9 deletions(-) diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index cd1dd4fe47..47ad7e5381 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -1626,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 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..a0a8155475 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp @@ -64,3 +64,43 @@ TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorOnlyOneDecimal) int numDecimalPlaces = 2; EXPECT_EQ(AzQtComponents::toString(1000.000, numDecimalPlaces, testLocal, showThousandsSeparator), "1,000.0"); } + +TEST(AzQtComponents, FloatToString_Truncate2DecimalsWithLocale) +{ + QLocale testLocal{ QLocale() }; + + const bool showThousandsSeparator = false; + const int numDecimalPlaces = 2; + QString testString = "0" + QString(testLocal.decimalPoint()) + "12"; + EXPECT_EQ(AzQtComponents::toString(0.1234, numDecimalPlaces, testLocal, showThousandsSeparator), testString); +} + +TEST(AzQtComponents, FloatToString_AllZerosButOneWithLocale) +{ + QLocale testLocal{ QLocale() }; + + const bool showThousandsSeparator = false; + const int numDecimalPlaces = 2; + QString testString = "1" + QString(testLocal.decimalPoint()) + "0"; + EXPECT_EQ(AzQtComponents::toString(1.0000, numDecimalPlaces, testLocal, showThousandsSeparator), testString); +} + +TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorTruncateNoRoundWithLocale) +{ + QLocale testLocal{ QLocale() }; + + const bool showThousandsSeparator = true; + const int numDecimalPlaces = 3; + QString testString = "1" + QString(testLocal.groupSeparator()) + "000" + QString(testLocal.decimalPoint()) + "123"; + EXPECT_EQ(AzQtComponents::toString(1000.1236, numDecimalPlaces, testLocal, showThousandsSeparator), testString); +} + +TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorOnlyOneDecimalWithLocale) +{ + QLocale testLocal{ QLocale() }; + + const bool showThousandsSeparator = true; + int numDecimalPlaces = 2; + QString testString = "1" + QString(testLocal.groupSeparator()) + "000" + QString(testLocal.decimalPoint()) + "0"; + EXPECT_EQ(AzQtComponents::toString(1000.000, numDecimalPlaces, testLocal, showThousandsSeparator), testString); +} 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); From 3b60862237ace01f572fd1d333a28a8e0021070c Mon Sep 17 00:00:00 2001 From: John Jones-Steele Date: Mon, 9 Aug 2021 16:30:49 +0100 Subject: [PATCH 158/251] Fixed order of tests Signed-off-by: John Jones-Steele --- .../AzQtComponents/Tests/FloatToStringConversionTests.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp index a0a8155475..21db675324 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp @@ -72,7 +72,7 @@ TEST(AzQtComponents, FloatToString_Truncate2DecimalsWithLocale) const bool showThousandsSeparator = false; const int numDecimalPlaces = 2; QString testString = "0" + QString(testLocal.decimalPoint()) + "12"; - EXPECT_EQ(AzQtComponents::toString(0.1234, numDecimalPlaces, testLocal, showThousandsSeparator), testString); + EXPECT_EQ(testString, AzQtComponents::toString(0.1234, numDecimalPlaces, testLocal, showThousandsSeparator)); } TEST(AzQtComponents, FloatToString_AllZerosButOneWithLocale) @@ -82,7 +82,7 @@ TEST(AzQtComponents, FloatToString_AllZerosButOneWithLocale) const bool showThousandsSeparator = false; const int numDecimalPlaces = 2; QString testString = "1" + QString(testLocal.decimalPoint()) + "0"; - EXPECT_EQ(AzQtComponents::toString(1.0000, numDecimalPlaces, testLocal, showThousandsSeparator), testString); + EXPECT_EQ(testString, AzQtComponents::toString(1.0000, numDecimalPlaces, testLocal, showThousandsSeparator)); } TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorTruncateNoRoundWithLocale) @@ -92,7 +92,7 @@ TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorTruncateNoRound const bool showThousandsSeparator = true; const int numDecimalPlaces = 3; QString testString = "1" + QString(testLocal.groupSeparator()) + "000" + QString(testLocal.decimalPoint()) + "123"; - EXPECT_EQ(AzQtComponents::toString(1000.1236, numDecimalPlaces, testLocal, showThousandsSeparator), testString); + EXPECT_EQ(testString, AzQtComponents::toString(1000.1236, numDecimalPlaces, testLocal, showThousandsSeparator)); } TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorOnlyOneDecimalWithLocale) @@ -102,5 +102,5 @@ TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorOnlyOneDecimalW const bool showThousandsSeparator = true; int numDecimalPlaces = 2; QString testString = "1" + QString(testLocal.groupSeparator()) + "000" + QString(testLocal.decimalPoint()) + "0"; - EXPECT_EQ(AzQtComponents::toString(1000.000, numDecimalPlaces, testLocal, showThousandsSeparator), testString); + EXPECT_EQ(testString, AzQtComponents::toString(1000.000, numDecimalPlaces, testLocal, showThousandsSeparator)); } From 8884227fe6cdf0dd5235ac041e68247229d287cd Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:11 -0700 Subject: [PATCH 159/251] Remove MCore::Array This translates all usages of MCore::Array to AZStd::vector. It is designed to be as minimal of a change as possible (no changing to range-for loops or other C++11 stuff). We can decide to submit this wholesale, or submit it to a separate branch that we can then integrate individual files from once we're ready to do a specific class's transition. It does not completely solve the `uint32`->`size_t` transition. One important finding from doing this: `MCore::Array` uses a `memcpy` when it reallocates. `AZStd::vector` will use the contained type's copy or move constructor, per element. This is a significant change in behavior. If you have type, `SomeStruct` that defines a destructor, that type is copyable and not movable. So if you have a `MCore::Array`, and you call `Add(); Add(); Add()`, that reallocates 3 times, copying the contents using `memcpy`, and never invokes `SomeStruct`'s copy constructor or destructor. Translating that to `AZStd::vector` and calling `push_back(); push_back(); push_back();` will still reallocate 3 times, but it sees that `SomeStruct` is non-movable, and uses the copy constructor to make the copies, and then the destructor on the previous values. This call to the destructor wasn't there before, and can cause things to be deleted that weren't before. The solution to this is to make that struct be a move-only type. Where possible, this was done by changing that type to use `AZStd::unique_ptr` instead of a raw pointer, to get the proper move behavior. Where that is not possible (types that inherit from `MCore::MemoryObject`), a hand-written move constructor was created. In general: GetLength() becomes size() GetMaxLength() becomes capacity() GetIsEmpty() becomes empty() Reserve() becomes reserve() ReserveExact() becomes reserve() Resize() becomes resize() ResizeFast() becomes resize_no_construct() Add() becomes emplace_back() AddExact() becomes emplace_back() AddEmpty() becomes emplace_back() AddEmptyExact() becomes emplace_back() GetPtr() becomes data() GetItem() becomes at() Shrink() becomes shrink_to_fit() GetFirst() becomes front() GetLast() becomes back() Remove() becomes erase() RemoveFirst() becomes erase() RemoveLast() becomes pop_back() RemoveByValue() becomes if (const auto it = AZStd::find(...); it != end(container)) container.erase(it); Insert() becomes emplace() Swap() becomes swap() Clear(true) becomes clear(); shrink_to_fit() Clear() becomes clear(); shrink_to_fit() Clear(false) becomes clear() Swap() becomes swap() Find() becomes AZStd::find MoveElements() becomes AZStd::move SetMemoryCategory() is removed Signed-off-by: Chris Burel --- .../CommandSystem/Source/ActorCommands.h | 2 +- .../Source/AnimGraphNodeCommands.cpp | 4 +- .../Source/AnimGraphParameterCommands.cpp | 2 +- .../Source/AnimGraphParameterCommands.h | 2 +- .../Source/MotionEventCommands.cpp | 6 +- .../Source/MotionEventCommands.h | 2 +- .../Source/SelectionCommands.cpp | 6 +- .../CommandSystem/Source/SelectionCommands.h | 2 +- .../Exporters/ExporterLib/Exporter/Exporter.h | 5 +- .../ExporterLib/Exporter/MaterialExport.cpp | 10 +- .../ExporterLib/Exporter/NodeExport.cpp | 24 +- .../EMotionFX/Rendering/Common/RenderUtil.cpp | 22 +- .../EMotionFX/Rendering/Common/RenderUtil.h | 20 +- .../Rendering/OpenGL2/Source/GBuffer.cpp | 2 +- .../Rendering/OpenGL2/Source/GLActor.cpp | 33 +- .../Rendering/OpenGL2/Source/GLRenderUtil.cpp | 17 +- .../Rendering/OpenGL2/Source/GLRenderUtil.h | 4 +- .../Rendering/OpenGL2/Source/GLSLShader.cpp | 53 +- .../Rendering/OpenGL2/Source/GLSLShader.h | 18 +- .../OpenGL2/Source/GraphicsManager.cpp | 6 +- .../OpenGL2/Source/GraphicsManager.h | 2 +- .../Rendering/OpenGL2/Source/Material.h | 2 +- .../OpenGL2/Source/PostProcessShader.cpp | 2 +- .../Rendering/OpenGL2/Source/ShaderCache.cpp | 15 +- .../OpenGL2/Source/StandardMaterial.cpp | 12 +- .../OpenGL2/Source/StandardMaterial.h | 2 +- .../Rendering/OpenGL2/Source/TextureCache.cpp | 19 +- .../Rendering/OpenGL2/Source/TextureCache.h | 4 +- .../Rendering/OpenGL2/Source/glactor.h | 14 +- .../Rendering/OpenGL2/Source/shadercache.h | 4 +- .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 182 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Actor.h | 59 +- .../Code/EMotionFX/Source/ActorInstance.cpp | 68 +- .../Code/EMotionFX/Source/ActorInstance.h | 14 +- .../Code/EMotionFX/Source/ActorManager.cpp | 43 +- .../Code/EMotionFX/Source/ActorManager.h | 12 +- .../Code/EMotionFX/Source/AnimGraph.cpp | 20 +- .../Code/EMotionFX/Source/AnimGraph.h | 8 +- .../Source/AnimGraphGameControllerSettings.h | 8 +- .../EMotionFX/Source/AnimGraphInstance.cpp | 44 +- .../Code/EMotionFX/Source/AnimGraphInstance.h | 6 +- .../Code/EMotionFX/Source/AnimGraphManager.h | 2 +- .../Code/EMotionFX/Source/AnimGraphNode.cpp | 12 +- .../Code/EMotionFX/Source/AnimGraphNode.h | 6 +- .../Code/EMotionFX/Source/AnimGraphObject.cpp | 4 +- .../Code/EMotionFX/Source/AnimGraphObject.h | 4 +- .../EMotionFX/Source/AnimGraphPosePool.cpp | 36 +- .../Code/EMotionFX/Source/AnimGraphPosePool.h | 12 +- .../Source/AnimGraphRefCountedDataPool.cpp | 38 +- .../Source/AnimGraphRefCountedDataPool.h | 12 +- .../Source/AnimGraphReferenceNode.cpp | 2 +- .../EMotionFX/Source/AnimGraphReferenceNode.h | 2 +- .../Source/AnimGraphStateMachine.cpp | 2 +- .../EMotionFX/Source/AnimGraphStateMachine.h | 2 +- .../Source/AnimGraphStateTransition.cpp | 4 +- .../Source/AnimGraphStateTransition.h | 2 +- .../EMotionFX/Source/DualQuatSkinDeformer.h | 2 +- .../EMotionFX/Source/EMotionFXManager.cpp | 13 +- .../Code/EMotionFX/Source/EMotionFXManager.h | 8 +- .../Code/EMotionFX/Source/EventManager.h | 2 +- .../Source/Importer/ChunkProcessors.cpp | 14 +- .../Source/Importer/ChunkProcessors.h | 4 +- .../EMotionFX/Source/Importer/Importer.cpp | 75 +- .../Code/EMotionFX/Source/Importer/Importer.h | 20 +- .../EMotionFX/Source/KeyTrackLinearDynamic.h | 11 +- .../Source/KeyTrackLinearDynamic.inl | 14 - Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 112 ++- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h | 18 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl | 8 +- .../EMotionFX/Source/MeshDeformerStack.cpp | 40 +- .../Code/EMotionFX/Source/MeshDeformerStack.h | 6 +- .../EMotionFX/Source/MorphMeshDeformer.cpp | 21 +- .../Code/EMotionFX/Source/MorphMeshDeformer.h | 4 +- .../Code/EMotionFX/Source/MorphSetup.cpp | 41 +- .../Code/EMotionFX/Source/MorphSetup.h | 6 +- .../EMotionFX/Source/MorphSetupInstance.cpp | 5 +- .../EMotionFX/Source/MorphSetupInstance.h | 6 +- .../Code/EMotionFX/Source/MorphTarget.cpp | 7 +- .../Code/EMotionFX/Source/MorphTarget.h | 5 - .../EMotionFX/Source/MorphTargetStandard.cpp | 25 +- .../EMotionFX/Source/MorphTargetStandard.h | 6 +- .../Code/EMotionFX/Source/MotionGroup.cpp | 277 ------ .../Code/EMotionFX/Source/MotionInstance.cpp | 4 +- .../Code/EMotionFX/Source/MotionInstance.h | 2 +- .../EMotionFX/Source/MotionInstancePool.cpp | 64 +- .../EMotionFX/Source/MotionInstancePool.h | 6 +- .../EMotionFX/Source/MotionLayerSystem.cpp | 43 +- .../Code/EMotionFX/Source/MotionLayerSystem.h | 4 +- .../Code/EMotionFX/Source/MotionManager.cpp | 57 +- .../Code/EMotionFX/Source/MotionManager.h | 10 +- .../Code/EMotionFX/Source/MotionQueue.cpp | 15 +- .../Code/EMotionFX/Source/MotionQueue.h | 6 +- .../Code/EMotionFX/Source/MotionSystem.cpp | 50 +- .../Code/EMotionFX/Source/MotionSystem.h | 8 +- .../EMotionFX/Source/MultiThreadScheduler.cpp | 33 +- .../EMotionFX/Source/MultiThreadScheduler.h | 14 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp | 49 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.h | 12 +- .../Code/EMotionFX/Source/NodeMap.cpp | 28 +- .../EMotionFX/Code/EMotionFX/Source/NodeMap.h | 6 +- .../Code/EMotionFX/Source/Recorder.cpp | 121 ++- .../Code/EMotionFX/Source/Recorder.h | 107 +-- .../Source/RepositioningLayerPass.cpp | 1 - .../EMotionFX/Source/RepositioningLayerPass.h | 4 +- .../Code/EMotionFX/Source/Skeleton.cpp | 34 +- .../Code/EMotionFX/Source/Skeleton.h | 10 +- .../EMotionFX/Source/StandardMaterial.cpp | 31 +- .../Code/EMotionFX/Source/StandardMaterial.h | 4 +- .../Code/EMotionFX/Source/SubMesh.cpp | 19 +- .../EMotionFX/Code/EMotionFX/Source/SubMesh.h | 12 +- .../Code/EMotionFX/Source/ThreadData.h | 2 +- .../EMStudioSDK/Source/EMStudioManager.cpp | 9 +- .../EMStudioSDK/Source/EMStudioManager.h | 4 +- .../EMStudioSDK/Source/FileManager.h | 2 +- .../EMStudioSDK/Source/MainWindow.cpp | 15 +- .../EMStudioSDK/Source/MainWindow.h | 6 +- .../Source/NodeHierarchyWidget.cpp | 37 +- .../EMStudioSDK/Source/NodeHierarchyWidget.h | 11 +- .../Source/NodeSelectionWindow.cpp | 4 +- .../EMStudioSDK/Source/NodeSelectionWindow.h | 6 +- .../Source/NotificationWindowManager.cpp | 19 +- .../Source/NotificationWindowManager.h | 8 +- .../Source/RenderPlugin/RenderPlugin.cpp | 55 +- .../Source/RenderPlugin/RenderPlugin.h | 6 +- .../RenderPlugin/RenderUpdateCallback.cpp | 10 +- .../Source/RenderPlugin/RenderWidget.cpp | 22 +- .../Source/RenderPlugin/RenderWidget.h | 8 +- .../Source/AnimGraph/AnimGraphPlugin.cpp | 6 +- .../Source/AnimGraph/AnimGraphPlugin.h | 2 +- .../AnimGraph/BlendGraphWidgetCallback.cpp | 409 --------- .../AnimGraph/BlendGraphWidgetCallback.h | 53 -- .../AnimGraph/BlendNodeSelectionWindow.h | 2 +- .../Source/AnimGraph/BlendTreeVisualNode.cpp | 13 +- .../Source/AnimGraph/GameControllerWindow.cpp | 24 +- .../Source/AnimGraph/GameControllerWindow.h | 8 +- .../Source/AnimGraph/GraphNode.cpp | 64 +- .../Source/AnimGraph/GraphNode.h | 23 +- .../Source/AnimGraph/NodeGraph.cpp | 26 +- .../Source/AnimGraph/NodeGroupWindow.cpp | 43 +- .../Source/AnimGraph/NodeGroupWindow.h | 11 +- .../AnimGraph/ParameterSelectionWindow.h | 2 +- .../Source/AnimGraph/StateGraphNode.cpp | 5 +- .../Attachments/AttachmentNodesWindow.cpp | 10 +- .../Attachments/AttachmentNodesWindow.h | 2 +- .../Source/Attachments/AttachmentsWindow.cpp | 6 +- .../Source/Attachments/AttachmentsWindow.h | 2 +- .../Source/LogWindow/LogWindowCallback.cpp | 13 +- .../MotionSetManagementWindow.cpp | 4 +- .../MotionSetManagementWindow.h | 2 +- .../MotionWindow/MotionExtractionWindow.cpp | 4 +- .../MotionWindow/MotionExtractionWindow.h | 2 +- .../Source/NodeGroups/NodeGroupWidget.cpp | 20 +- .../Source/NodeGroups/NodeGroupWidget.h | 2 +- .../Source/NodeWindow/NodeWindowPlugin.cpp | 4 +- .../SceneManager/ActorPropertiesWindow.cpp | 24 - .../SceneManager/ActorPropertiesWindow.h | 1 - .../Source/SceneManager/MirrorSetupWindow.cpp | 2 +- .../Source/SceneManager/MirrorSetupWindow.h | 4 +- .../Source/TimeView/TimeViewPlugin.cpp | 54 +- .../Source/TimeView/TimeViewPlugin.h | 14 +- .../Source/TimeView/TrackDataHeaderWidget.h | 2 +- .../Source/TimeView/TrackDataWidget.cpp | 52 +- .../Source/TimeView/TrackDataWidget.h | 6 +- .../Source/TimeView/TrackHeaderWidget.cpp | 2 +- Gems/EMotionFX/Code/MCore/Source/Array.h | 799 ------------------ Gems/EMotionFX/Code/MCore/Source/Config.h | 19 +- Gems/EMotionFX/Code/MCore/Source/HashTable.h | 239 ------ .../EMotionFX/Code/MCore/Source/HashTable.inl | 338 -------- .../Code/MCore/Source/LogManager.cpp | 68 +- Gems/EMotionFX/Code/MCore/Source/LogManager.h | 12 +- .../Code/MCore/Source/MCoreCommandManager.h | 2 +- Gems/EMotionFX/Code/MCore/mcore_files.cmake | 3 - .../Code/MysticQt/Source/DialogStack.cpp | 126 ++- .../Code/MysticQt/Source/DialogStack.h | 33 +- .../Code/MysticQt/Source/MysticQtManager.cpp | 16 +- .../Code/MysticQt/Source/MysticQtManager.h | 4 +- .../Platform/Windows/platform_windows.cmake | 4 + .../Source/Editor/ActorJointBrowseEdit.cpp | 18 - .../Code/Source/Editor/ActorJointBrowseEdit.h | 3 - .../PropertyWidgets/ActorGoalNodeHandler.cpp | 10 +- .../Code/Source/Editor/SkeletonModel.cpp | 4 +- .../Tests/AnimGraphParameterCommandsTests.cpp | 1 - .../Code/Tests/BoolLogicNodeTests.cpp | 2 +- Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h | 2 +- .../Code/Tests/Mocks/AnimGraphInstance.h | 2 +- Gems/EMotionFX/Code/Tests/Mocks/Node.h | 2 +- .../EMotionFX/Code/Tests/SkeletalLODTests.cpp | 4 +- .../Code/Tests/UI/LODSkinnedMeshTests.cpp | 1 - .../Vector2ToVector3CompatibilityTests.cpp | 2 +- 189 files changed, 1488 insertions(+), 3797 deletions(-) delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Source/MotionGroup.cpp delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.cpp delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.h delete mode 100644 Gems/EMotionFX/Code/MCore/Source/Array.h delete mode 100644 Gems/EMotionFX/Code/MCore/Source/HashTable.h delete mode 100644 Gems/EMotionFX/Code/MCore/Source/HashTable.inl diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h index 75d92d5f27..eec9f7a5c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h @@ -25,7 +25,7 @@ namespace CommandSystem AZStd::string mOldAttachmentNodes; AZStd::string mOldExcludedFromBoundsNodes; AZStd::string mOldName; - MCore::Array mOldMirrorSetup; + AZStd::vector mOldMirrorSetup; bool mOldDirtyFlag; void SetIsAttachmentNode(EMotionFX::Actor* actor, bool isAttachmentNode); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp index fe41312701..ed871fc03f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp @@ -1204,10 +1204,10 @@ 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 uint32 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(); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp index 41a6a26b89..38a545465b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp @@ -865,7 +865,7 @@ namespace CommandSystem parameter->GetName().c_str(), parameterContents.c_str()); - if (insertAtIndex != MCORE_INVALIDINDEX32) + if (insertAtIndex != InvalidIndex32) { outResult += AZStd::string::format(" -index \"%i\"", insertAtIndex); } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h index b70e8d24d2..8b55130677 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h @@ -81,6 +81,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, uint32 insertAtIndex = InvalidIndex32); } // namespace CommandSystem diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp index 8ee207713c..76ba6f37b7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp @@ -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,7 +1191,7 @@ namespace CommandSystem MCore::CommandGroup internalCommandGroup("Remove motion events"); // get the number of events to remove and iterate through them - const int32 numEvents = eventNumbers.GetLength(); + const int32 numEvents = eventNumbers.size(); for (int32 i = 0; i < numEvents; ++i) { // remove the events from back to front @@ -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) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h index 30caae2713..269a0322c0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h @@ -222,6 +222,6 @@ namespace CommandSystem 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 CommandHelperRemoveMotionEvents(const char* trackName, const AZStd::vector& eventNumbers, MCore::CommandGroup* commandGroup = nullptr); void COMMANDSYSTEM_API CommandHelperMotionEventTrackChanged(uint32 eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName); } // namespace CommandSystem diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp index 7f0fcfa9d0..f6d03d2983 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp @@ -33,10 +33,10 @@ 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 uint32 numSelectedActorInstances = selectedActorInstances.size(); // check if the current selection is equal to the desired actor instances selection list bool nothingChanged = true; @@ -52,7 +52,7 @@ namespace CommandSystem for (uint32 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h index d48bc3d3b6..0c1fad6588 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h @@ -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/Exporters/ExporterLib/Exporter/Exporter.h b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h index e302f3ffe2..09c0646509 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 @@ -100,9 +99,9 @@ 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp index 4adee9af84..8bd005af6c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp @@ -199,10 +199,10 @@ namespace ExporterLib // save the given materials - void SaveMaterials(MCore::Stream* file, MCore::Array& materials, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) + void SaveMaterials(MCore::Stream* file, AZStd::vector& materials, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) { // get the number of materials - const uint32 numMaterials = materials.GetLength(); + const uint32 numMaterials = materials.size(); // chunk header EMotionFX::FileFormat::FileChunk chunkHeader; @@ -269,15 +269,15 @@ namespace ExporterLib const uint32 numMaterials = actor->GetNumMaterials(lodLevel); // create our materials array and reserve some elements - MCore::Array materials; - materials.Reserve(numMaterials); + AZStd::vector 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); + materials.emplace_back(baseMaterial); } // save the materials diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp index 79861be4b8..80efb54606 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp @@ -227,13 +227,13 @@ 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 uint32 numGroups = nodeGroups.size(); if (numGroups == 0) { @@ -286,13 +286,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 @@ -300,7 +300,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); @@ -311,7 +311,7 @@ namespace ExporterLib MCORE_ASSERT(nodeMirrorInfos); - const uint32 numNodes = nodeMirrorInfos->GetLength(); + const uint32 numNodes = nodeMirrorInfos->size(); // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; @@ -342,7 +342,7 @@ namespace ExporterLib for (uint32 i = 0; i < numNodes; ++i) { // get the motion node source - uint16 nodeMotionSource = nodeMirrorInfos->GetItem(i).mSourceNode; + uint16 nodeMotionSource = nodeMirrorInfos->at(i).mSourceNode; //if (actor && nodeMotionSource != MCORE_INVALIDINDEX16) //LogInfo(" + '%s' (NodeNr=%i) -> '%s' (NodeNr=%i)", actor->GetNode( i )->GetName(), i, actor->GetNode( nodeMotionSource )->GetName(), nodeMotionSource); @@ -355,14 +355,14 @@ namespace ExporterLib // write all axes for (uint32 i = 0; i < numNodes; ++i) { - uint8 axis = static_cast(nodeMirrorInfos->GetItem(i).mAxis); + uint8 axis = static_cast(nodeMirrorInfos->at(i).mAxis); file->Write(&axis, sizeof(uint8)); } // write all flags for (uint32 i = 0; i < numNodes; ++i) { - uint8 flags = static_cast(nodeMirrorInfos->GetItem(i).mFlags); + uint8 flags = static_cast(nodeMirrorInfos->at(i).mFlags); file->Write(&flags, sizeof(uint8)); } } @@ -430,7 +430,7 @@ 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); @@ -455,7 +455,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/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index 9c0a4af895..e17fffbdb5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -51,8 +51,6 @@ namespace MCommon mArrowHeadMesh = CreateArrowHead(1.0f, 0.5f); mUnitCubeMesh = CreateCube(1.0f); mFont = new VectorFont(this); - - mTriangleVertices.SetMemoryCategory(MEMCATEGORY_MCOMMON); } @@ -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 (mTriangleVertices.empty()) { return; } // render the triangles and clear the array RenderTriangles(mTriangleVertices); - mTriangleVertices.Clear(false); + mTriangleVertices.clear(); } @@ -655,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) @@ -680,7 +678,7 @@ namespace MCommon const AZ::u32 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 == MCORE_INVALIDINDEX32 || AZStd::find(begin(boneList), end(boneList), jointIndex) == end(boneList)) { continue; } @@ -717,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()); @@ -739,7 +737,7 @@ namespace MCommon (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 != MCORE_INVALIDINDEX32 && AZStd::find(begin(boneList), end(boneList), jointIndex) != end(boneList)) { static const float axisBoneScale = 50.0f; axisRenderingSettings.mSize = GetBoneScale(actorInstance, joint) * constPreScale * axisBoneScale; @@ -1711,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->mTraceParticles; + const int32 numTraceParticles = traceParticles.size(); + if (traceParticles.empty()) { return; } @@ -1858,7 +1856,7 @@ namespace MCommon } // remove all particles while keeping the data in memory - trajectoryPath->mTraceParticles.Clear(false); + trajectoryPath->mTraceParticles.clear(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h index f63d41e812..8fb8f524c4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h @@ -191,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. @@ -202,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. @@ -570,17 +570,17 @@ namespace MCommon 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)); + mTriangleVertices.emplace_back(TriangleVertex(posA, normalA, color)); + mTriangleVertices.emplace_back(TriangleVertex(posB, normalB, color)); + mTriangleVertices.emplace_back(TriangleVertex(posC, normalC, color)); - if (mTriangleVertices.GetLength() + 2 >= mNumMaxTriangleVertices) + if (mTriangleVertices.size() + 2 >= mNumMaxTriangleVertices) { RenderTriangles(); } } - virtual void RenderTriangles(const MCore::Array& triangleVertices) { MCORE_UNUSED(triangleVertices); } + virtual void RenderTriangles(const AZStd::vector& triangleVertices) { MCORE_UNUSED(triangleVertices); } void RenderTriangles(); //--------------------------------------------------------------------------------------------- @@ -609,13 +609,13 @@ namespace MCommon struct TrajectoryTracePath { - MCore::Array mTraceParticles; + AZStd::vector mTraceParticles; EMotionFX::ActorInstance* mActorInstance; float mTimePassed; TrajectoryTracePath() { - mTraceParticles.Reserve(250); + mTraceParticles.reserve(250); mTimePassed = 0.0f; mActorInstance = NULL; } @@ -812,7 +812,7 @@ namespace MCommon static uint32 mNumMaxMeshIndices; /**< The maximum capacity of the util mesh index buffer */ // helper variables for rendering triangles - MCore::Array mTriangleVertices; + AZStd::vector mTriangleVertices; static uint32 mNumMaxTriangleVertices; /**< The maximum capacity of the triangle vertex buffer */ }; } // 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..3e2a25fe80 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" diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp index d727300dd5..7a78b5749d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp @@ -27,15 +27,6 @@ namespace RenderGL mActor = nullptr; mEnableGPUSkinning = 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); } @@ -71,14 +62,14 @@ namespace RenderGL for (uint32 a = 0; a < 3; ++a) { // get rid of the given vertex buffers - const uint32 numVertexBuffers = mVertexBuffers[a].GetLength(); + const uint32 numVertexBuffers = mVertexBuffers[a].size(); for (i = 0; i < numVertexBuffers; ++i) { delete mVertexBuffers[a][i]; } // get rid of the given index buffers - const uint32 numIndexBuffers = mIndexBuffers[a].GetLength(); + const uint32 numIndexBuffers = mIndexBuffers[a].size(); for (i = 0; i < numIndexBuffers; ++i) { delete mIndexBuffers[a][i]; @@ -86,10 +77,10 @@ namespace RenderGL } // delete all materials - const uint32 numLOD = mMaterials.GetLength(); + const uint32 numLOD = mMaterials.size(); for (uint32 l = 0; l < numLOD; l++) { - const uint32 numMaterials = mMaterials[l].GetLength(); + const uint32 numMaterials = mMaterials[l].size(); for (uint32 n = 0; n < numMaterials; n++) { delete mMaterials[l][n]->mMaterial; @@ -126,13 +117,13 @@ namespace RenderGL const uint32 numNodes = actor->GetNumNodes(); // set the pre-allocation amount for the number of materials - mMaterials.Resize(numGeometryLODLevels); + mMaterials.resize(numGeometryLODLevels); // resize the vertex and index buffers for (uint32 a = 0; a < 3; ++a) { - mVertexBuffers[a].Resize(numGeometryLODLevels); - mIndexBuffers[a].Resize(numGeometryLODLevels); + mVertexBuffers[a].resize(numGeometryLODLevels); + mIndexBuffers[a].resize(numGeometryLODLevels); mPrimitives[a].Resize(numGeometryLODLevels); // reset the vertex and index buffers @@ -143,7 +134,7 @@ namespace RenderGL } } - mHomoMaterials.Resize(numGeometryLODLevels); + mHomoMaterials.resize(numGeometryLODLevels); mDynamicNodes.Resize (numGeometryLODLevels); EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); @@ -206,7 +197,7 @@ namespace RenderGL // add to material list MaterialPrimitives* materialPrims = mMaterials[lodLevel][newPrimitive.mMaterialIndex]; - materialPrims->mPrimitives[meshType].Add(newPrimitive); + materialPrims->mPrimitives[meshType].emplace_back(newPrimitive); totalNumIndices[meshType] += newPrimitive.mNumTriangles * 3; totalNumVerts[meshType] += subMesh->GetNumVertices(); @@ -373,7 +364,7 @@ namespace RenderGL { EMotionFX::Material* emfxMaterial = mActor->GetMaterial(lodLevel, m); Material* material = InitMaterial(emfxMaterial); - mMaterials[lodLevel].Add( new MaterialPrimitives(material) ); + mMaterials[lodLevel].emplace_back( new MaterialPrimitives(material) ); } } @@ -412,7 +403,7 @@ namespace RenderGL void GLActor::RenderMeshes(EMotionFX::ActorInstance* actorInstance, EMotionFX::Mesh::EMeshType meshType, uint32 renderFlags) { const uint32 lodLevel = actorInstance->GetLODLevel(); - const uint32 numMaterials = mMaterials[lodLevel].GetLength(); + const uint32 numMaterials = mMaterials[lodLevel].size(); if (numMaterials == 0) { @@ -437,7 +428,7 @@ namespace RenderGL for (uint32 n = 0; n < numMaterials; n++) { const MaterialPrimitives* materialPrims = mMaterials[lodLevel][n]; - const uint32 numPrimitives = materialPrims->mPrimitives[meshType].GetLength(); + const uint32 numPrimitives = materialPrims->mPrimitives[meshType].size(); if (numPrimitives == 0) { continue; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp index feb2cd22ee..2ef39bd7c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp @@ -110,7 +110,6 @@ namespace RenderGL mTextures = new TextureEntry[mMaxNumTextures]; // text rendering - mTextEntries.SetMemoryCategory(MEMCATEGORY_RENDERING); } @@ -164,12 +163,12 @@ namespace RenderGL delete[] mTextures; // get rid of texture entries - const uint32 numTextEntries = mTextEntries.GetLength(); + const uint32 numTextEntries = mTextEntries.size(); for (uint32 i = 0; i < numTextEntries; ++i) { delete mTextEntries[i]; } - mTextEntries.Clear(); + mTextEntries.clear(); } @@ -481,10 +480,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,7 +491,7 @@ namespace RenderGL glDisable(GL_CULL_FACE); // get the number of vertices to render - const uint32 numVertices = triangleVertices.GetLength(); + const uint32 numVertices = triangleVertices.size(); MCORE_ASSERT(numVertices <= mNumMaxTriangleVertices); // lock the vertex buffer @@ -552,7 +551,7 @@ namespace RenderGL textEntry->mFontSize = fontSize; textEntry->mCentered = centered; - mTextEntries.Add(textEntry); + mTextEntries.emplace_back(textEntry); } @@ -560,7 +559,7 @@ 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 < mTextEntries.size(); ) { TextEntry* textEntry = mTextEntries[i]; RenderText(static_cast(textEntry->mX), static_cast(textEntry->mY), textEntry->mText.c_str(), textEntry->mColor, textEntry->mFontSize, textEntry->mCentered); @@ -569,7 +568,7 @@ namespace RenderGL if (textEntry->mLifeTime < 0.0f) { delete textEntry; - mTextEntries.Remove(i); + mTextEntries.erase(AZStd::next(begin(mTextEntries), 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..672a8c524f 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); @@ -108,7 +108,7 @@ namespace RenderGL bool mCentered; }; - MCore::Array mTextEntries; + AZStd::vector mTextEntries; TextureEntry* mTextures; uint32 mNumTextures; uint32 mMaxNumTextures; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp index 02aad3aa04..451246a8e2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp @@ -36,16 +36,11 @@ namespace RenderGL mPixelShader = 0; mTextureUnit = 0; - mUniforms.SetMemoryCategory(MEMCATEGORY_RENDERING); - mAttributes.SetMemoryCategory(MEMCATEGORY_RENDERING); - mActivatedAttribs.SetMemoryCategory(MEMCATEGORY_RENDERING); - mActivatedTextures.SetMemoryCategory(MEMCATEGORY_RENDERING); - // pre-alloc data for uniforms and attributes - mUniforms.Reserve(10); - mAttributes.Reserve(10); - mActivatedAttribs.Reserve(10); - mActivatedTextures.Reserve(10); + mUniforms.reserve(10); + mAttributes.reserve(10); + mActivatedAttribs.reserve(10); + mActivatedTextures.reserve(10); } @@ -70,14 +65,14 @@ namespace RenderGL // Deactivate void GLSLShader::Deactivate() { - const uint32 numAttribs = mActivatedAttribs.GetLength(); + const uint32 numAttribs = mActivatedAttribs.size(); for (uint32 i = 0; i < numAttribs; ++i) { const uint32 index = mActivatedAttribs[i]; glDisableVertexAttribArray(mAttributes[index].mLocation); } - const uint32 numTextures = mActivatedTextures.GetLength(); + const uint32 numTextures = mActivatedTextures.size(); for (uint32 i = 0; i < numTextures; ++i) { const uint32 index = mActivatedTextures[i]; @@ -86,8 +81,8 @@ namespace RenderGL glBindTexture(GL_TEXTURE_2D, 0); } - mActivatedAttribs.Clear(false); - mActivatedTextures.Clear(false); + mActivatedAttribs.clear(); + mActivatedTextures.clear(); } bool GLSLShader::Validate() @@ -129,7 +124,7 @@ namespace RenderGL text = "#version 120\n"; // build define string - const uint32 numDefines = mDefines.GetLength(); + const uint32 numDefines = mDefines.size(); for (uint32 n = 0; n < numDefines; ++n) { text += AZStd::string::format("#define %s\n", mDefines[n].c_str()); @@ -180,10 +175,10 @@ 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 (mDefines.size() > 0) { AZStd::string dStr; - const uint32 numDefines = mDefines.GetLength(); + const uint32 numDefines = mDefines.size(); for (uint32 n = 0; n < numDefines; ++n) { if (n < numDefines - 1) @@ -209,7 +204,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", @@ -276,9 +271,9 @@ namespace RenderGL // FindAttributeIndex - uint32 GLSLShader::FindAttributeIndex(const char* name) + size_t GLSLShader::FindAttributeIndex(const char* name) { - const uint32 numAttribs = mAttributes.GetLength(); + const uint32 numAttribs = mAttributes.size(); for (uint32 i = 0; i < numAttribs; ++i) { if (AzFramework::StringFunc::Equal(mAttributes[i].mName.c_str(), name, false /* no case */)) @@ -296,14 +291,14 @@ namespace RenderGL // the parameter wasn't cached, try to retrieve it const GLint loc = glGetAttribLocation(mProgram, name); - mAttributes.Add(ShaderParameter(name, loc, true)); + mAttributes.emplace_back(name, loc, true); if (loc < 0) { return MCORE_INVALIDINDEX32; } - return mAttributes.GetLength() - 1; + return mAttributes.size() - 1; } @@ -334,9 +329,9 @@ namespace RenderGL // FindUniformIndex - uint32 GLSLShader::FindUniformIndex(const char* name) + size_t GLSLShader::FindUniformIndex(const char* name) { - const uint32 numUniforms = mUniforms.GetLength(); + const uint32 numUniforms = mUniforms.size(); for (uint32 i = 0; i < numUniforms; ++i) { if (AzFramework::StringFunc::Equal(mUniforms[i].mName.c_str(), name, false /* no case */)) @@ -352,14 +347,14 @@ namespace RenderGL // the parameter wasn't cached, try to retrieve it const GLint loc = glGetUniformLocation(mProgram, name); - mUniforms.Add(ShaderParameter(name, loc, false)); + mUniforms.emplace_back(name, loc, false); if (loc < 0) { return MCORE_INVALIDINDEX32; } - return mUniforms.GetLength() - 1; + return mUniforms.size() - 1; } @@ -377,7 +372,7 @@ namespace RenderGL glEnableVertexAttribArray(param->mLocation); glVertexAttribPointer(param->mLocation, dim, type, GL_FALSE, stride, (GLvoid*)offset); - mActivatedAttribs.Add(index); + mActivatedAttribs.emplace_back(index); } @@ -532,7 +527,7 @@ namespace RenderGL glBindTexture(GL_TEXTURE_2D, texture->GetID()); glUniform1i(mUniforms[index].mLocation, mUniforms[index].mTextureUnit); - mActivatedTextures.Add(index); + mActivatedTextures.emplace_back(index); } @@ -563,7 +558,7 @@ namespace RenderGL glBindTexture(GL_TEXTURE_2D, textureID); glUniform1i(mUniforms[index].mLocation, mUniforms[index].mTextureUnit); - mActivatedTextures.Add(index); + mActivatedTextures.emplace_back(index); } @@ -571,7 +566,7 @@ namespace RenderGL bool GLSLShader::CheckIfIsDefined(const char* attributeName) { // get the number of defines and iterate through them - const uint32 numDefines = mDefines.GetLength(); + const uint32 numDefines = mDefines.size(); for (uint32 i = 0; i < numDefines; ++i) { // compare the given attribute with the current define and return if they are equal diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h index 6a6854e29f..6eb77b69c2 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 @@ -42,7 +42,7 @@ namespace RenderGL MCORE_INLINE unsigned int GetProgram() const { return mProgram; } bool CheckIfIsDefined(const char* attributeName); - 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; @@ -73,8 +73,8 @@ namespace RenderGL bool mIsAttribute; }; - 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); @@ -84,11 +84,11 @@ namespace RenderGL AZ::IO::Path mFileName; - MCore::Array mActivatedAttribs; - MCore::Array mActivatedTextures; - MCore::Array mUniforms; - MCore::Array mAttributes; - MCore::Array mDefines; + AZStd::vector mActivatedAttribs; + AZStd::vector mActivatedTextures; + AZStd::vector mUniforms; + AZStd::vector mAttributes; + AZStd::vector mDefines; unsigned int mVertexShader; unsigned int mPixelShader; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp index db03a694a8..78b5813770 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp @@ -403,20 +403,20 @@ 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}; // construct the lookup string for the shader cache AZStd::string cacheLookupStr = vertexPath.Native() + pixelPath.Native(); - const uint32 numDefines = defines.GetLength(); + const uint32 numDefines = defines.size(); for (uint32 n = 0; n < numDefines; n++) { cacheLookupStr += AZStd::string::format("#%s", defines[n].c_str()); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h index 674d428382..e13e643938 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h @@ -62,7 +62,7 @@ namespace RenderGL bool GetIsPostProcessingEnabled() const { return mPostProcessing; } 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; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h index 1cebe2d87b..ed5ab18609 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h @@ -40,7 +40,7 @@ namespace RenderGL uint32 mNumVertices; /**< The number of vertices in the primitive. */ uint32 mMaterialIndex; /**< The material index which is mapped to the primitive. */ - MCore::Array mBoneNodeIndices;/**< Mapping from local bones 0-50 to nodes. */ + AZStd::vector mBoneNodeIndices;/**< Mapping from local bones 0-50 to nodes. */ }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp index 7492f3e845..84c369bcbc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp @@ -81,7 +81,7 @@ namespace RenderGL // Init bool PostProcessShader::Init(AZ::IO::PathView filename) { - MCore::Array defines; + AZStd::vector defines; return GLSLShader::Init(nullptr, filename, defines); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp index 604ad4dcaf..26acd0e77d 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); + mEntries.reserve(128); } @@ -31,7 +30,7 @@ namespace RenderGL void ShaderCache::Release() { // delete all shaders - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { mEntries[i].mName.clear(); @@ -39,23 +38,21 @@ namespace RenderGL } // clear all entries - mEntries.Clear(); + mEntries.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; + mEntries.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(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { if (AzFramework::StringFunc::Equal(mEntries[i].mName, filename, false /* no case */)) // non-case-sensitive name compare @@ -72,7 +69,7 @@ namespace RenderGL // check if we have a given shader in the cache bool ShaderCache::CheckIfHasShader(Shader* shader) const { - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { if (mEntries[i].mShader == shader) diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp index a782cfcd42..46c7e5c13e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp @@ -28,8 +28,6 @@ namespace RenderGL mSpecularMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); mNormalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); - mShaders.SetMemoryCategory(MEMCATEGORY_RENDERING); - SetAttribute(LIGHTING, true); SetAttribute(SKINNING, false); SetAttribute(SHADOWS, false); @@ -266,7 +264,7 @@ namespace RenderGL const AZ::Matrix3x4* skinningMatrices = transformData->GetSkinningMatrices(); // multiple each transform by its inverse bind pose - const uint32 numBones = primitive->mBoneNodeIndices.GetLength(); + const uint32 numBones = primitive->mBoneNodeIndices.size(); for (uint32 i = 0; i < numBones; ++i) { const uint32 nodeNr = primitive->mBoneNodeIndices[i]; @@ -307,7 +305,7 @@ namespace RenderGL mActiveShader = nullptr; // get the number of shaders and iterate through them - const uint32 numShaders = mShaders.GetLength(); + const uint32 numShaders = mShaders.size(); for (uint32 i = 0; i < numShaders; ++i) { if (mShaders[i] == nullptr) @@ -351,18 +349,18 @@ namespace RenderGL // 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]) { - 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); + mShaders.emplace_back(mActiveShader); } mAttributesUpdated = 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..d9eb23b50a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.h @@ -45,7 +45,7 @@ namespace RenderGL bool mAttributesUpdated; GLSLShader* mActiveShader; - MCore::Array mShaders; + AZStd::vector mShaders; AZ::Matrix4x4 mBoneMatrices[200]; EMotionFX::Material* mMaterial; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp index 4723d166a7..7ef5b49c67 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp @@ -47,8 +47,7 @@ namespace RenderGL mWhiteTexture = nullptr; mDefaultNormalTexture = nullptr; - mEntries.SetMemoryCategory(MEMCATEGORY_RENDERING); - mEntries.Reserve(128); + mEntries.reserve(128); } @@ -74,14 +73,14 @@ namespace RenderGL void TextureCache::Release() { // delete all textures - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { delete mEntries[i].mTexture; } // clear all entries - mEntries.Clear(); + mEntries.clear(); // delete the white texture delete mWhiteTexture; @@ -95,9 +94,7 @@ namespace RenderGL // 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; + mEntries.emplace_back(Entry{filename, texture}); } @@ -105,7 +102,7 @@ namespace RenderGL Texture* TextureCache::FindTexture(const char* filename) const { // get the number of entries and iterate through them - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { if (AzFramework::StringFunc::Equal(mEntries[i].mName.c_str(), filename, false /* no case */)) // non-case-sensitive name compare @@ -123,7 +120,7 @@ namespace RenderGL bool TextureCache::CheckIfHasTexture(Texture* texture) const { // get the number of entries and iterate through them - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { if (mEntries[i].mTexture == texture) @@ -139,13 +136,13 @@ namespace RenderGL // remove an item from the cache void TextureCache::RemoveTexture(Texture* texture) { - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { if (mEntries[i].mTexture == texture) { delete mEntries[i].mTexture; - mEntries.Remove(i); + mEntries.erase(AZStd::next(begin(mEntries), i)); return; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h index bae46bd75b..43d0f1a635 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 @@ -72,7 +72,7 @@ namespace RenderGL Texture* mTexture; }; - MCore::Array mEntries; + AZStd::vector mEntries; Texture* mWhiteTexture; Texture* mDefaultNormalTexture; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h index ff20861c08..4de5d7198a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h @@ -61,10 +61,10 @@ namespace RenderGL struct RENDERGL_API MaterialPrimitives { Material* mMaterial; - MCore::Array mPrimitives[3]; + AZStd::vector mPrimitives[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() { 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); } }; AZStd::string mTexturePath; @@ -85,12 +85,12 @@ namespace RenderGL EMotionFX::Mesh::EMeshType ClassifyMeshType(EMotionFX::Node* node, EMotionFX::Mesh* mesh, uint32 lodLevel); - MCore::Array< MCore::Array > mMaterials; + AZStd::vector< AZStd::vector > mMaterials; MCore::Array2D mDynamicNodes; MCore::Array2D mPrimitives[3]; - MCore::Array mHomoMaterials; - MCore::Array mVertexBuffers[3]; - MCore::Array mIndexBuffers[3]; + AZStd::vector mHomoMaterials; + AZStd::vector mVertexBuffers[3]; + AZStd::vector mIndexBuffers[3]; MCore::RGBAColor mGroundColor; MCore::RGBAColor mSkyColor; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h index 25a91026f8..08bf9dfa58 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 @@ -42,7 +42,7 @@ namespace RenderGL }; // - MCore::Array mEntries; // the shader cache entries + AZStd::vector mEntries; // 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 68b9d62e8e..541ab65071 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -49,14 +49,10 @@ namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(Actor, ActorAllocator, 0) - Actor::LODLevel::LODLevel() - { - } - Actor::MeshLODData::MeshLODData() { // Create the default LOD level - m_lodLevels.push_back({}); + m_lodLevels.emplace_back(); } Actor::NodeLODInfo::NodeLODInfo() @@ -77,11 +73,6 @@ 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(); mMotionExtractionNode = MCORE_INVALIDINDEX32; @@ -105,11 +96,10 @@ namespace EMotionFX #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); + mMaterials.reserve(4); // reserve space for 4 lods + mMorphSetups.reserve(4); // + mMaterials.emplace_back(); + mMorphSetups.emplace_back(nullptr); GetEventManager().OnCreateActor(this); ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnActorCreated, this); @@ -120,7 +110,7 @@ namespace EMotionFX ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnActorDestroyed, this); GetEventManager().OnDeleteActor(this); - mNodeMirrorInfos.Clear(true); + mNodeMirrorInfos.clear(); RemoveAllMaterials(); RemoveAllMorphSetups(); @@ -158,12 +148,12 @@ namespace EMotionFX } // clone the materials - result->mMaterials.Resize(mMaterials.GetLength()); - for (uint32 i = 0; i < mMaterials.GetLength(); ++i) + result->mMaterials.resize(mMaterials.size()); + for (uint32 i = 0; i < mMaterials.size(); ++i) { // get the number of materials in the current LOD - const uint32 numMaterials = mMaterials[i].GetLength(); - result->mMaterials[i].Reserve(numMaterials); + const uint32 numMaterials = mMaterials[i].size(); + result->mMaterials[i].reserve(numMaterials); for (uint32 m = 0; m < numMaterials; ++m) { // retrieve the current material @@ -190,10 +180,10 @@ 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].mNodeInfos; + AZStd::vector& resultNodeInfos = resultMeshLodData.m_lodLevels[lodLevel].mNodeInfos; - resultNodeInfos.Resize(numNodes); + resultNodeInfos.resize(numNodes); for (uint32 n = 0; n < numNodes; ++n) { NodeLODInfo& resultNodeInfo = resultNodeInfos[n]; @@ -204,8 +194,8 @@ namespace EMotionFX } // clone the morph setups - result->mMorphSetups.Resize(mMorphSetups.GetLength()); - for (uint32 i = 0; i < mMorphSetups.GetLength(); ++i) + result->mMorphSetups.resize(mMorphSetups.size()); + for (uint32 i = 0; i < mMorphSetups.size(); ++i) { if (mMorphSetups[i]) { @@ -241,7 +231,7 @@ namespace EMotionFX void Actor::AllocateNodeMirrorInfos() { const uint32 numNodes = mSkeleton->GetNumNodes(); - mNodeMirrorInfos.Resize(numNodes); + mNodeMirrorInfos.resize(numNodes); // init the data for (uint32 i = 0; i < numNodes; ++i) @@ -255,19 +245,20 @@ namespace EMotionFX // remove the node mirror info void Actor::RemoveNodeMirrorInfos() { - mNodeMirrorInfos.Clear(true); + mNodeMirrorInfos.clear(); + mNodeMirrorInfos.shrink_to_fit(); } // check if we have our axes detected bool Actor::GetHasMirrorAxesDetected() const { - if (mNodeMirrorInfos.GetLength() == 0) + if (mNodeMirrorInfos.size() == 0) { return false; } - for (uint32 i = 0; i < mNodeMirrorInfos.GetLength(); ++i) + for (uint32 i = 0; i < mNodeMirrorInfos.size(); ++i) { if (mNodeMirrorInfos[i].mAxis == MCORE_INVALIDINDEX8) { @@ -283,17 +274,17 @@ namespace EMotionFX void Actor::RemoveAllMaterials() { // for all LODs - for (uint32 i = 0; i < mMaterials.GetLength(); ++i) + for (uint32 i = 0; i < mMaterials.size(); ++i) { // delete all materials - const uint32 numMats = mMaterials[i].GetLength(); + const uint32 numMats = mMaterials[i].size(); for (uint32 m = 0; m < numMats; ++m) { mMaterials[i][m]->Destroy(); } } - mMaterials.Clear(); + mMaterials.clear(); } @@ -305,8 +296,7 @@ namespace EMotionFX lodLevels.emplace_back(); LODLevel& newLOD = lodLevels.back(); const uint32 numNodes = mSkeleton->GetNumNodes(); - newLOD.mNodeInfos.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - newLOD.mNodeInfos.Resize(numNodes); + newLOD.mNodeInfos.resize(numNodes); const size_t numLODs = lodLevels.size(); const size_t lodIndex = numLODs - 1; @@ -329,11 +319,10 @@ namespace EMotionFX } // create a new material array for the new LOD level - mMaterials.Resize(static_cast(lodLevels.size())); - mMaterials[static_cast(lodIndex)].SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); + mMaterials.resize(lodLevels.size()); // create an empty morph setup for the new LOD level - mMorphSetups.Add(nullptr); + mMorphSetups.emplace_back(nullptr); // copy data from the previous LOD level if wanted if (copyFromLastLODLevel && numLODs > 0) @@ -347,12 +336,11 @@ namespace EMotionFX { 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); + newLOD.mNodeInfos.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) @@ -363,11 +351,10 @@ namespace EMotionFX } // create a new material array for the new LOD level - mMaterials.Insert(insertAt); - mMaterials[lodIndex].SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); + mMaterials.emplace(AZStd::next(begin(mMaterials), insertAt)); // create an empty morph setup for the new LOD level - mMorphSetups.Insert(insertAt, nullptr); + mMorphSetups.emplace(AZStd::next(begin(mMorphSetups), insertAt), nullptr); } // replace existing LOD level with the current actor @@ -424,12 +411,12 @@ namespace EMotionFX // copy the materials const uint32 numMaterials = copyActor->GetNumMaterials(copyLODLevel); - for (uint32 i = 0; i < mMaterials[replaceLODLevel].GetLength(); ++i) + for (uint32 i = 0; i < mMaterials[replaceLODLevel].size(); ++i) { mMaterials[replaceLODLevel][i]->Destroy(); } - mMaterials[replaceLODLevel].Clear(); - mMaterials[replaceLODLevel].Reserve(numMaterials); + mMaterials[replaceLODLevel].clear(); + mMaterials[replaceLODLevel].reserve(numMaterials); for (uint32 i = 0; i < numMaterials; ++i) { AddMaterial(replaceLODLevel, copyActor->GetMaterial(copyLODLevel, i)->Clone()); @@ -457,15 +444,11 @@ namespace EMotionFX 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); - } + mMaterials.resize(numLODs); if (adjustMorphSetup) { - mMorphSetups.Resize(numLODs); + mMorphSetups.resize(numLODs); for (uint32 i = 0; i < numLODs; ++i) { mMorphSetups[i] = nullptr; @@ -639,7 +622,7 @@ 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, uint32 skeletalLODLevel, uint32 geometryLODLevel) { uint32 n; @@ -647,13 +630,13 @@ namespace EMotionFX const uint32 numNodes = mSkeleton->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) @@ -791,7 +774,7 @@ namespace EMotionFX const uint32 numLODs = GetNumLODLevels(); // for all LODs, get rid of all the morph setups for each geometry LOD - for (i = 0; i < mMorphSetups.GetLength(); ++i) + for (i = 0; i < mMorphSetups.size(); ++i) { if (mMorphSetups[i]) { @@ -882,11 +865,11 @@ namespace EMotionFX // remove the given material and reassign all material numbers of the submeshes void Actor::RemoveMaterial(uint32 lodLevel, uint32 index) { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); + MCORE_ASSERT(lodLevel < mMaterials.size()); // first of all remove the given material mMaterials[lodLevel][index]->Destroy(); - mMaterials[lodLevel].Remove(index); + mMaterials[lodLevel].erase(AZStd::next(begin(mMaterials[lodLevel]), index)); } @@ -930,10 +913,10 @@ namespace EMotionFX // extract a bone list - void Actor::ExtractBoneList(uint32 lodLevel, MCore::Array* outBoneList) const + void Actor::ExtractBoneList(uint32 lodLevel, AZStd::vector* outBoneList) const { // clear the existing items - outBoneList->Clear(); + outBoneList->clear(); // for all nodes const uint32 numNodes = mSkeleton->GetNumNodes(); @@ -966,9 +949,9 @@ namespace EMotionFX uint32 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); } } } @@ -984,7 +967,7 @@ namespace EMotionFX for (uint32 i = 0; i < numDependencies; ++i) { // add it to the actor instance - mDependencies.Add(*actor->GetDependency(i)); + mDependencies.emplace_back(*actor->GetDependency(i)); // recursive into the actor we are dependent on RecursiveAddDependencies(actor->GetDependency(i)->mActor); @@ -1083,7 +1066,7 @@ namespace EMotionFX } // allocate the data if we haven't already - if (mNodeMirrorInfos.GetLength() == 0) + if (mNodeMirrorInfos.size() == 0) { AllocateNodeMirrorInfos(); } @@ -1101,7 +1084,7 @@ namespace EMotionFX bool Actor::MapNodeMotionSource(uint16 sourceNodeIndex, uint16 targetNodeIndex) { // allocate the data if we haven't already - if (mNodeMirrorInfos.GetLength() == 0) + if (mNodeMirrorInfos.size() == 0) { AllocateNodeMirrorInfos(); } @@ -1267,17 +1250,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(uint32 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); 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(); @@ -1361,7 +1344,7 @@ namespace EMotionFX ReinitializeMeshDeformers(); // make sure our world space bind pose is updated too - if (mMorphSetups.GetLength() > 0 && mMorphSetups[0]) + if (mMorphSetups.size() > 0 && mMorphSetups[0]) { mSkeleton->GetBindPose()->ResizeNumMorphs(mMorphSetups[0]->GetNumMorphTargets()); } @@ -1594,7 +1577,7 @@ namespace EMotionFX Pose pose; pose.LinkToActor(this); - const uint32 numNodes = mNodeMirrorInfos.GetLength(); + const uint32 numNodes = mNodeMirrorInfos.size(); for (uint32 i = 0; i < numNodes; ++i) { const uint16 motionSource = (GetHasMirrorInfo()) ? GetNodeMirrorInfo(i).mSourceNode : static_cast(i); @@ -1723,21 +1706,21 @@ namespace EMotionFX // get the array of node mirror infos - const MCore::Array& Actor::GetNodeMirrorInfos() const + const AZStd::vector& Actor::GetNodeMirrorInfos() const { return mNodeMirrorInfos; } // get the array of node mirror infos - MCore::Array& Actor::GetNodeMirrorInfos() + AZStd::vector& Actor::GetNodeMirrorInfos() { return mNodeMirrorInfos; } // set the node mirror infos directly - void Actor::SetNodeMirrorInfos(const MCore::Array& mirrorInfos) + void Actor::SetNodeMirrorInfos(const AZStd::vector& mirrorInfos) { mNodeMirrorInfos = mirrorInfos; } @@ -1862,7 +1845,7 @@ namespace EMotionFX AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.Resize(numNodes); + lodLevel.mNodeInfos.resize(numNodes); } Pose* bindPose = mSkeleton->GetBindPose(); @@ -1878,7 +1861,7 @@ namespace EMotionFX AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.AddEmpty(); + lodLevel.mNodeInfos.emplace_back(); } mSkeleton->GetBindPose()->LinkToActor(this, Pose::FLAG_LOCALTRANSFORMREADY, false); @@ -1909,7 +1892,7 @@ namespace EMotionFX AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.Remove(nr); + lodLevel.mNodeInfos.erase(AZStd::next(begin(lodLevel.mNodeInfos), nr)); } } @@ -1920,20 +1903,20 @@ namespace EMotionFX AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.Clear(); + lodLevel.mNodeInfos.clear(); } } void Actor::ReserveMaterials(uint32 lodLevel, uint32 numMaterials) { - mMaterials[lodLevel].Reserve(numMaterials); + mMaterials[lodLevel].reserve(numMaterials); } // get a material Material* Actor::GetMaterial(uint32 lodLevel, uint32 nr) const { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - MCORE_ASSERT(nr < mMaterials[lodLevel].GetLength()); + MCORE_ASSERT(lodLevel < mMaterials.size()); + MCORE_ASSERT(nr < mMaterials[lodLevel].size()); return mMaterials[lodLevel][nr]; } @@ -1941,10 +1924,10 @@ namespace EMotionFX // get a material by name uint32 Actor::FindMaterialIndexByName(uint32 lodLevel, const char* name) const { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); + MCORE_ASSERT(lodLevel < mMaterials.size()); // search through all materials - const uint32 numMaterials = mMaterials[lodLevel].GetLength(); + const uint32 numMaterials = mMaterials[lodLevel].size(); for (uint32 i = 0; i < numMaterials; ++i) { if (mMaterials[lodLevel][i]->GetNameString() == name) @@ -1960,27 +1943,26 @@ namespace EMotionFX // set a material void Actor::SetMaterial(uint32 lodLevel, uint32 nr, Material* mat) { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - MCORE_ASSERT(nr < mMaterials[lodLevel].GetLength()); + MCORE_ASSERT(lodLevel < mMaterials.size()); + MCORE_ASSERT(nr < mMaterials[lodLevel].size()); mMaterials[lodLevel][nr] = mat; } void Actor::AddMaterial(uint32 lodLevel, Material* mat) { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - mMaterials[lodLevel].Add(mat); + MCORE_ASSERT(lodLevel < mMaterials.size()); + mMaterials[lodLevel].emplace_back(mat); } - uint32 Actor::GetNumMaterials(uint32 lodLevel) const + size_t Actor::GetNumMaterials(uint32 lodLevel) const { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - return mMaterials[lodLevel].GetLength(); + MCORE_ASSERT(lodLevel < mMaterials.size()); + return mMaterials[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(); } @@ -2022,7 +2004,7 @@ namespace EMotionFX void Actor::AddDependency(const Dependency& dependency) { - mDependencies.Add(dependency); + mDependencies.emplace_back(dependency); } @@ -2459,8 +2441,8 @@ namespace EMotionFX const AZ::u32 numSubMeshes = mesh->GetNumSubMeshes(); for (AZ::u32 subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) { - const MCore::Array& subMeshJoints = mesh->GetSubMesh(subMeshIndex)->GetBonesArray(); - const AZ::u32 numSubMeshJoints = subMeshJoints.GetLength(); + const AZStd::vector& subMeshJoints = mesh->GetSubMesh(subMeshIndex)->GetBonesArray(); + const AZ::u32 numSubMeshJoints = subMeshJoints.size(); for (AZ::u32 i = 0; i < numSubMeshJoints; ++i) { InsertJointAndParents(subMeshJoints[i], includedJointIndices); @@ -2678,13 +2660,13 @@ namespace EMotionFX // 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)); + mMaterials.resize(numLODLevels); for (size_t lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) { const AZ::Data::Asset& lodAsset = lodAssets[lodLevel]; - lodLevels[lodLevel].mNodeInfos.Resize(numNodes); + lodLevels[lodLevel].mNodeInfos.resize(numNodes); // Create a single mesh for the actor. Mesh* mesh = Mesh::CreateFromModelLod(lodAsset, m_skinToSkeletonIndexMap); @@ -2798,7 +2780,7 @@ 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(mMorphSetups.size() == numLODLevels, "There needs to be a morph setup for every single LOD level."); for (size_t lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h index faf5b6b94d..0894d22c4c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -22,7 +22,7 @@ // include MCore related files #include -#include +#include #include #include @@ -188,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(uint32 endNodeIndex, AZStd::vector& outPath) const; /** * Set the motion extraction node. @@ -245,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(uint32 lodLevel, AZStd::vector* outBoneList) const; //------------------------------------------------ void SetPhysicsSetup(const AZStd::shared_ptr& physicsSetup); @@ -313,7 +313,7 @@ namespace EMotionFX * @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(uint32 lodLevel) const; /** * Removes all materials from this actor. @@ -367,7 +367,7 @@ namespace EMotionFX * 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; //-------------------------------------------------------------------------- @@ -438,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, uint32 skeletalLODLevel, uint32 geometryLODLevel); /** * Checks if the given material is used by a given mesh. @@ -522,7 +522,7 @@ 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 mDependencies.size(); } /** * Get a given dependency. @@ -658,7 +658,7 @@ namespace EMotionFX */ MCORE_INLINE const NodeMirrorInfo& GetNodeMirrorInfo(uint32 nodeIndex) const { return mNodeMirrorInfos[nodeIndex]; } - MCORE_INLINE bool GetHasMirrorInfo() const { return (mNodeMirrorInfos.GetLength() != 0); } + MCORE_INLINE bool GetHasMirrorInfo() const { return (mNodeMirrorInfos.size() != 0); } //--------------------------------------------------------------- @@ -749,9 +749,9 @@ namespace EMotionFX 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; } @@ -861,15 +861,38 @@ namespace EMotionFX MeshDeformerStack* mStack; NodeLODInfo(); + NodeLODInfo(const NodeLODInfo&) = delete; + NodeLODInfo(NodeLODInfo&& rhs) + { + if (&rhs == this) + { + return; + } + mMesh = rhs.mMesh; + mStack = rhs.mStack; + rhs.mMesh = nullptr; + rhs.mStack = nullptr; + } + NodeLODInfo& operator=(const NodeLODInfo&) = delete; + NodeLODInfo& operator=(NodeLODInfo&& rhs) + { + if (&rhs == this) + { + return *this; + } + mMesh = rhs.mMesh; + mStack = rhs.mStack; + rhs.mMesh = nullptr; + rhs.mStack = nullptr; + return *this; + } ~NodeLODInfo(); }; // a lod level struct EMFX_API LODLevel { - MCore::Array mNodeInfos; - - LODLevel(); + AZStd::vector mNodeInfos; }; struct MeshLODData @@ -896,12 +919,12 @@ 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 mDependencies; /**< The dependencies on other actors (shared meshes and transforms). */ 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. */ + AZStd::vector mNodeMirrorInfos; /**< The array of node mirror info. */ + AZStd::vector< AZStd::vector< Material* > > mMaterials; /**< A collection of materials (for each lod). */ + AZStd::vector< MorphSetup* > mMorphSetups; /**< A morph setup for each geometry LOD. */ MCore::SmallArray mNodeGroups; /**< 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 */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index b80aab3c50..34af57026a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -45,11 +45,7 @@ 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()); + mEnabledNodes.reserve(actor->GetNumNodes()); // set the actor and create the motion system mBoolFlags = 0; @@ -174,7 +170,7 @@ namespace EMotionFX // delete all attachments // actor instances that are attached will be detached, and not deleted from memory - const uint32 numAttachments = mAttachments.GetLength(); + const uint32 numAttachments = mAttachments.size(); for (uint32 i = 0; i < numAttachments; ++i) { ActorInstance* attachmentActorInstance = mAttachments[i]->GetAttachmentActorInstance(); @@ -187,7 +183,7 @@ namespace EMotionFX } mAttachments[i]->Destroy(); } - mAttachments.Clear(); + mAttachments.clear(); if (mMorphSetup) { @@ -396,7 +392,7 @@ namespace EMotionFX // Update the mesh deformers. const Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = mEnabledNodes.GetLength(); + const uint32 numNodes = mEnabledNodes.size(); for (uint32 i = 0; i < numNodes; ++i) { const uint16 nodeNr = mEnabledNodes[i]; @@ -416,7 +412,7 @@ namespace EMotionFX // Update the mesh morph deformers. const Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = mEnabledNodes.GetLength(); + const uint32 numNodes = mEnabledNodes.size(); for (uint32 i = 0; i < numNodes; ++i) { const uint16 nodeNr = mEnabledNodes[i]; @@ -448,7 +444,7 @@ namespace EMotionFX GetActorManager().GetScheduler()->RecursiveRemoveActorInstance(root); // add the attachment - mAttachments.Add(attachment); + mAttachments.emplace_back(attachment); ActorInstance* attachmentActorInstance = attachment->GetAttachmentActorInstance(); if (attachmentActorInstance) { @@ -468,7 +464,7 @@ namespace EMotionFX uint32 ActorInstance::FindAttachmentNr(ActorInstance* actorInstance) { // for all attachments - const uint32 numAttachments = mAttachments.GetLength(); + const uint32 numAttachments = mAttachments.size(); for (uint32 i = 0; i < numAttachments; ++i) { if (mAttachments[i]->GetAttachmentActorInstance() == actorInstance) @@ -498,7 +494,7 @@ namespace EMotionFX // remove an attachment void ActorInstance::RemoveAttachment(uint32 nr, bool delFromMem) { - MCORE_ASSERT(nr < mAttachments.GetLength()); + MCORE_ASSERT(nr < mAttachments.size()); // first remove the current attachment tree from the scheduler ActorInstance* root = FindAttachmentRoot(); @@ -528,7 +524,7 @@ namespace EMotionFX } // remove it from the attachment list - mAttachments.Remove(nr); + mAttachments.erase(AZStd::next(begin(mAttachments), nr)); // and re-add the root to the scheduler GetActorManager().GetScheduler()->RecursiveInsertActorInstance(root, 0); @@ -544,9 +540,9 @@ namespace EMotionFX void ActorInstance::RemoveAllAttachments(bool delFromMem) { // keep removing the last attachment until there are none left - while (mAttachments.GetLength()) + while (mAttachments.size()) { - RemoveAttachment(mAttachments.GetLength() - 1, delFromMem); + RemoveAttachment(mAttachments.size() - 1, delFromMem); } } @@ -554,19 +550,19 @@ namespace EMotionFX void ActorInstance::UpdateDependencies() { // get rid of existing dependencies - mDependencies.Clear(); + mDependencies.clear(); // add the main dependency Actor::Dependency mainDependency; mainDependency.mActor = mActor; mainDependency.mAnimGraph = (mAnimGraphInstance) ? mAnimGraphInstance->GetAnimGraph() : nullptr; - mDependencies.Add(mainDependency); + mDependencies.emplace_back(mainDependency); // add all dependencies stored inside the actor const uint32 numDependencies = mActor->GetNumDependencies(); for (uint32 i = 0; i < numDependencies; ++i) { - mDependencies.Add(*mActor->GetDependency(i)); + mDependencies.emplace_back(*mActor->GetDependency(i)); } } @@ -574,7 +570,7 @@ namespace EMotionFX void ActorInstance::UpdateAttachments() { // update all attachments - const uint32 numAttachments = mAttachments.GetLength(); + const uint32 numAttachments = mAttachments.size(); for (uint32 i = 0; i < numAttachments; ++i) { mAttachments[i]->Update(); @@ -1089,7 +1085,7 @@ 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(mEnabledNodes), end(mEnabledNodes), nodeIndex) != end(mEnabledNodes)) { return; } @@ -1105,16 +1101,16 @@ namespace EMotionFX uint32 parentIndex = skeleton->GetNode(curNode)->GetParentIndex(); if (parentIndex != MCORE_INVALIDINDEX32) { - const uint32 parentArrayIndex = mEnabledNodes.Find(static_cast(parentIndex)); - if (parentArrayIndex != MCORE_INVALIDINDEX32) + const auto parentArrayIter = AZStd::find(begin(mEnabledNodes), end(mEnabledNodes), static_cast(parentIndex)); + if (parentArrayIter != end(mEnabledNodes)) { - if (parentArrayIndex + 1 >= mEnabledNodes.GetLength()) + if (parentArrayIter + 1 == end(mEnabledNodes)) { - mEnabledNodes.Add(nodeIndex); + mEnabledNodes.emplace_back(nodeIndex); } else { - mEnabledNodes.Insert(parentArrayIndex + 1, nodeIndex); + mEnabledNodes.emplace(parentArrayIter + 1, nodeIndex); } found = true; } @@ -1125,7 +1121,7 @@ namespace EMotionFX } else // if we're dealing with a root node, insert it in the front of the array { - mEnabledNodes.Insert(0, nodeIndex); + mEnabledNodes.emplace(AZStd::next(begin(mEnabledNodes), 0), nodeIndex); found = true; } } while (found == false); @@ -1135,14 +1131,18 @@ namespace EMotionFX void ActorInstance::DisableNode(uint16 nodeIndex) { // try to remove the node from the array - mEnabledNodes.RemoveByValue(nodeIndex); + const auto it = AZStd::find(begin(mEnabledNodes), end(mEnabledNodes), nodeIndex); + if (it != end(mEnabledNodes)) + { + mEnabledNodes.erase(it); + } } // enable all nodes void ActorInstance::EnableAllNodes() { const uint32 numNodes = mActor->GetNumNodes(); - mEnabledNodes.Resize(numNodes); + mEnabledNodes.resize(numNodes); for (uint32 i = 0; i < numNodes; ++i) { mEnabledNodes[i] = static_cast(i); @@ -1152,7 +1152,7 @@ namespace EMotionFX // disable all nodes void ActorInstance::DisableAllNodes() { - mEnabledNodes.Clear(); + mEnabledNodes.clear(); } // change the skeletal LOD level @@ -1587,9 +1587,9 @@ namespace EMotionFX m_aabb = aabb; } - uint32 ActorInstance::GetNumAttachments() const + size_t ActorInstance::GetNumAttachments() const { - return mAttachments.GetLength(); + return mAttachments.size(); } Attachment* ActorInstance::GetAttachment(uint32 nr) const @@ -1612,9 +1612,9 @@ namespace EMotionFX return mSelfAttachment; } - uint32 ActorInstance::GetNumDependencies() const + size_t ActorInstance::GetNumDependencies() const { - return mDependencies.GetLength(); + return mDependencies.size(); } Actor::Dependency* ActorInstance::GetDependency(uint32 nr) @@ -1779,7 +1779,7 @@ namespace EMotionFX SetIsVisible(isVisible); // recurse to all child attachments - const uint32 numAttachments = mAttachments.GetLength(); + const uint32 numAttachments = mAttachments.size(); for (uint32 i = 0; i < numAttachments; ++i) { mAttachments[i]->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h index 4488a1386f..4b605afc3b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h @@ -599,7 +599,7 @@ namespace EMotionFX * 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. @@ -664,7 +664,7 @@ 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. @@ -788,13 +788,13 @@ 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 mEnabledNodes; } /** * 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 mEnabledNodes.size(); } /** * Get the node number of a given enabled node. @@ -873,10 +873,10 @@ namespace EMotionFX 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. */ + AZStd::vector mAttachments; /**< The attachments linked to this actor instance. */ + AZStd::vector 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. */ + AZStd::vector 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. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp index e40a0dde5b..a8584163ed 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp @@ -27,17 +27,13 @@ namespace EMotionFX { mScheduler = nullptr; - // set memory categories - mActorInstances.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORMANAGER); - mRootActorInstances.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORMANAGER); - // setup the default scheduler SetScheduler(MultiThreadScheduler::Create()); // reserve memory m_actors.reserve(512); - mActorInstances.Reserve(1024); - mRootActorInstances.Reserve(1024); + mActorInstances.reserve(1024); + mRootActorInstances.reserve(1024); } @@ -79,8 +75,8 @@ namespace EMotionFX void ActorManager::UnregisterAllActorInstances() { LockActorInstances(); - mActorInstances.Clear(); - mRootActorInstances.Clear(); + mActorInstances.clear(); + mRootActorInstances.clear(); if (mScheduler) { mScheduler->Clear(); @@ -104,7 +100,7 @@ namespace EMotionFX mScheduler = scheduler; // adjust all visibility flags to false for all actor instances - const uint32 numActorInstances = mActorInstances.GetLength(); + const uint32 numActorInstances = mActorInstances.size(); for (uint32 i = 0; i < numActorInstances; ++i) { mActorInstances[i]->SetIsVisible(false); @@ -139,7 +135,7 @@ namespace EMotionFX { LockActorInstances(); - mActorInstances.Add(actorInstance); + mActorInstances.emplace_back(actorInstance); UpdateActorInstanceStatus(actorInstance, false); UnlockActorInstances(); @@ -213,7 +209,7 @@ namespace EMotionFX LockActorInstances(); // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); + const uint32 numActorInstances = mActorInstances.size(); for (uint32 i = 0; i < numActorInstances; ++i) { if (mActorInstances[i] == actorInstance) @@ -233,7 +229,7 @@ namespace EMotionFX uint32 ActorManager::FindActorInstanceIndex(ActorInstance* actorInstance) const { // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); + const uint32 numActorInstances = mActorInstances.size(); for (uint32 i = 0; i < numActorInstances; ++i) { if (mActorInstances[i] == actorInstance) @@ -251,7 +247,7 @@ namespace EMotionFX ActorInstance* ActorManager::FindActorInstanceByID(uint32 id) const { // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); + const uint32 numActorInstances = mActorInstances.size(); for (uint32 i = 0; i < numActorInstances; ++i) { if (mActorInstances[i]->GetID() == id) @@ -349,15 +345,18 @@ namespace EMotionFX if (actorInstance->GetAttachedTo() == nullptr) { // make sure it's in the root list - if (mRootActorInstances.Contains(actorInstance) == false) + if (AZStd::find(begin(mRootActorInstances), end(mRootActorInstances), actorInstance) == end(mRootActorInstances)) { - mRootActorInstances.Add(actorInstance); + mRootActorInstances.emplace_back(actorInstance); } } else // no root actor instance { // remove it from the root list - mRootActorInstances.RemoveByValue(actorInstance); + if (const auto it = AZStd::find(begin(mRootActorInstances), end(mRootActorInstances), actorInstance); it != end(mRootActorInstances)) + { + mRootActorInstances.erase(it); + } mScheduler->RecursiveRemoveActorInstance(actorInstance); } @@ -374,10 +373,16 @@ namespace EMotionFX LockActorInstances(); // remove the actor instance from the list - mActorInstances.RemoveByValue(instance); + if (const auto it = AZStd::find(begin(mActorInstances), end(mActorInstances), instance); it != end(mActorInstances)) + { + mActorInstances.erase(it); + } // remove it from the list of roots, if it is in there - mRootActorInstances.RemoveByValue(instance); + if (const auto it = AZStd::find(begin(mRootActorInstances), end(mRootActorInstances), instance); it != end(mRootActorInstances)) + { + mRootActorInstances.erase(it); + } // remove it from the schedule mScheduler->RemoveActorInstance(instance); @@ -416,7 +421,7 @@ namespace EMotionFX } - const MCore::Array& ActorManager::GetActorInstanceArray() const + const AZStd::vector& ActorManager::GetActorInstanceArray() const { return mActorInstances; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h index 280cc33498..34b290cfff 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 @@ -124,7 +124,7 @@ 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 mActorInstances.size(); } /** * Get a given registered actor instance. @@ -137,7 +137,7 @@ namespace EMotionFX * 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. @@ -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 mRootActorInstances.size(); } /** * Get a given root actor instance. @@ -255,9 +255,9 @@ namespace EMotionFX void UnlockActors(); private: - MCore::Array mActorInstances; /**< The registered actor instances. */ + AZStd::vector mActorInstances; /**< The registered actor instances. */ AZStd::vector> m_actors; /**< The registered actors. */ - MCore::Array mRootActorInstances; /**< Root actor instances (roots of all attachment chains). */ + AZStd::vector 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. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp index 7a9001433a..f049c498f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp @@ -36,8 +36,6 @@ namespace EMotionFX AnimGraph::AnimGraph() : mGameControllerSettings(aznew AnimGraphGameControllerSettings()) { - mNodes.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH); - mID = MCore::GetIDGenerator().GenerateID(); mDirtyFlag = false; mAutoUnregister = true; @@ -50,7 +48,7 @@ namespace EMotionFX #endif // EMFX_DEVELOPMENT_BUILD // reserve some memory - mNodes.Reserve(1024); + mNodes.reserve(1024); // automatically register the anim graph GetAnimGraphManager().AddAnimGraph(this); @@ -628,7 +626,7 @@ namespace EMotionFX mRootStateMachine->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); } @@ -725,8 +723,8 @@ namespace EMotionFX if (azrtti_istypeof(object)) { AnimGraphNode* node = static_cast(object); - node->SetNodeIndex(mNodes.GetLength()); - mNodes.Add(node); + node->SetNodeIndex(mNodes.size()); + mNodes.emplace_back(node); } // create a unique data for this added object in the animgraph instances as well @@ -765,7 +763,7 @@ namespace EMotionFX AnimGraphNode* node = static_cast(object); const uint32 nodeIndex = node->GetNodeIndex(); - const uint32 numNodes = mNodes.GetLength(); + const uint32 numNodes = mNodes.size(); for (uint32 i = nodeIndex + 1; i < numNodes; ++i) { AnimGraphNode* curNode = mNodes[i]; @@ -774,7 +772,7 @@ namespace EMotionFX } // remove the object from the array - mNodes.Remove(nodeIndex); + mNodes.erase(AZStd::next(begin(mNodes), nodeIndex)); } } @@ -789,14 +787,14 @@ namespace EMotionFX // reserve space for a given amount of nodes void AnimGraph::ReserveNumNodes(uint32 numNodes) { - mNodes.Reserve(numNodes); + mNodes.reserve(numNodes); } // Calculate number of motion nodes in the graph uint32 AnimGraph::CalcNumMotionNodes() const { - const uint32 numNodes = mNodes.GetLength(); + const uint32 numNodes = mNodes.size(); uint32 numMotionNodes = 0; for (uint32 i = 0; i < numNodes; ++i) { @@ -1029,7 +1027,7 @@ namespace EMotionFX void AnimGraph::RemoveInvalidConnections(bool logWarnings) { // Iterate over all nodes - const AZ::u32 numNodes = mNodes.GetLength(); + const AZ::u32 numNodes = mNodes.size(); for (AZ::u32 i = 0; i < numNodes; ++i) { AnimGraphNode* node = mNodes[i]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h index e7c775d644..ab1cfd926f 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,7 +65,7 @@ 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); @@ -381,7 +381,7 @@ namespace EMotionFX AnimGraphObject* GetObject(uint32 index) const { return mObjects[index]; } void ReserveNumObjects(uint32 numObjects); - uint32 GetNumNodes() const { return mNodes.GetLength(); } + size_t GetNumNodes() const { return mNodes.size(); } AnimGraphNode* GetNode(uint32 index) const { return mNodes[index]; } void ReserveNumNodes(uint32 numNodes); uint32 CalcNumMotionNodes() const; @@ -417,7 +417,7 @@ namespace EMotionFX 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 mNodes; AZStd::vector m_animGraphInstances; AZStd::string mFileName; AnimGraphStateMachine* mRootStateMachine; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h index e00fef8601..715b280690 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp index 46764744a8..1082bc112b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp @@ -57,8 +57,6 @@ namespace EMotionFX mInitSettings = *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) @@ -145,7 +143,7 @@ namespace EMotionFX { if (delFromMem) { - const uint32 numParams = mParamValues.GetLength(); + const uint32 numParams = mParamValues.size(); for (uint32 i = 0; i < numParams; ++i) { if (mParamValues[i]) @@ -155,7 +153,7 @@ namespace EMotionFX } } - mParamValues.Clear(); + mParamValues.clear(); } @@ -268,10 +266,10 @@ namespace EMotionFX RemoveAllParameters(true); const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - mParamValues.Resize(static_cast(valueParameters.size())); + mParamValues.resize(static_cast(valueParameters.size())); // init the values - const uint32 numParams = mParamValues.GetLength(); + const uint32 numParams = mParamValues.size(); for (uint32 i = 0; i < numParams; ++i) { mParamValues[i] = valueParameters[i]->ConstructDefaultValueAsAttribute(); @@ -284,22 +282,22 @@ namespace EMotionFX { // check how many parameters we need to add const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - const int32 numToAdd = static_cast(valueParameters.size()) - mParamValues.GetLength(); + const int32 numToAdd = static_cast(valueParameters.size()) - mParamValues.size(); if (numToAdd <= 0) { return; } // make sure we have the right space pre-allocated - mParamValues.Reserve(static_cast(valueParameters.size())); + mParamValues.reserve(static_cast(valueParameters.size())); // add the remaining parameters - const uint32 startIndex = mParamValues.GetLength(); + const uint32 startIndex = mParamValues.size(); for (int32 i = 0; i < numToAdd; ++i) { const uint32 index = startIndex + i; - mParamValues.AddEmpty(); - mParamValues.GetLast() = valueParameters[index]->ConstructDefaultValueAsAttribute(); + mParamValues.emplace_back(); + mParamValues.back() = valueParameters[index]->ConstructDefaultValueAsAttribute(); } } @@ -315,7 +313,7 @@ namespace EMotionFX } } - mParamValues.Remove(index); + mParamValues.erase(AZStd::next(begin(mParamValues), index)); } @@ -333,7 +331,7 @@ namespace EMotionFX void AnimGraphInstance::ReInitParameterValues() { - const AZ::u32 parameterValueCount = mParamValues.GetLength(); + const AZ::u32 parameterValueCount = mParamValues.size(); for (AZ::u32 i = 0; i < parameterValueCount; ++i) { ReInitParameterValue(i); @@ -503,15 +501,15 @@ namespace EMotionFX // add the last anim graph parameter to this instance void AnimGraphInstance::AddParameterValue() { - mParamValues.Add(nullptr); - ReInitParameterValue(mParamValues.GetLength() - 1); + mParamValues.emplace_back(nullptr); + ReInitParameterValue(mParamValues.size() - 1); } // add the parameter of the animgraph, at a given index void AnimGraphInstance::InsertParameterValue(uint32 index) { - mParamValues.Insert(index, nullptr); + mParamValues.emplace(AZStd::next(begin(mParamValues), index), nullptr); ReInitParameterValue(index); } @@ -658,7 +656,7 @@ namespace EMotionFX void AnimGraphInstance::AddUniqueObjectData() { m_uniqueDatas.emplace_back(nullptr); - mObjectFlags.Add(0); + mObjectFlags.emplace_back(0); } // remove the given unique data object @@ -676,7 +674,7 @@ namespace EMotionFX } m_uniqueDatas.erase(m_uniqueDatas.begin() + index); - mObjectFlags.Remove(index); + mObjectFlags.erase(AZStd::next(begin(mObjectFlags), index)); } @@ -684,7 +682,7 @@ namespace EMotionFX { AnimGraphObjectData* data = m_uniqueDatas[index]; m_uniqueDatas.erase(m_uniqueDatas.begin() + index); - mObjectFlags.Remove(static_cast(index)); + mObjectFlags.erase(AZStd::next(begin(mObjectFlags), static_cast(index))); if (delFromMem && data) { data->Destroy(); @@ -707,7 +705,7 @@ namespace EMotionFX } m_uniqueDatas.clear(); - mObjectFlags.Clear(); + mObjectFlags.clear(); } @@ -813,7 +811,7 @@ namespace EMotionFX { const uint32 numObjects = mAnimGraph->GetNumObjects(); m_uniqueDatas.resize(numObjects); - mObjectFlags.Resize(numObjects); + mObjectFlags.resize(numObjects); for (uint32 i = 0; i < numObjects; ++i) { m_uniqueDatas[i] = nullptr; @@ -934,7 +932,7 @@ namespace EMotionFX // reset all node flags void AnimGraphInstance::ResetFlagsForAllObjects(uint32 flagsToDisable) { - const uint32 numObjects = mObjectFlags.GetLength(); + const uint32 numObjects = mObjectFlags.size(); for (uint32 i = 0; i < numObjects; ++i) { mObjectFlags[i] &= ~flagsToDisable; @@ -967,7 +965,7 @@ namespace EMotionFX // reset all node flags void AnimGraphInstance::ResetFlagsForAllObjects() { - MCore::MemSet(mObjectFlags.GetPtr(), 0, sizeof(uint32) * mObjectFlags.GetLength()); + MCore::MemSet(mObjectFlags.data(), 0, sizeof(uint32) * mObjectFlags.size()); for (AnimGraphInstance* childInstance : m_childAnimGraphInstances) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h index 97d076d244..417883d16f 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 @@ -302,9 +302,9 @@ namespace EMotionFX ActorInstance* mActorInstance; 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 mParamValues; // a value for each AnimGraph parameter (the control parameters) AZStd::vector m_uniqueDatas; // unique object data - MCore::Array mObjectFlags; // the object flags + AZStd::vector mObjectFlags; // 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h index 9f04517982..4973437b8e 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 diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp index 44d048c03c..f9896cf677 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp @@ -1287,14 +1287,14 @@ 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) { // 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); } } } @@ -1324,7 +1324,7 @@ namespace EMotionFX } } - 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,7 +1346,7 @@ namespace EMotionFX AnimGraphTransitionCondition* condition = transition->GetCondition(j); if (azrtti_typeid(condition) == conditionType) { - outConditions->Add(condition); + outConditions->emplace_back(condition); } } } @@ -1601,9 +1601,9 @@ 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) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h index c469631335..7377f27d7c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h @@ -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; @@ -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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp index a56e8d246e..c687dcadb1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp @@ -116,9 +116,9 @@ 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() diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h index c3d6968a2d..2f01b572e3 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 @@ -153,7 +153,7 @@ namespace EMotionFX 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 - 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp index f30d742a24..5f139d9c49 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp @@ -16,10 +16,8 @@ namespace EMotionFX // constructor AnimGraphPosePool::AnimGraphPosePool() { - mPoses.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSEPOOL); - mFreePoses.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSEPOOL); - mPoses.Reserve(12); - mFreePoses.Reserve(12); + mPoses.reserve(12); + mFreePoses.reserve(12); Resize(8); mMaxUsed = 0; } @@ -29,22 +27,22 @@ namespace EMotionFX AnimGraphPosePool::~AnimGraphPosePool() { // delete all poses - const uint32 numPoses = mPoses.GetLength(); + const uint32 numPoses = mPoses.size(); for (uint32 i = 0; i < numPoses; ++i) { delete mPoses[i]; } - mPoses.Clear(); + mPoses.clear(); // clear the free array - mFreePoses.Clear(); + mFreePoses.clear(); } // resize the number of poses in the pool void AnimGraphPosePool::Resize(uint32 numPoses) { - const uint32 numOldPoses = mPoses.GetLength(); + const uint32 numOldPoses = mPoses.size(); // if we will remove poses int32 difference = numPoses - numOldPoses; @@ -54,10 +52,10 @@ namespace EMotionFX difference = abs(difference); for (int32 i = 0; i < difference; ++i) { - AnimGraphPose* pose = mPoses[mFreePoses.GetLength() - 1]; - MCORE_ASSERT(mFreePoses.Contains(pose)); // make sure the pose is not already in use + AnimGraphPose* pose = mPoses.back(); + MCORE_ASSERT(AZStd::find(begin(mFreePoses), end(mFreePoses), pose) == end(mFreePoses)); // make sure the pose is not already in use delete pose; - mPoses.Remove(mFreePoses.GetLength() - 1); + mPoses.erase(mFreePoses.end() - 1); } } else // we want to add new poses @@ -65,8 +63,8 @@ namespace EMotionFX for (int32 i = 0; i < difference; ++i) { AnimGraphPose* newPose = new AnimGraphPose(); - mPoses.Add(newPose); - mFreePoses.Add(newPose); + mPoses.emplace_back(newPose); + mFreePoses.emplace_back(newPose); } } } @@ -76,21 +74,21 @@ namespace EMotionFX AnimGraphPose* AnimGraphPosePool::RequestPose(const ActorInstance* actorInstance) { // if we have no free poses left, allocate a new one - if (mFreePoses.GetLength() == 0) + if (mFreePoses.size() == 0) { AnimGraphPose* newPose = new AnimGraphPose(); newPose->LinkToActorInstance(actorInstance); - mPoses.Add(newPose); + mPoses.emplace_back(newPose); mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedPoses()); newPose->SetIsInUse(true); return newPose; } // request the last free pose - AnimGraphPose* pose = mFreePoses[mFreePoses.GetLength() - 1]; + AnimGraphPose* pose = mFreePoses[mFreePoses.size() - 1]; //if (pose->GetActorInstance() != actorInstance) pose->LinkToActorInstance(actorInstance); - mFreePoses.RemoveLast(); // remove it from the list of free poses + mFreePoses.pop_back(); // remove it from the list of free poses mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedPoses()); pose->SetIsInUse(true); return pose; @@ -101,7 +99,7 @@ namespace EMotionFX void AnimGraphPosePool::FreePose(AnimGraphPose* pose) { //MCORE_ASSERT( mPoses.Contains(pose) ); - mFreePoses.Add(pose); + mFreePoses.emplace_back(pose); pose->SetIsInUse(false); } @@ -109,7 +107,7 @@ namespace EMotionFX // free all poses void AnimGraphPosePool::FreeAllPoses() { - const uint32 numPoses = mPoses.GetLength(); + const uint32 numPoses = mPoses.size(); for (uint32 i = 0; i < numPoses; ++i) { AnimGraphPose* curPose = mPoses[i]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h index 2c792e2005..8f7a38be97 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 @@ -41,15 +41,15 @@ namespace EMotionFX 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 size_t GetNumFreePoses() const { return mFreePoses.size(); } + MCORE_INLINE size_t GetNumPoses() const { return mPoses.size(); } + MCORE_INLINE size_t GetNumUsedPoses() const { return (mPoses.size() - mFreePoses.size()); } MCORE_INLINE uint32 GetNumMaxUsedPoses() const { return mMaxUsed; } MCORE_INLINE void ResetMaxUsedPoses() { mMaxUsed = 0; } private: - MCore::Array mPoses; - MCore::Array mFreePoses; + AZStd::vector mPoses; + AZStd::vector mFreePoses; uint32 mMaxUsed; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp index 6f77868ad7..289a9c4982 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,10 +17,8 @@ namespace EMotionFX // constructor AnimGraphRefCountedDataPool::AnimGraphRefCountedDataPool() { - mItems.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_REFCOUNTEDDATA); - mFreeItems.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_REFCOUNTEDDATA); - mItems.Reserve(32); - mFreeItems.Reserve(32); + mItems.reserve(32); + mFreeItems.reserve(32); Resize(16); mMaxUsed = 0; } @@ -28,22 +28,22 @@ namespace EMotionFX AnimGraphRefCountedDataPool::~AnimGraphRefCountedDataPool() { // delete all items - const uint32 numItems = mItems.GetLength(); + const uint32 numItems = mItems.size(); for (uint32 i = 0; i < numItems; ++i) { delete mItems[i]; } - mItems.Clear(); + mItems.clear(); // clear the free array - mFreeItems.Clear(); + mFreeItems.clear(); } // resize the number of items in the pool void AnimGraphRefCountedDataPool::Resize(uint32 numItems) { - const uint32 numOldItems = mItems.GetLength(); + const uint32 numOldItems = mItems.size(); // if we will remove Items int32 difference = numItems - numOldItems; @@ -53,10 +53,10 @@ namespace EMotionFX difference = abs(difference); for (int32 i = 0; i < difference; ++i) { - AnimGraphRefCountedData* item = mItems[mFreeItems.GetLength() - 1]; - MCORE_ASSERT(mFreeItems.Contains(item)); // make sure the Item is not already in use + AnimGraphRefCountedData* item = mItems.back(); + MCORE_ASSERT(AZStd::find(begin(mFreeItems), end(mFreeItems), item) != end(mFreeItems)); // make sure the Item is not already in use delete item; - mItems.Remove(mFreeItems.GetLength() - 1); + mItems.erase(mItems.end() - 1); } } else // we want to add new Items @@ -64,8 +64,8 @@ namespace EMotionFX for (int32 i = 0; i < difference; ++i) { AnimGraphRefCountedData* newItem = new AnimGraphRefCountedData(); - mItems.Add(newItem); - mFreeItems.Add(newItem); + mItems.emplace_back(newItem); + mFreeItems.emplace_back(newItem); } } } @@ -75,17 +75,17 @@ namespace EMotionFX AnimGraphRefCountedData* AnimGraphRefCountedDataPool::RequestNew() { // if we have no free items left, allocate a new one - if (mFreeItems.GetLength() == 0) + if (mFreeItems.size() == 0) { AnimGraphRefCountedData* newItem = new AnimGraphRefCountedData(); - mItems.Add(newItem); + mItems.emplace_back(newItem); mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedItems()); return newItem; } // request the last free item - AnimGraphRefCountedData* item = mFreeItems[mFreeItems.GetLength() - 1]; - mFreeItems.RemoveLast(); // remove it from the list of free Items + AnimGraphRefCountedData* item = mFreeItems[mFreeItems.size() - 1]; + mFreeItems.pop_back(); // remove it from the list of free Items mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedItems()); return item; } @@ -94,7 +94,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(mItems), end(mItems), item) != end(mItems)); + mFreeItems.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..33590766ff 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 @@ -34,15 +34,15 @@ namespace EMotionFX 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 size_t GetNumFreeItems() const { return mFreeItems.size(); } + MCORE_INLINE size_t GetNumItems() const { return mItems.size(); } + MCORE_INLINE size_t GetNumUsedItems() const { return (mItems.size() - mFreeItems.size()); } MCORE_INLINE uint32 GetNumMaxUsedItems() const { return mMaxUsed; } MCORE_INLINE void ResetMaxUsedItems() { mMaxUsed = 0; } private: - MCore::Array mItems; - MCore::Array mFreeItems; + AZStd::vector mItems; + AZStd::vector mFreeItems; uint32 mMaxUsed; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp index 57500b01d9..e6f6bb0985 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp @@ -499,7 +499,7 @@ namespace EMotionFX } - void AnimGraphReferenceNode::RecursiveCollectObjects(MCore::Array& outObjects) const + void AnimGraphReferenceNode::RecursiveCollectObjects(AZStd::vector& outObjects) const { AnimGraphNode::RecursiveCollectObjects(outObjects); 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/AnimGraphStateMachine.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp index 2db1d920ef..a191ae9e13 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp @@ -1277,7 +1277,7 @@ namespace EMotionFX return result; } - void AnimGraphStateMachine::RecursiveCollectObjects(MCore::Array& outObjects) const + void AnimGraphStateMachine::RecursiveCollectObjects(AZStd::vector& outObjects) const { for (const AnimGraphStateTransition* transition : mTransitions) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h index 7c0a5a14f9..8583a8a6e3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h @@ -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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp index 15d6f6bd3a..de3fa990bf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp @@ -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) { condition->RecursiveCollectObjects(outObjects); } - outObjects.Add(const_cast(this)); + outObjects.emplace_back(const_cast(this)); } // calculate the blend weight, based on the type of smoothing diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h index 5e8d5446ef..c9347111bb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h @@ -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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h index 1775eb4789..b1f3387df7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h @@ -97,7 +97,7 @@ 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp index ba81cc41b5..d58b4286b9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp @@ -107,7 +107,6 @@ namespace EMotionFX // constructor EMotionFXManager::EMotionFXManager() { - mThreadDatas.SetMemoryCategory(EMFX_MEMCATEGORY_EMOTIONFXMANAGER); // build the low version string AZStd::string lowVersionString; BuildLowVersionString(lowVersionString); @@ -174,11 +173,11 @@ namespace EMotionFX mEventManager = nullptr; // delete the thread datas - for (uint32 i = 0; i < mThreadDatas.GetLength(); ++i) + for (uint32 i = 0; i < mThreadDatas.size(); ++i) { mThreadDatas[i]->Destroy(); } - mThreadDatas.Clear(); + mThreadDatas.clear(); } @@ -477,19 +476,19 @@ namespace EMotionFX numThreads = 1; } - if (mThreadDatas.GetLength() == numThreads) + if (mThreadDatas.size() == numThreads) { return; } // get rid of old data - for (uint32 i = 0; i < mThreadDatas.GetLength(); ++i) + for (uint32 i = 0; i < mThreadDatas.size(); ++i) { mThreadDatas[i]->Destroy(); } - mThreadDatas.Clear(false); // force calling constructors again to reset everything - mThreadDatas.Resize(numThreads); + mThreadDatas.clear(); // force calling constructors again to reset everything + mThreadDatas.resize(numThreads); for (uint32 i = 0; i < numThreads; ++i) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.h index 824cc95850..45bf59c94c 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" @@ -268,13 +268,13 @@ namespace EMotionFX * @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 < mThreadDatas.size()); return mThreadDatas[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 mThreadDatas.size(); } /** * Shrink the memory pools, to reduce memory usage. @@ -354,7 +354,7 @@ namespace EMotionFX Recorder* mRecorder; /**< The recorder. */ MotionInstancePool* mMotionInstancePool; /**< The motion instance pool. */ DebugDraw* mDebugDraw; /**< The debug drawing system. */ - MCore::Array mThreadDatas; /**< The per thread data. */ + AZStd::vector 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. */ bool m_isInEditorMode; /**< True when the runtime requires to support an editor. Optimizations can be made if there is no need for editor support. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.h index 5f87b66388..cf47eff346 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" diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp index 9f6429abd7..18ec99b435 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp @@ -280,7 +280,7 @@ namespace EMotionFX mStringStorageSize = 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); @@ -904,9 +904,9 @@ namespace EMotionFX // read all tracks AZStd::string trackName; - MCore::Array typeStrings; - MCore::Array paramStrings; - MCore::Array mirrorTypeStrings; + AZStd::vector typeStrings; + AZStd::vector paramStrings; + AZStd::vector mirrorTypeStrings; for (uint32 t = 0; t < fileEventTable.mNumTracks; ++t) { // read the motion event table header @@ -934,9 +934,9 @@ namespace EMotionFX } // the even type and parameter strings - typeStrings.Resize(fileTrack.mNumTypeStrings); - paramStrings.Resize(fileTrack.mNumParamStrings); - mirrorTypeStrings.Resize(fileTrack.mNumMirrorTypeStrings); + typeStrings.resize(fileTrack.mNumTypeStrings); + paramStrings.resize(fileTrack.mNumParamStrings); + mirrorTypeStrings.resize(fileTrack.mNumMirrorTypeStrings); // read all type strings if (GetLogging()) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h index 56822c6940..66a2193b71 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,7 +94,7 @@ 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. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp index 82da9ccd86..069182883c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp @@ -47,9 +47,6 @@ namespace EMotionFX Importer::Importer() : BaseObject() { - // set the memory category - mChunkProcessors.SetMemoryCategory(EMFX_MEMCATEGORY_IMPORTER); - // register all standard chunks RegisterStandardChunks(); @@ -63,7 +60,7 @@ namespace EMotionFX Importer::~Importer() { // remove all chunk processors - const uint32 numProcessors = mChunkProcessors.GetLength(); + const uint32 numProcessors = mChunkProcessors.size(); for (uint32 i = 0; i < numProcessors; ++i) { mChunkProcessors[i]->Destroy(); @@ -110,7 +107,6 @@ namespace EMotionFX MCore::LogError("Unsupported endian type used! (endian type = %d)", header.mEndianType); return false; } - ; // yes, it is a valid actor file! return true; @@ -150,7 +146,6 @@ namespace EMotionFX MCore::LogError("Unsupported endian type used! (endian type = %d)", header.mEndianType); return false; } - ; // yes, it is a valid motion file! return true; @@ -291,8 +286,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 @@ -360,7 +354,7 @@ namespace EMotionFX // get rid of shared data ResetSharedData(sharedData); - sharedData.Clear(); + sharedData.clear(); // return the created actor return actor; @@ -461,8 +455,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 @@ -513,7 +506,7 @@ namespace EMotionFX // get rid of shared data ResetSharedData(sharedData); - sharedData.Clear(); + sharedData.clear(); return motion; } @@ -671,8 +664,7 @@ namespace EMotionFX } // create the shared data - MCore::Array sharedData; - sharedData.SetMemoryCategory(EMFX_MEMCATEGORY_IMPORTER); + AZStd::vector sharedData; PrepareSharedData(sharedData); //----------------------------------------------- @@ -710,7 +702,7 @@ namespace EMotionFX // get rid of shared data ResetSharedData(sharedData); - sharedData.Clear(); + sharedData.clear(); // return the created actor return nodeMap; @@ -722,26 +714,26 @@ namespace EMotionFX void Importer::RegisterChunkProcessor(ChunkProcessor* processorToRegister) { MCORE_ASSERT(processorToRegister); - mChunkProcessors.Add(processorToRegister); + mChunkProcessors.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(); + const uint32 numSharedData = sharedDataArray->size(); for (uint32 i = 0; i < numSharedData; ++i) { - SharedData* sharedData = sharedDataArray->GetItem(i); + SharedData* sharedData = sharedDataArray->at(i); // check if it's the type we are searching for if (sharedData->GetType() == type) @@ -772,7 +764,7 @@ namespace EMotionFX mLogDetails = detailLoggingActive; // set the processors logging flag - const int32 numProcessors = mChunkProcessors.GetLength(); + const int32 numProcessors = mChunkProcessors.size(); for (int32 i = 0; i < numProcessors; i++) { ChunkProcessor* processor = mChunkProcessors[i]; @@ -787,7 +779,7 @@ namespace EMotionFX } - void Importer::PrepareSharedData(MCore::Array& sharedData) + void Importer::PrepareSharedData(AZStd::vector& sharedData) { // create standard shared objects AddSharedData(sharedData, SharedHelperData::Create()); @@ -795,16 +787,16 @@ 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(); + const int32 numSharedData = sharedData.size(); for (int32 i = 0; i < numSharedData; i++) { SharedData* data = sharedData[i]; data->Reset(); data->Destroy(); } - sharedData.Clear(); + sharedData.clear(); } @@ -812,7 +804,7 @@ namespace EMotionFX ChunkProcessor* Importer::FindChunk(uint32 chunkID, uint32 version) const { // for all chunk processors - const uint32 numProcessors = mChunkProcessors.GetLength(); + const uint32 numProcessors = mChunkProcessors.size(); for (uint32 i = 0; i < numProcessors; ++i) { ChunkProcessor* processor = mChunkProcessors[i]; @@ -833,7 +825,7 @@ namespace EMotionFX void Importer::RegisterStandardChunks() { // reserve space for 75 chunk processors - mChunkProcessors.Reserve(75); + mChunkProcessors.reserve(75); // shared processors RegisterChunkProcessor(aznew ChunkProcessorMotionEventTrackTable()); @@ -912,12 +904,12 @@ namespace EMotionFX bool mustSkip = false; // check if we specified to ignore this chunk - if (actorSettings && actorSettings->mChunkIDsToIgnore.Contains(chunk.mChunkID)) + if (actorSettings && AZStd::find(begin(actorSettings->mChunkIDsToIgnore), end(actorSettings->mChunkIDsToIgnore), chunk.mChunkID) != end(actorSettings->mChunkIDsToIgnore)) { mustSkip = true; } - if (skelMotionSettings && skelMotionSettings->mChunkIDsToIgnore.Contains(chunk.mChunkID)) + if (skelMotionSettings && AZStd::find(begin(skelMotionSettings->mChunkIDsToIgnore), end(skelMotionSettings->mChunkIDsToIgnore), chunk.mChunkID) != end(skelMotionSettings->mChunkIDsToIgnore)) { mustSkip = true; } @@ -963,20 +955,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->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_TANGENTS) == end(settings->mLayerIDsToIgnore)) { - settings->mLayerIDsToIgnore.Add(Mesh::ATTRIB_TANGENTS); + settings->mLayerIDsToIgnore.emplace_back(Mesh::ATTRIB_TANGENTS); } - if (!settings->mLayerIDsToIgnore.Contains(Mesh::ATTRIB_BITANGENTS)) + if (AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_BITANGENTS) == end(settings->mLayerIDsToIgnore)) { - settings->mLayerIDsToIgnore.Add(Mesh::ATTRIB_BITANGENTS); + settings->mLayerIDsToIgnore.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->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_ORGVTXNUMBERS); it != end(settings->mLayerIDsToIgnore)) + { + settings->mLayerIDsToIgnore.erase(it); + } + if(const auto it = AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_NORMALS); it != end(settings->mLayerIDsToIgnore)) + { + settings->mLayerIDsToIgnore.erase(it); + } + if(const auto it = AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_POSITIONS); it != end(settings->mLayerIDsToIgnore)) + { + settings->mLayerIDsToIgnore.erase(it); + } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h index 2b12f93a1a..a708e7f017 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 @@ -82,8 +82,8 @@ namespace EMotionFX 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. */ + AZStd::vector mChunkIDsToIgnore; /**< Add chunk ID's to this array. Chunks with these ID's will not be processed. */ + AZStd::vector mLayerIDsToIgnore; /**< Add vertex attribute layer ID's to ignore. */ /** * If the actor need to be optimized for server, will overwrite a few other actor settings. @@ -105,7 +105,7 @@ namespace EMotionFX 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. */ + AZStd::vector mChunkIDsToIgnore; /**< Add the ID's of the chunks you wish to ignore. */ }; /** @@ -133,7 +133,7 @@ namespace EMotionFX Motion* mMotion = nullptr; Importer::ActorSettings* mActorSettings = nullptr; Importer::MotionSettings* mMotionSettings = nullptr; - MCore::Array* mSharedData = nullptr; + AZStd::vector* mSharedData = nullptr; MCore::Endian::EEndianType mEndianType = MCore::Endian::ENDIAN_LITTLE; NodeMap* mNodeMap = nullptr; @@ -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,7 +355,7 @@ namespace EMotionFX private: - MCore::Array mChunkProcessors; /**< The registered chunk processors. */ + AZStd::vector 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. */ @@ -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/KeyTrackLinearDynamic.h b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h index 2635e12a71..8c5c56895a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h @@ -41,22 +41,13 @@ 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(); - static void Reflect(AZ::ReflectContext* context); /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl index b28c9973fc..94abe4d707 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl @@ -6,13 +6,6 @@ * */ -// default constructor -template -KeyTrackLinearDynamic::KeyTrackLinearDynamic() -{ -} - - // extended constructor template KeyTrackLinearDynamic::KeyTrackLinearDynamic(uint32 nrKeys) @@ -21,13 +14,6 @@ KeyTrackLinearDynamic::KeyTrackLinearDynamic(uint32 nrK } -// destructor -template -KeyTrackLinearDynamic::~KeyTrackLinearDynamic() -{ - ClearKeys(); -} - template void KeyTrackLinearDynamic::Reflect(AZ::ReflectContext* context) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index 3ece1e24af..36fc898ed1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -36,11 +36,6 @@ namespace EMotionFX 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); } // allocation constructor @@ -54,11 +49,6 @@ namespace EMotionFX 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); - // allocate the mesh data Allocate(numVerts, numIndices, numPolygons, numOrgVerts); } @@ -384,7 +374,7 @@ namespace EMotionFX // copy all original data over the output data void Mesh::ResetToOriginalData() { - const uint32 numLayers = mVertexAttributes.GetLength(); + const uint32 numLayers = mVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { mVertexAttributes[i]->ResetToOriginalData(); @@ -402,12 +392,12 @@ namespace EMotionFX RemoveAllVertexAttributeLayers(); // get rid of all sub meshes - const uint32 numSubMeshes = mSubMeshes.GetLength(); + const uint32 numSubMeshes = mSubMeshes.size(); for (uint32 i = 0; i < numSubMeshes; ++i) { mSubMeshes[i]->Destroy(); } - mSubMeshes.Clear(); + mSubMeshes.clear(); if (mIndices) { @@ -668,10 +658,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 +693,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); } } } @@ -818,7 +808,7 @@ namespace EMotionFX void Mesh::RemoveSubMesh(uint32 nr, bool delFromMem) { SubMesh* subMesh = mSubMeshes[nr]; - mSubMeshes.Remove(nr); + mSubMeshes.erase(AZStd::next(begin(mSubMeshes), nr)); if (delFromMem) { subMesh->Destroy(); @@ -829,7 +819,7 @@ namespace EMotionFX // insert a given submesh void Mesh::InsertSubMesh(uint32 insertIndex, SubMesh* subMesh) { - mSubMeshes.Insert(insertIndex, subMesh); + mSubMeshes.emplace(AZStd::next(begin(mSubMeshes), insertIndex), subMesh); } @@ -839,7 +829,7 @@ namespace EMotionFX uint32 numLayers = 0; // check the types of all vertex attribute layers - const uint32 numAttributes = mVertexAttributes.GetLength(); + const uint32 numAttributes = mVertexAttributes.size(); for (uint32 i = 0; i < numAttributes; ++i) { if (mVertexAttributes[i]->GetType() == type) @@ -862,21 +852,21 @@ namespace EMotionFX VertexAttributeLayer* Mesh::GetSharedVertexAttributeLayer(uint32 layerNr) { - MCORE_ASSERT(layerNr < mSharedVertexAttributes.GetLength()); + MCORE_ASSERT(layerNr < mSharedVertexAttributes.size()); return mSharedVertexAttributes[layerNr]; } void Mesh::AddSharedVertexAttributeLayer(VertexAttributeLayer* layer) { - MCORE_ASSERT(mSharedVertexAttributes.Contains(layer) == false); - mSharedVertexAttributes.Add(layer); + MCORE_ASSERT(AZStd::find(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), layer) == end(mSharedVertexAttributes)); + mSharedVertexAttributes.emplace_back(layer); } - uint32 Mesh::GetNumSharedVertexAttributeLayers() const + size_t Mesh::GetNumSharedVertexAttributeLayers() const { - return mSharedVertexAttributes.GetLength(); + return mSharedVertexAttributes.size(); } @@ -885,7 +875,7 @@ namespace EMotionFX uint32 layerCounter = 0; // check all vertex attributes of our first vertex, and find where the specific attribute is - const uint32 numLayers = mSharedVertexAttributes.GetLength(); + const uint32 numLayers = mSharedVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { VertexAttributeLayer* layer = mSharedVertexAttributes[i]; @@ -922,10 +912,10 @@ namespace EMotionFX // delete all shared attribute layers void Mesh::RemoveAllSharedVertexAttributeLayers() { - while (mSharedVertexAttributes.GetLength()) + while (mSharedVertexAttributes.size()) { - mSharedVertexAttributes.GetLast()->Destroy(); - mSharedVertexAttributes.RemoveLast(); + mSharedVertexAttributes.back()->Destroy(); + mSharedVertexAttributes.pop_back(); } } @@ -933,29 +923,29 @@ namespace EMotionFX // remove a layer by its index void Mesh::RemoveSharedVertexAttributeLayer(uint32 layerNr) { - MCORE_ASSERT(layerNr < mSharedVertexAttributes.GetLength()); + MCORE_ASSERT(layerNr < mSharedVertexAttributes.size()); mSharedVertexAttributes[layerNr]->Destroy(); - mSharedVertexAttributes.Remove(layerNr); + mSharedVertexAttributes.erase(AZStd::next(begin(mSharedVertexAttributes), layerNr)); } - uint32 Mesh::GetNumVertexAttributeLayers() const + size_t Mesh::GetNumVertexAttributeLayers() const { - return mVertexAttributes.GetLength(); + return mVertexAttributes.size(); } VertexAttributeLayer* Mesh::GetVertexAttributeLayer(uint32 layerNr) { - MCORE_ASSERT(layerNr < mVertexAttributes.GetLength()); + MCORE_ASSERT(layerNr < mVertexAttributes.size()); return mVertexAttributes[layerNr]; } void Mesh::AddVertexAttributeLayer(VertexAttributeLayer* layer) { - MCORE_ASSERT(mVertexAttributes.Contains(layer) == false); - mVertexAttributes.Add(layer); + MCORE_ASSERT(AZStd::find(begin(mVertexAttributes), end(mVertexAttributes), layer) == end(mVertexAttributes)); + mVertexAttributes.emplace_back(layer); } @@ -965,7 +955,7 @@ namespace EMotionFX uint32 layerCounter = 0; // check all vertex attributes of our first vertex, and find where the specific attribute is - const uint32 numLayers = mVertexAttributes.GetLength(); + const uint32 numLayers = mVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { VertexAttributeLayer* layer = mVertexAttributes[i]; @@ -989,7 +979,7 @@ namespace EMotionFX uint32 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(); + const uint32 numLayers = mVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { VertexAttributeLayer* layer = mVertexAttributes[i]; @@ -1035,19 +1025,19 @@ namespace EMotionFX void Mesh::RemoveAllVertexAttributeLayers() { - while (mVertexAttributes.GetLength()) + while (mVertexAttributes.size()) { - mVertexAttributes.GetLast()->Destroy(); - mVertexAttributes.RemoveLast(); + mVertexAttributes.back()->Destroy(); + mVertexAttributes.pop_back(); } } void Mesh::RemoveVertexAttributeLayer(uint32 layerNr) { - MCORE_ASSERT(layerNr < mVertexAttributes.GetLength()); + MCORE_ASSERT(layerNr < mVertexAttributes.size()); mVertexAttributes[layerNr]->Destroy(); - mVertexAttributes.Remove(layerNr); + mVertexAttributes.erase(AZStd::next(begin(mVertexAttributes), layerNr)); } @@ -1064,24 +1054,24 @@ namespace EMotionFX // copy the submesh data uint32 i; - const uint32 numSubMeshes = mSubMeshes.GetLength(); - clone->mSubMeshes.Resize(numSubMeshes); + const uint32 numSubMeshes = mSubMeshes.size(); + clone->mSubMeshes.resize(numSubMeshes); for (i = 0; i < numSubMeshes; ++i) { clone->mSubMeshes[i] = mSubMeshes[i]->Clone(clone); } // clone the shared vertex attributes - const uint32 numSharedAttributes = mSharedVertexAttributes.GetLength(); - clone->mSharedVertexAttributes.Resize(numSharedAttributes); + const uint32 numSharedAttributes = mSharedVertexAttributes.size(); + clone->mSharedVertexAttributes.resize(numSharedAttributes); for (i = 0; i < numSharedAttributes; ++i) { clone->mSharedVertexAttributes[i] = mSharedVertexAttributes[i]->Clone(); } // clone the non-shared vertex attributes - const uint32 numAttributes = mVertexAttributes.GetLength(); - clone->mVertexAttributes.Resize(numAttributes); + const uint32 numAttributes = mVertexAttributes.size(); + clone->mVertexAttributes.resize(numAttributes); for (i = 0; i < numAttributes; ++i) { clone->mVertexAttributes[i] = mVertexAttributes[i]->Clone(); @@ -1105,7 +1095,7 @@ namespace EMotionFX } // swap all vertex attribute layers - const uint32 numLayers = mVertexAttributes.GetLength(); + const uint32 numLayers = mVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { mVertexAttributes[i]->SwapAttributes(vertexA, vertexB); @@ -1229,7 +1219,7 @@ namespace EMotionFX for (uint32 w = 0; w < numVertsToRemove; ++w) { // adjust all submesh start index offsets changed - for (uint32 s = 0; s < mSubMeshes.GetLength();) + for (uint32 s = 0; s < mSubMeshes.size();) { SubMesh* subMesh = mSubMeshes[s]; @@ -1249,7 +1239,7 @@ namespace EMotionFX // remove the submesh if it's empty if (subMesh->GetNumVertices() == 0 && removeEmptySubMeshes) { - mSubMeshes.Remove(s); + mSubMeshes.erase(AZStd::next(begin(mSubMeshes), s)); } else { @@ -1283,7 +1273,7 @@ namespace EMotionFX uint32 numRemoved = 0; // for all the submeshes - for (uint32 i = 0; i < mSubMeshes.GetLength();) + for (uint32 i = 0; i < mSubMeshes.size();) { SubMesh* subMesh = mSubMeshes[i]; @@ -1305,7 +1295,7 @@ namespace EMotionFX // remove or skip if (mustRemove) { - mSubMeshes.Remove(i); + mSubMeshes.erase(AZStd::next(begin(mSubMeshes), i)); numRemoved++; } else @@ -1966,7 +1956,7 @@ namespace EMotionFX void Mesh::ReserveVertexAttributeLayerSpace(uint32 numLayers) { - mVertexAttributes.Reserve(numLayers); + mVertexAttributes.reserve(numLayers); } @@ -2003,7 +1993,7 @@ namespace EMotionFX // find by name uint32 Mesh::FindVertexAttributeLayerIndexByName(const char* name) const { - const uint32 numLayers = mVertexAttributes.GetLength(); + const uint32 numLayers = mVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { if (mVertexAttributes[i]->GetNameString() == name) @@ -2019,7 +2009,7 @@ namespace EMotionFX // find by name as string uint32 Mesh::FindVertexAttributeLayerIndexByNameString(const AZStd::string& name) const { - const uint32 numLayers = mVertexAttributes.GetLength(); + const uint32 numLayers = mVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { if (mVertexAttributes[i]->GetNameString() == name) @@ -2035,7 +2025,7 @@ namespace EMotionFX // find by name ID uint32 Mesh::FindVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const uint32 numLayers = mVertexAttributes.GetLength(); + const uint32 numLayers = mVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { if (mVertexAttributes[i]->GetNameID() == nameID) @@ -2051,7 +2041,7 @@ namespace EMotionFX // find by name uint32 Mesh::FindSharedVertexAttributeLayerIndexByName(const char* name) const { - const uint32 numLayers = mSharedVertexAttributes.GetLength(); + const uint32 numLayers = mSharedVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { if (mSharedVertexAttributes[i]->GetNameString() == name) @@ -2067,7 +2057,7 @@ namespace EMotionFX // find by name as string uint32 Mesh::FindSharedVertexAttributeLayerIndexByNameString(const AZStd::string& name) const { - const uint32 numLayers = mSharedVertexAttributes.GetLength(); + const uint32 numLayers = mSharedVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { if (mSharedVertexAttributes[i]->GetNameString() == name) @@ -2083,7 +2073,7 @@ namespace EMotionFX // find by name ID uint32 Mesh::FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const uint32 numLayers = mSharedVertexAttributes.GetLength(); + const uint32 numLayers = mSharedVertexAttributes.size(); for (uint32 i = 0; i < numLayers; ++i) { if (mSharedVertexAttributes[i]->GetNameID() == nameID) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index cb929dc7db..a0a99f2961 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -18,7 +18,7 @@ #include "Transform.h" #include -#include +#include #include #include @@ -235,7 +235,7 @@ 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. @@ -257,7 +257,7 @@ 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(uint32 numSubMeshes) { mSubMeshes.resize(numSubMeshes); } /** * Remove a given submesh from this mesh. @@ -293,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. @@ -338,7 +338,7 @@ namespace EMotionFX * 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. @@ -447,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. @@ -653,7 +653,7 @@ namespace EMotionFX protected: - MCore::Array mSubMeshes; /**< The collection of sub meshes. */ + AZStd::vector 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. */ @@ -666,13 +666,13 @@ namespace EMotionFX * 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* > mSharedVertexAttributes; /** * 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* > mVertexAttributes; /** * Default constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl index 850d9d1f17..4ee52eaf19 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl @@ -24,22 +24,22 @@ MCORE_INLINE uint32 Mesh::GetNumPolygons() const } -MCORE_INLINE uint32 Mesh::GetNumSubMeshes() const +MCORE_INLINE size_t Mesh::GetNumSubMeshes() const { - return mSubMeshes.GetLength(); + return mSubMeshes.size(); } MCORE_INLINE SubMesh* Mesh::GetSubMesh(uint32 nr) const { - MCORE_ASSERT(nr < mSubMeshes.GetLength()); + MCORE_ASSERT(nr < mSubMeshes.size()); return mSubMeshes[nr]; } MCORE_INLINE void Mesh::AddSubMesh(SubMesh* subMesh) { - mSubMeshes.Add(subMesh); + mSubMeshes.emplace_back(subMesh); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp index c50aca4325..c4fae4d3bb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp @@ -22,20 +22,19 @@ namespace EMotionFX : BaseObject() { mMesh = mesh; - mDeformers.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_DEFORMERS); } // destructor MeshDeformerStack::~MeshDeformerStack() { - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); for (uint32 i = 0; i < numDeformers; ++i) { mDeformers[i]->Destroy(); } - mDeformers.Clear(); + mDeformers.clear(); // reset mMesh = nullptr; @@ -60,7 +59,7 @@ namespace EMotionFX void MeshDeformerStack::Update(ActorInstance* actorInstance, Node* node, float timeDelta, bool forceUpdateDisabledDeformers) { // if we have deformers in the stack - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); if (numDeformers > 0) { bool firstEnabled = true; @@ -92,7 +91,7 @@ namespace EMotionFX { bool resetDone = false; // if we have deformers in the stack - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); // iterate through the deformers and update them for (uint32 i = 0; i < numDeformers; ++i) { @@ -118,7 +117,7 @@ namespace EMotionFX void MeshDeformerStack::ReinitializeDeformers(Actor* actor, Node* node, uint32 lodLevel) { // if we have deformers in the stack - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); // iterate through the deformers and reinitialize them for (uint32 i = 0; i < numDeformers; ++i) @@ -131,21 +130,26 @@ namespace EMotionFX void MeshDeformerStack::AddDeformer(MeshDeformer* meshDeformer) { // add the object into the stack - mDeformers.Add(meshDeformer); + mDeformers.emplace_back(meshDeformer); } void MeshDeformerStack::InsertDeformer(uint32 pos, MeshDeformer* meshDeformer) { // add the object into the stack - mDeformers.Insert(pos, meshDeformer); + mDeformers.emplace(AZStd::next(begin(mDeformers), pos), meshDeformer); } bool MeshDeformerStack::RemoveDeformer(MeshDeformer* meshDeformer) { // delete the object - return mDeformers.RemoveByValue(meshDeformer); + if (const auto it = AZStd::find(begin(mDeformers), end(mDeformers), meshDeformer); it != end(mDeformers)) + { + mDeformers.erase(it); + return true; + } + return false; } @@ -155,7 +159,7 @@ namespace EMotionFX MeshDeformerStack* newStack = aznew MeshDeformerStack(mesh); // clone all deformers - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); for (uint32 i = 0; i < numDeformers; ++i) { newStack->AddDeformer(mDeformers[i]->Clone(mesh)); @@ -166,15 +170,15 @@ namespace EMotionFX } - uint32 MeshDeformerStack::GetNumDeformers() const + size_t MeshDeformerStack::GetNumDeformers() const { - return mDeformers.GetLength(); + return mDeformers.size(); } MeshDeformer* MeshDeformerStack::GetDeformer(uint32 nr) const { - MCORE_ASSERT(nr < mDeformers.GetLength()); + MCORE_ASSERT(nr < mDeformers.size()); return mDeformers[nr]; } @@ -183,7 +187,7 @@ namespace EMotionFX uint32 MeshDeformerStack::RemoveAllDeformersByType(uint32 deformerTypeID) { uint32 numRemoved = 0; - for (uint32 a = 0; a < mDeformers.GetLength(); ) + for (uint32 a = 0; a < mDeformers.size(); ) { MeshDeformer* deformer = mDeformers[a]; if (deformer->GetType() == deformerTypeID) @@ -205,7 +209,7 @@ namespace EMotionFX // remove all the deformers void MeshDeformerStack::RemoveAllDeformers() { - for (uint32 i = 0; i < mDeformers.GetLength(); ++i) + for (uint32 i = 0; i < mDeformers.size(); ++i) { // retrieve the current deformer MeshDeformer* deformer = mDeformers[i]; @@ -221,7 +225,7 @@ namespace EMotionFX uint32 MeshDeformerStack::EnableAllDeformersByType(uint32 deformerTypeID, bool enabled) { uint32 numChanged = 0; - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); for (uint32 a = 0; a < numDeformers; ++a) { MeshDeformer* deformer = mDeformers[a]; @@ -239,7 +243,7 @@ namespace EMotionFX // check if the stack contains a deformer of a specified type bool MeshDeformerStack::CheckIfHasDeformerOfType(uint32 deformerTypeID) const { - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); for (uint32 a = 0; a < numDeformers; ++a) { if (mDeformers[a]->GetType() == deformerTypeID) @@ -258,7 +262,7 @@ namespace EMotionFX uint32 count = 0; // for all deformers - const uint32 numDeformers = mDeformers.GetLength(); + const uint32 numDeformers = mDeformers.size(); for (uint32 a = 0; a < numDeformers; ++a) { // if this is a deformer of the type we search for diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h index 902eecf0d2..020e2b2b75 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 @@ -134,7 +134,7 @@ 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. @@ -159,7 +159,7 @@ namespace EMotionFX MeshDeformer* FindDeformerByType(uint32 deformerTypeID, uint32 occurrence = 0) const; private: - MCore::Array mDeformers; /**< The stack of deformers. */ + AZStd::vector mDeformers; /**< The stack of deformers. */ Mesh* mMesh; /**< Pointer to the mesh to which the modifier stack belongs to.*/ /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp index c609f908d1..41b1475927 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); } @@ -64,8 +63,8 @@ namespace EMotionFX MorphMeshDeformer* result = aznew MorphMeshDeformer(mesh); // copy the deform passes - result->mDeformPasses.Resize(mDeformPasses.GetLength()); - for (uint32 i = 0; i < mDeformPasses.GetLength(); ++i) + result->mDeformPasses.resize(mDeformPasses.size()); + for (uint32 i = 0; i < mDeformPasses.size(); ++i) { DeformPass& pass = result->mDeformPasses[i]; pass.mDeformDataNr = mDeformPasses[i].mDeformDataNr; @@ -89,7 +88,7 @@ namespace EMotionFX const uint32 lodLevel = actorInstance->GetLODLevel(); // apply all deform passes - const uint32 numPasses = mDeformPasses.GetLength(); + const uint32 numPasses = mDeformPasses.size(); for (uint32 i = 0; i < numPasses; ++i) { // find the morph target @@ -198,7 +197,7 @@ namespace EMotionFX void MorphMeshDeformer::Reinitialize(Actor* actor, Node* node, uint32 lodLevel) { // clear the deform passes, but don't free the currently allocated/reserved memory - mDeformPasses.Clear(false); + mDeformPasses.clear(); // get the morph setup MorphSetup* morphSetup = actor->GetMorphSetup(lodLevel); @@ -219,8 +218,8 @@ namespace EMotionFX if (deformData->mNodeIndex == node->GetNodeIndex()) { // add an empty deform pass and fill it afterwards - mDeformPasses.AddEmpty(); - const uint32 deformPassIndex = mDeformPasses.GetLength() - 1; + mDeformPasses.emplace_back(); + const uint32 deformPassIndex = mDeformPasses.size() - 1; mDeformPasses[deformPassIndex].mDeformDataNr = j; mDeformPasses[deformPassIndex].mMorphTarget = morphTarget; } @@ -231,18 +230,18 @@ namespace EMotionFX void MorphMeshDeformer::AddDeformPass(const DeformPass& deformPass) { - mDeformPasses.Add(deformPass); + mDeformPasses.emplace_back(deformPass); } - uint32 MorphMeshDeformer::GetNumDeformPasses() const + size_t MorphMeshDeformer::GetNumDeformPasses() const { - return mDeformPasses.GetLength(); + return mDeformPasses.size(); } void MorphMeshDeformer::ReserveDeformPasses(uint32 numPasses) { - mDeformPasses.Reserve(numPasses); + mDeformPasses.reserve(numPasses); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h index 6cbf4cae5b..ae56ecc96d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h @@ -122,7 +122,7 @@ 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. @@ -132,7 +132,7 @@ namespace EMotionFX void ReserveDeformPasses(uint32 numPasses); private: - MCore::Array mDeformPasses; /**< The deform passes. Each pass basically represents a morph target. */ + AZStd::vector mDeformPasses; /**< 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..386f73ae23 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,7 +35,7 @@ namespace EMotionFX // add a morph target void MorphSetup::AddMorphTarget(MorphTarget* morphTarget) { - mMorphTargets.Add(morphTarget); + mMorphTargets.emplace_back(morphTarget); } @@ -54,14 +47,18 @@ namespace EMotionFX mMorphTargets[nr]->Destroy(); } - mMorphTargets.Remove(nr); + mMorphTargets.erase(AZStd::next(begin(mMorphTargets), nr)); } // remove a morph target void MorphSetup::RemoveMorphTarget(MorphTarget* morphTarget, bool delFromMem) { - mMorphTargets.RemoveByValue(morphTarget); + const auto* foundMorphTarget = AZStd::find(begin(mMorphTargets), end(mMorphTargets), morphTarget); + if (foundMorphTarget != end(mMorphTargets)) + { + mMorphTargets.erase(foundMorphTarget); + } if (delFromMem) { @@ -73,13 +70,13 @@ namespace EMotionFX // remove all morph targets void MorphSetup::RemoveAllMorphTargets() { - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { mMorphTargets[i]->Destroy(); } - mMorphTargets.Clear(); + mMorphTargets.clear(); } @@ -87,7 +84,7 @@ namespace EMotionFX MorphTarget* MorphSetup::FindMorphTargetByID(uint32 id) const { // linear search, and check IDs - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { if (mMorphTargets[i]->GetID() == id) @@ -105,7 +102,7 @@ namespace EMotionFX uint32 MorphSetup::FindMorphTargetNumberByID(uint32 id) const { // linear search, and check IDs - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { if (mMorphTargets[i]->GetID() == id) @@ -121,7 +118,7 @@ namespace EMotionFX uint32 MorphSetup::FindMorphTargetIndexByName(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { if (mMorphTargets[i]->GetNameString() == name) @@ -136,7 +133,7 @@ namespace EMotionFX uint32 MorphSetup::FindMorphTargetIndexByNameNoCase(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { if (AzFramework::StringFunc::Equal(mMorphTargets[i]->GetNameString().c_str(), name, false /* no case */)) @@ -152,7 +149,7 @@ namespace EMotionFX // find a morph target by name (case sensitive) MorphTarget* MorphSetup::FindMorphTargetByName(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { if (mMorphTargets[i]->GetNameString() == name) @@ -168,7 +165,7 @@ namespace EMotionFX // find a morph target by name (not case sensitive) MorphTarget* MorphSetup::FindMorphTargetByNameNoCase(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { if (AzFramework::StringFunc::Equal(mMorphTargets[i]->GetNameString().c_str(), name, false /* no case */)) @@ -188,7 +185,7 @@ namespace EMotionFX MorphSetup* clone = MorphSetup::Create(); // clone all morph targets - const uint32 numMorphTargets = mMorphTargets.GetLength(); + const uint32 numMorphTargets = mMorphTargets.size(); for (uint32 i = 0; i < numMorphTargets; ++i) { clone->AddMorphTarget(mMorphTargets[i]->Clone()); @@ -201,7 +198,7 @@ namespace EMotionFX void MorphSetup::ReserveMorphTargets(uint32 numMorphTargets) { - mMorphTargets.Reserve(numMorphTargets); + mMorphTargets.reserve(numMorphTargets); } @@ -215,7 +212,7 @@ namespace EMotionFX } // scale the morph targets - const uint32 numMorphTargets = mMorphTargets.GetLength(); + const uint32 numMorphTargets = mMorphTargets.size(); for (uint32 i = 0; i < numMorphTargets; ++i) { mMorphTargets[i]->Scale(scaleFactor); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h index 6a19a0247c..c7c04ae636 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h @@ -40,7 +40,7 @@ namespace EMotionFX * 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 mMorphTargets.size(); } /** * Get a given morph target. @@ -137,12 +137,12 @@ namespace EMotionFX protected: - MCore::Array mMorphTargets; /**< The collection of morph targets. */ + AZStd::vector mMorphTargets; /**< 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..456056d00f 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); } @@ -63,7 +62,7 @@ namespace EMotionFX // allocate the number of morph targets const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); - mMorphTargets.Resize(numMorphTargets); + mMorphTargets.resize(numMorphTargets); // update the ID values for (uint32 i = 0; i < numMorphTargets; ++i) @@ -77,7 +76,7 @@ namespace EMotionFX uint32 MorphSetupInstance::FindMorphTargetIndexByID(uint32 id) const { // try to locate the morph target with the given ID - const uint32 numTargets = mMorphTargets.GetLength(); + const uint32 numTargets = mMorphTargets.size(); for (uint32 i = 0; i < numTargets; ++i) { if (mMorphTargets[i].GetID() == id) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h index 7cc0c0dbd0..e597cb7a63 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 @@ -123,7 +123,7 @@ 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 mMorphTargets.size(); } /** * Get a specific morph target. @@ -149,7 +149,7 @@ namespace EMotionFX MorphTarget* FindMorphTargetByID(uint32 id); private: - MCore::Array mMorphTargets; /**< The unique morph target information. */ + AZStd::vector mMorphTargets; /**< 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..3bb84881ff 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 @@ -31,12 +32,6 @@ namespace EMotionFX } - // destructor - MorphTarget::~MorphTarget() - { - } - - // convert the given phoneme name to a phoneme set MorphTarget::EPhonemeSet MorphTarget::FindPhonemeSet(const AZStd::string& phonemeName) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h index 726f7d81bc..829d6f5be6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h @@ -286,10 +286,5 @@ namespace EMotionFX * @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..d1c23ba04d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp @@ -177,7 +177,7 @@ namespace EMotionFX 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(); + const uint32 numTransforms = mTransforms.size(); for (uint32 i = 0; i < numTransforms; ++i) { // if this is the node that gets modified by this transform @@ -214,7 +214,7 @@ namespace EMotionFX } // check all transforms - const uint32 numTransforms = mTransforms.GetLength(); + const uint32 numTransforms = mTransforms.size(); for (uint32 i = 0; i < numTransforms; ++i) { if (mTransforms[i].mNodeIndex == nodeIndex) @@ -239,7 +239,7 @@ namespace EMotionFX Transform newTransform; // calculate the new transformations for all nodes of this morph target - const uint32 numTransforms = mTransforms.GetLength(); + const uint32 numTransforms = mTransforms.size(); for (uint32 i = 0; i < numTransforms; ++i) { // try to find the node @@ -277,9 +277,9 @@ namespace EMotionFX } } - uint32 MorphTargetStandard::GetNumDeformDatas() const + size_t MorphTargetStandard::GetNumDeformDatas() const { - return static_cast(mDeformDatas.size()); + return mDeformDatas.size(); } MorphTargetStandard::DeformData* MorphTargetStandard::GetDeformData(uint32 nr) const @@ -294,12 +294,13 @@ namespace EMotionFX void MorphTargetStandard::AddTransformation(const Transformation& transform) { - mTransforms.Add(transform); + mTransforms.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 mTransforms.size(); } MorphTargetStandard::Transformation& MorphTargetStandard::GetTransformation(uint32 nr) @@ -321,7 +322,7 @@ namespace EMotionFX // now clone the deform datas clone->mDeformDatas.resize(mDeformDatas.size()); - for (size_t i = 0; i < mDeformDatas.size(); ++i) + for (uint32 i = 0; i < mDeformDatas.size(); ++i) { clone->mDeformDatas[i] = mDeformDatas[i]->Clone(); } @@ -404,7 +405,7 @@ namespace EMotionFX // pre-allocate memory for the transformations void MorphTargetStandard::ReserveTransformations(uint32 numTransforms) { - mTransforms.Reserve(numTransforms); + mTransforms.reserve(numTransforms); } void MorphTargetStandard::RemoveDeformData(uint32 index, bool delFromMem) @@ -419,7 +420,7 @@ namespace EMotionFX void MorphTargetStandard::RemoveTransformation(uint32 index) { - mTransforms.Remove(index); + mTransforms.erase(AZStd::next(begin(mTransforms), index)); } @@ -433,7 +434,7 @@ namespace EMotionFX } // scale the transformations - const uint32 numTransformations = mTransforms.GetLength(); + const uint32 numTransformations = mTransforms.size(); for (uint32 i = 0; i < numTransformations; ++i) { Transformation& transform = mTransforms[i]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h index 2d8a20ec11..cda878efbb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h @@ -175,7 +175,7 @@ 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. @@ -200,7 +200,7 @@ 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. @@ -260,7 +260,7 @@ 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 mTransforms; /**< The relative transformations for the given nodes, in local space. The rotation however is absolute. */ AZStd::vector mDeformDatas; /**< The deformation data objects. */ /** 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..292aef9d54 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp @@ -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,7 +829,7 @@ 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 (int32 i = hierarchyPath.size() - 1; i >= 0; --i) { // get the current node index const AZ::u32 nodeIndex = hierarchyPath[i]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h index 5c7ed822e3..d0f2d1d3fb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h @@ -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."); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp index 0277843cf9..f2abc5f5de 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp @@ -42,8 +42,6 @@ namespace EMotionFX // constructor MotionInstancePool::Pool::Pool() { - mFreeList.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL); - mSubPools.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL); mPoolType = POOLTYPE_DYNAMIC; mData = nullptr; mNumInstances = 0; @@ -59,7 +57,7 @@ namespace EMotionFX { MCore::Free(mData); mData = nullptr; - mFreeList.Clear(); + mFreeList.clear(); } else if (mPoolType == POOLTYPE_DYNAMIC) @@ -67,14 +65,14 @@ namespace EMotionFX MCORE_ASSERT(mData == nullptr); // delete all subpools - const uint32 numSubPools = mSubPools.GetLength(); + const uint32 numSubPools = mSubPools.size(); for (uint32 s = 0; s < numSubPools; ++s) { delete mSubPools[s]; } - mSubPools.Clear(); + mSubPools.clear(); - mFreeList.Clear(); + mFreeList.clear(); } else { @@ -142,7 +140,7 @@ namespace EMotionFX if (poolType == POOLTYPE_STATIC) { mPool->mData = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space - mPool->mFreeList.ResizeFast(numInitialInstances); + mPool->mFreeList.resize_no_construct(numInitialInstances); for (uint32 i = 0; i < numInitialInstances; ++i) { void* memLocation = (void*)(mPool->mData + i * sizeof(MotionInstance)); @@ -153,20 +151,20 @@ namespace EMotionFX else // if we have a dynamic pool if (poolType == POOLTYPE_DYNAMIC) { - mPool->mSubPools.Reserve(32); + mPool->mSubPools.reserve(32); SubPool* subPool = new SubPool(); subPool->mData = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space subPool->mNumInstances = numInitialInstances; - mPool->mFreeList.ResizeFast(numInitialInstances); + mPool->mFreeList.resize_no_construct(numInitialInstances); for (uint32 i = 0; i < numInitialInstances; ++i) { mPool->mFreeList[i].mAddress = (void*)(subPool->mData + i * sizeof(MotionInstance)); mPool->mFreeList[i].mSubPool = subPool; } - mPool->mSubPools.Add(subPool); + mPool->mSubPools.emplace_back(subPool); } else { @@ -186,9 +184,9 @@ namespace EMotionFX } // if there is are free items left - if (mPool->mFreeList.GetLength() > 0) + if (mPool->mFreeList.size() > 0) { - const MemLocation& location = mPool->mFreeList.GetLast(); + const MemLocation& location = mPool->mFreeList.back(); MotionInstance* result = MotionInstance::Create(location.mAddress, motion, actorInstance); if (location.mSubPool) @@ -197,7 +195,7 @@ namespace EMotionFX } result->SetSubPool(location.mSubPool); - mPool->mFreeList.RemoveLast(); // remove it from the free list + mPool->mFreeList.pop_back(); // remove it from the free list mPool->mNumUsedInstances++; return result; } @@ -212,14 +210,14 @@ namespace EMotionFX subPool->mData = (uint8*)MCore::Allocate(numInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space subPool->mNumInstances = numInstances; - const uint32 startIndex = mPool->mFreeList.GetLength(); + const uint32 startIndex = mPool->mFreeList.size(); //mPool->mFreeList.Reserve( numInstances * 2 ); - if (mPool->mFreeList.GetMaxLength() < mPool->mNumInstances) + if (mPool->mFreeList.capacity() < mPool->mNumInstances) { - mPool->mFreeList.Reserve(mPool->mNumInstances + mPool->mFreeList.GetMaxLength() / 2); + mPool->mFreeList.reserve(mPool->mNumInstances + mPool->mFreeList.capacity() / 2); } - mPool->mFreeList.ResizeFast(startIndex + numInstances); + mPool->mFreeList.resize_no_construct(startIndex + numInstances); for (uint32 i = 0; i < numInstances; ++i) { void* memAddress = (void*)(subPool->mData + i * sizeof(MotionInstance)); @@ -227,16 +225,16 @@ namespace EMotionFX mPool->mFreeList[i + startIndex].mSubPool = subPool; } - mPool->mSubPools.Add(subPool); + mPool->mSubPools.emplace_back(subPool); - const MemLocation& location = mPool->mFreeList.GetLast(); + const MemLocation& location = mPool->mFreeList.back(); MotionInstance* result = MotionInstance::Create(location.mAddress, motion, actorInstance); if (location.mSubPool) { location.mSubPool->mNumInUse++; } result->SetSubPool(location.mSubPool); - mPool->mFreeList.RemoveLast(); // remove it from the free list + mPool->mFreeList.pop_back(); // remove it from the free list mPool->mNumUsedInstances++; return result; } @@ -276,9 +274,9 @@ namespace EMotionFX motionInstance->GetSubPool()->mNumInUse--; } - mPool->mFreeList.AddEmpty(); - mPool->mFreeList.GetLast().mAddress = motionInstance; - mPool->mFreeList.GetLast().mSubPool = motionInstance->GetSubPool(); + mPool->mFreeList.emplace_back(); + mPool->mFreeList.back().mAddress = motionInstance; + mPool->mFreeList.back().mSubPool = motionInstance->GetSubPool(); mPool->mNumUsedInstances--; motionInstance->DecreaseReferenceCount(); @@ -292,7 +290,7 @@ namespace EMotionFX Lock(); MCore::LogInfo("EMotionFX::MotionInstancePool::LogMemoryStats() - Logging motion instance pool info"); - const uint32 numFree = mPool->mFreeList.GetLength(); + const uint32 numFree = mPool->mFreeList.size(); uint32 numUsed = mPool->mNumUsedInstances; uint32 memUsage = 0; uint32 usedMemUsage = 0; @@ -320,12 +318,12 @@ namespace EMotionFX totalUsedInstancesMemUsage += usedMemUsage; totalMemUsage += memUsage; totalMemUsage += sizeof(Pool); - totalMemUsage += mPool->mFreeList.CalcMemoryUsage(false); + totalMemUsage += mPool->mFreeList.capacity() * sizeof(decltype(mPool->mFreeList)::value_type); MCore::LogInfo("Pool:"); if (mPool->mPoolType == POOLTYPE_DYNAMIC) { - MCore::LogInfo(" - Num SubPools: %d", mPool->mSubPools.GetLength()); + MCore::LogInfo(" - Num SubPools: %d", mPool->mSubPools.size()); } MCore::LogInfo(" - Num Instances: %d", mPool->mNumInstances); MCore::LogInfo(" - Num Free: %d", numFree); @@ -377,17 +375,17 @@ namespace EMotionFX { Lock(); - for (uint32 i = 0; i < mPool->mSubPools.GetLength(); ) + for (uint32 i = 0; i < mPool->mSubPools.size(); ) { SubPool* subPool = mPool->mSubPools[i]; if (subPool->mNumInUse == 0) { // remove all free allocations - for (uint32 a = 0; a < mPool->mFreeList.GetLength(); ) + for (uint32 a = 0; a < mPool->mFreeList.size(); ) { if (mPool->mFreeList[a].mSubPool == subPool) { - mPool->mFreeList.Remove(a); + mPool->mFreeList.erase(AZStd::next(begin(mPool->mFreeList), a)); } else { @@ -396,7 +394,7 @@ namespace EMotionFX } mPool->mNumInstances -= subPool->mNumInstances; - mPool->mSubPools.Remove(i); + mPool->mSubPools.erase(AZStd::next(begin(mPool->mSubPools), i)); delete subPool; } else @@ -405,11 +403,11 @@ namespace EMotionFX } } - mPool->mSubPools.Shrink(); + mPool->mSubPools.shrink_to_fit(); //mPool->mFreeList.Shrink(); - if ((mPool->mFreeList.GetMaxLength() - mPool->mFreeList.GetLength()) > 4096) + if ((mPool->mFreeList.capacity() - mPool->mFreeList.size()) > 4096) { - mPool->mFreeList.ReserveExact(mPool->mFreeList.GetLength() + 4096); + mPool->mFreeList.reserve(mPool->mFreeList.size() + 4096); } Unlock(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h index 0fd658915e..8cb675bb08 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 @@ -91,8 +91,8 @@ namespace EMotionFX uint32 mNumInstances; uint32 mNumUsedInstances; uint32 mSubPoolSize; - MCore::Array mFreeList; - MCore::Array mSubPools; + AZStd::vector mFreeList; + AZStd::vector mSubPools; EPoolType mPoolType; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp index 14e6b582b4..9cda792890 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp @@ -22,8 +22,6 @@ 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); } @@ -50,7 +48,7 @@ namespace EMotionFX void MotionLayerSystem::RemoveAllLayerPasses(bool delFromMem) { // delete all layer passes - const uint32 numLayerPasses = mLayerPasses.GetLength(); + const uint32 numLayerPasses = mLayerPasses.size(); for (uint32 i = 0; i < numLayerPasses; ++i) { if (delFromMem) @@ -59,7 +57,7 @@ namespace EMotionFX } } - mLayerPasses.Clear(); + mLayerPasses.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 uint32 numMotionInstances = mMotionInstances.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) { - mMotionInstances.Insert(insertPos, motion); + mMotionInstances.emplace(AZStd::next(begin(mMotionInstances), insertPos), motion); } else { - mMotionInstances.Add(motion); + mMotionInstances.emplace_back(motion); } } else // no motions are playing, so just add it { - mMotionInstances.Add(motion); + mMotionInstances.emplace_back(motion); } // trigger an event @@ -101,7 +99,7 @@ namespace EMotionFX // find the location where to insert a new motion with a given priority uint32 MotionLayerSystem::FindInsertPos(uint32 priorityLevel) const { - const uint32 numInstances = mMotionInstances.GetLength(); + const uint32 numInstances = mMotionInstances.size(); for (uint32 i = 0; i < numInstances; ++i) { if (mMotionInstances[i]->GetPriorityLevel() <= priorityLevel) @@ -127,7 +125,7 @@ namespace EMotionFX mMotionQueue->Update(); // process all layer passes - const uint32 numPasses = mLayerPasses.GetLength(); + const uint32 numPasses = mLayerPasses.size(); for (uint32 i = 0; i < numPasses; ++i) { mLayerPasses[i]->Process(); @@ -153,7 +151,7 @@ namespace EMotionFX // update the motion tree void MotionLayerSystem::UpdateMotionTree() { - for (uint32 i = 0; i < mMotionInstances.GetLength(); ++i) + for (uint32 i = 0; i < mMotionInstances.size(); ++i) { MotionInstance* source = mMotionInstances[i]; @@ -235,7 +233,7 @@ namespace EMotionFX if (source->GetCanOverwrite()) { // remove all motions that got overwritten by the current one - const uint32 numToRemove = mMotionInstances.GetLength() - (i + 1); + const uint32 numToRemove = mMotionInstances.size() - (i + 1); for (uint32 a = 0; a < numToRemove; ++a) { RemoveMotionInstance(mMotionInstances[i + 1]); @@ -253,7 +251,7 @@ namespace EMotionFX uint32 numRemoved = 0; // start from the bottom up - for (uint32 i = mMotionInstances.GetLength() - 1; i != MCORE_INVALIDINDEX32;) + for (uint32 i = mMotionInstances.size() - 1; i != MCORE_INVALIDINDEX32;) { MotionInstance* curInstance = mMotionInstances[i]; @@ -276,7 +274,7 @@ namespace EMotionFX MotionInstance* MotionLayerSystem::FindFirstNonMixingMotionInstance() const { // if there aren't any motion instances, return nullptr - const uint32 numInstances = mMotionInstances.GetLength(); + const uint32 numInstances = mMotionInstances.size(); if (numInstances == 0) { return nullptr; @@ -306,7 +304,7 @@ namespace EMotionFX Pose* tempActorPose = &tempAnimGraphPose->GetPose(); - const uint32 numMotionInstances = mMotionInstances.GetLength(); + const uint32 numMotionInstances = mMotionInstances.size(); if (numMotionInstances > 0) { if (numMotionInstances > 1) @@ -396,14 +394,14 @@ namespace EMotionFX // add a new pass void MotionLayerSystem::AddLayerPass(LayerPass* newPass) { - mLayerPasses.Add(newPass); + mLayerPasses.emplace_back(newPass); } // get the number of layer passes - uint32 MotionLayerSystem::GetNumLayerPasses() const + size_t MotionLayerSystem::GetNumLayerPasses() const { - return mLayerPasses.GetLength(); + return mLayerPasses.size(); } @@ -415,14 +413,17 @@ namespace EMotionFX mLayerPasses[nr]->Destroy(); } - mLayerPasses.Remove(nr); + mLayerPasses.erase(AZStd::next(begin(mLayerPasses), nr)); } // remove a given pass void MotionLayerSystem::RemoveLayerPass(LayerPass* pass, bool delFromMem) { - mLayerPasses.RemoveByValue(pass); + if (const auto it = AZStd::find(begin(mLayerPasses), end(mLayerPasses), pass); it != end(mLayerPasses)) + { + mLayerPasses.erase(it); + } if (delFromMem) { @@ -434,7 +435,7 @@ namespace EMotionFX // insert a layer pass at a given position void MotionLayerSystem::InsertLayerPass(uint32 insertPos, LayerPass* pass) { - mLayerPasses.Insert(insertPos, pass); + mLayerPasses.emplace(AZStd::next(begin(mLayerPasses), insertPos), pass); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h index ff4761d49c..e207f48fd5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h @@ -140,7 +140,7 @@ 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. @@ -179,7 +179,7 @@ namespace EMotionFX private: - MCore::Array mLayerPasses; /**< The layer passes. */ + AZStd::vector mLayerPasses; /**< The layer passes. */ RepositioningLayerPass* mRepositioningPass; /**< The motion based actor repositioning layer pass. */ /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp index 13ac1956fa..b193c58175 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); + mMotions.reserve(400); m_motionDataFactory = aznew MotionDataFactory(); } @@ -69,13 +66,13 @@ namespace EMotionFX if (delFromMemory) { // destroy all motion sets, they will internally call RemoveMotionSetWithoutLock(this) in their destructor - while (mMotionSets.GetLength() > 0) + while (mMotionSets.size() > 0) { delete mMotionSets[0]; } // destroy all motions, they will internally call RemoveMotionWithoutLock(this) in their destructor - while (mMotions.GetLength() > 0) + while (mMotions.size() > 0) { mMotions[0]->Destroy(); } @@ -84,12 +81,12 @@ namespace EMotionFX { // wait with execution until we can set the lock mSetLock.Lock(); - mMotionSets.Clear(); + mMotionSets.clear(); mSetLock.Unlock(); // clear the arrays without destroying the memory of the entries mLock.Lock(); - mMotions.Clear(); + mMotions.clear(); mLock.Unlock(); } } @@ -99,7 +96,7 @@ namespace EMotionFX Motion* MotionManager::FindMotionByName(const char* motionName, bool isTool) const { // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); + const uint32 numMotions = mMotions.size(); for (uint32 i = 0; i < numMotions; ++i) { if (mMotions[i]->GetIsOwnedByRuntime() == isTool) @@ -122,7 +119,7 @@ namespace EMotionFX Motion* MotionManager::FindMotionByFileName(const char* fileName, bool isTool) const { // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); + const uint32 numMotions = mMotions.size(); for (uint32 i = 0; i < numMotions; ++i) { if (mMotions[i]->GetIsOwnedByRuntime() == isTool) @@ -145,7 +142,7 @@ namespace EMotionFX MotionSet* MotionManager::FindMotionSetByFileName(const char* fileName, bool isTool) const { // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { MotionSet* motionSet = mMotionSets[i]; @@ -169,7 +166,7 @@ namespace EMotionFX MotionSet* MotionManager::FindMotionSetByName(const char* name, bool isOwnedByRuntime) const { // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { MotionSet* motionSet = mMotionSets[i]; @@ -192,7 +189,7 @@ namespace EMotionFX uint32 MotionManager::FindMotionIndexByName(const char* motionName, bool isTool) const { // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); + const uint32 numMotions = mMotions.size(); for (uint32 i = 0; i < numMotions; ++i) { if (mMotions[i]->GetIsOwnedByRuntime() == isTool) @@ -215,7 +212,7 @@ namespace EMotionFX uint32 MotionManager::FindMotionSetIndexByName(const char* name, bool isTool) const { // get the number of motions and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { MotionSet* motionSet = mMotionSets[i]; @@ -240,7 +237,7 @@ namespace EMotionFX uint32 MotionManager::FindMotionIndexByID(uint32 id) const { // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); + const uint32 numMotions = mMotions.size(); for (uint32 i = 0; i < numMotions; ++i) { if (mMotions[i]->GetID() == id) @@ -257,7 +254,7 @@ namespace EMotionFX uint32 MotionManager::FindMotionSetIndexByID(uint32 id) const { // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { // compare the motion names @@ -275,7 +272,7 @@ namespace EMotionFX Motion* MotionManager::FindMotionByID(uint32 id) const { // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); + const uint32 numMotions = mMotions.size(); for (uint32 i = 0; i < numMotions; ++i) { if (mMotions[i]->GetID() == id) @@ -292,7 +289,7 @@ namespace EMotionFX MotionSet* MotionManager::FindMotionSetByID(uint32 id) const { // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { if (mMotionSets[i]->GetID() == id) @@ -309,7 +306,7 @@ namespace EMotionFX uint32 MotionManager::FindMotionSetIndex(MotionSet* motionSet) const { // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { if (mMotionSets[i] == motionSet) @@ -326,7 +323,7 @@ namespace EMotionFX uint32 MotionManager::FindMotionIndex(Motion* motion) const { // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); + const uint32 numMotions = mMotions.size(); for (uint32 i = 0; i < numMotions; ++i) { // compare the motions @@ -345,7 +342,7 @@ namespace EMotionFX { // wait with execution until we can set the lock mLock.Lock(); - mMotions.Add(motion); + mMotions.emplace_back(motion); mLock.Unlock(); } @@ -386,7 +383,7 @@ namespace EMotionFX uint32 MotionManager::FindMotionIndexByFileName(const char* fileName, bool isTool) const { // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); + const uint32 numMotions = mMotions.size(); for (uint32 i = 0; i < numMotions; ++i) { if (mMotions[i]->GetIsOwnedByRuntime() == isTool) @@ -494,7 +491,7 @@ namespace EMotionFX } // Reset all motion entries in the motion sets of the current motion. - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (i = 0; i < numMotionSets; ++i) { MotionSet* motionSet = mMotionSets[i]; @@ -525,11 +522,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 + mMotions.erase(AZStd::next(begin(mMotions), 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 + mMotions.erase(AZStd::next(begin(mMotions), index)); // only remove the motion from the motion manager without destroying its memory } return true; @@ -540,7 +537,7 @@ namespace EMotionFX void MotionManager::AddMotionSet(MotionSet* motionSet) { MCore::LockGuard lock(mLock); - mMotionSets.Add(motionSet); + mMotionSets.emplace_back(motionSet); } @@ -578,7 +575,7 @@ namespace EMotionFX delete motionSet; } - mMotionSets.Remove(index); + mMotionSets.erase(AZStd::next(begin(mMotionSets), index)); return true; } @@ -606,7 +603,7 @@ namespace EMotionFX uint32 result = 0; // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { // sum up the root motion sets @@ -626,7 +623,7 @@ namespace EMotionFX uint32 currentIndex = 0; // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); + const uint32 numMotionSets = mMotionSets.size(); for (uint32 i = 0; i < numMotionSets; ++i) { // get the current motion set diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h index 78d8b0eaa7..98555da9f7 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 @@ -50,7 +50,7 @@ namespace EMotionFX * 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 mMotions.size(); } /** * Remove the motion with the given name from the motion manager. @@ -160,7 +160,7 @@ namespace EMotionFX * 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 mMotionSets.size(); } /** * Calculate the number of root motion sets. @@ -233,8 +233,8 @@ namespace EMotionFX const MotionDataFactory& GetMotionDataFactory() const; private: - MCore::Array mMotions; /**< The array of motions. */ - MCore::Array mMotionSets; /**< The array of motion sets. */ + AZStd::vector mMotions; /**< The array of motions. */ + AZStd::vector mMotionSets; /**< The array of motion sets. */ MCore::Mutex mLock; /**< Motion lock. */ MCore::Mutex mSetLock; /**< The motion set multithread lock. */ MotionDataFactory* m_motionDataFactory = nullptr; /**< The motion data factory. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp index d3a76f7967..ea8826fe9a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp @@ -26,7 +26,6 @@ namespace EMotionFX { MCORE_ASSERT(actorInstance && motionSystem); - mEntries.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MISC); mActorInstance = actorInstance; mMotionSystem = motionSystem; } @@ -54,7 +53,7 @@ namespace EMotionFX GetMotionInstancePool().Free(mEntries[nr].mMotion); } - mEntries.Remove(nr); + mEntries.erase(AZStd::next(begin(mEntries), nr)); } @@ -168,7 +167,7 @@ namespace EMotionFX void MotionQueue::ClearAllEntries() { - while (mEntries.GetLength()) + while (mEntries.size()) { RemoveEntry(0); } @@ -177,26 +176,26 @@ namespace EMotionFX void MotionQueue::AddEntry(const MotionQueue::QueueEntry& motion) { - mEntries.Add(motion); + mEntries.emplace_back(motion); } - uint32 MotionQueue::GetNumEntries() const + size_t MotionQueue::GetNumEntries() const { - return mEntries.GetLength(); + return mEntries.size(); } MotionQueue::QueueEntry& MotionQueue::GetFirstEntry() { - MCORE_ASSERT(mEntries.GetLength() > 0); + MCORE_ASSERT(mEntries.size() > 0); return mEntries[0]; } void MotionQueue::RemoveFirstEntry() { - mEntries.RemoveFirst(); + mEntries.erase(mEntries.begin()); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h index 5480f5c40d..9978a16bc6 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 @@ -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. @@ -133,7 +133,7 @@ namespace EMotionFX void PlayNextMotion(); private: - MCore::Array mEntries; /**< The motion queue entries. */ + AZStd::vector mEntries; /**< The motion queue entries. */ MotionSystem* mMotionSystem; /**< Motion system access pointer. */ ActorInstance* mActorInstance; /**< The actor instance where this queue works on. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp index 364ad28d3d..fcd243c95f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp @@ -29,7 +29,6 @@ namespace EMotionFX { MCORE_ASSERT(actorInstance); - mMotionInstances.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MOTIONSYSTEMS); mActorInstance = actorInstance; mMotionQueue = nullptr; @@ -46,11 +45,11 @@ namespace EMotionFX GetEventManager().OnDeleteMotionSystem(this); // delete the motion infos - while (mMotionInstances.GetLength()) + while (mMotionInstances.size()) { //delete mMotionInstances.GetLast(); - GetMotionInstancePool().Free(mMotionInstances.GetLast()); - mMotionInstances.RemoveLast(); + GetMotionInstancePool().Free(mMotionInstances.back()); + mMotionInstances.pop_back(); } // get rid of the motion queue @@ -138,7 +137,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(mMotionInstances), end(mMotionInstances), instance); it != end(mMotionInstances)) + { + mMotionInstances.erase(it); + return true; + } + return false; + }(); // delete the motion instance from memory if (isSuccess) @@ -167,7 +173,7 @@ namespace EMotionFX // stop all the motions that are currently playing void MotionSystem::StopAllMotions() { - const uint32 numInstances = mMotionInstances.GetLength(); + const uint32 numInstances = mMotionInstances.size(); for (uint32 i = 0; i < numInstances; ++i) { mMotionInstances[i]->Stop(); @@ -178,7 +184,7 @@ namespace EMotionFX // stop all motion instances of a given motion void MotionSystem::StopAllMotions(Motion* motion) { - const uint32 numInstances = mMotionInstances.GetLength(); + const uint32 numInstances = mMotionInstances.size(); for (uint32 i = 0; i < numInstances; ++i) { if (mMotionInstances[i]->GetMotion()->GetID() == motion->GetID()) @@ -190,16 +196,16 @@ namespace EMotionFX // 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 < mMotionInstances.size()); if (deleteMem) { GetEMotionFX().GetMotionInstancePool()->Free(mMotionInstances[nr]); } - mMotionInstances.Remove(nr); + mMotionInstances.erase(AZStd::next(begin(mMotionInstances), nr)); } @@ -208,15 +214,15 @@ namespace EMotionFX { MCORE_ASSERT(motion); - uint32 nr = mMotionInstances.Find(motion); - MCORE_ASSERT(nr != MCORE_INVALIDINDEX32); + const auto it = AZStd::find(begin(mMotionInstances), end(mMotionInstances), motion); + MCORE_ASSERT(it != end(mMotionInstances)); - if (nr == MCORE_INVALIDINDEX32) + if (it == end(mMotionInstances)) { return; } - RemoveMotion(nr, delMem); + RemoveMotion(AZStd::distance(begin(mMotionInstances), it), delMem); } @@ -224,7 +230,7 @@ namespace EMotionFX void MotionSystem::UpdateMotionInstances(float timePassed) { // update all the motion infos - const uint32 numInstances = mMotionInstances.GetLength(); + const uint32 numInstances = mMotionInstances.size(); for (uint32 i = 0; i < numInstances; ++i) { mMotionInstances[i]->Update(timePassed); @@ -242,7 +248,7 @@ namespace EMotionFX } // for all motion instances currently playing in this actor - const uint32 numInstances = mMotionInstances.GetLength(); + const uint32 numInstances = mMotionInstances.size(); 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 @@ -269,7 +275,7 @@ namespace EMotionFX } // for all motion instances currently playing in this actor - const uint32 numInstances = mMotionInstances.GetLength(); + const uint32 numInstances = mMotionInstances.size(); for (uint32 i = 0; i < numInstances; ++i) { const MotionInstance* motionInstance = mMotionInstances[i]; @@ -294,15 +300,15 @@ namespace EMotionFX // return given motion instance MotionInstance* MotionSystem::GetMotionInstance(uint32 nr) const { - MCORE_ASSERT(nr < mMotionInstances.GetLength()); + MCORE_ASSERT(nr < mMotionInstances.size()); return mMotionInstances[nr]; } // return number of motion instances - uint32 MotionSystem::GetNumMotionInstances() const + size_t MotionSystem::GetNumMotionInstances() const { - return mMotionInstances.GetLength(); + return mMotionInstances.size(); } @@ -350,12 +356,12 @@ namespace EMotionFX void MotionSystem::AddMotionInstance(MotionInstance* instance) { - mMotionInstances.Add(instance); + mMotionInstances.emplace_back(instance); } bool MotionSystem::GetIsPlaying() const { - return (mMotionInstances.GetLength() > 0); + return (mMotionInstances.size() > 0); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h index c0cbb779df..dd7ba26170 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. @@ -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,7 +215,7 @@ namespace EMotionFX protected: - MCore::Array mMotionInstances; /**< The collection of motion instances. */ + AZStd::vector mMotionInstances; /**< The collection of motion instances. */ ActorInstance* mActorInstance; /**< The actor instance where this motion system belongs to. */ MotionQueue* mMotionQueue; /**< The motion queue. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp index 9af9ddf71f..bd339ecb36 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); + mSteps.reserve(1000); } @@ -53,7 +52,7 @@ namespace EMotionFX void MultiThreadScheduler::Clear() { Lock(); - mSteps.Clear(); + mSteps.clear(); Unlock(); } @@ -79,7 +78,7 @@ namespace EMotionFX void MultiThreadScheduler::Print() { // for all steps - const uint32 numSteps = mSteps.GetLength(); + const uint32 numSteps = mSteps.size(); for (uint32 i = 0; i < numSteps; ++i) { AZ_Printf("EMotionFX", "STEP %.3d - %d", i, mSteps[i].mActorInstances.size()); @@ -92,7 +91,7 @@ namespace EMotionFX void MultiThreadScheduler::RemoveEmptySteps() { // process all steps - for (uint32 s = 0; s < mSteps.GetLength(); ) + for (uint32 s = 0; s < mSteps.size(); ) { // if the step isn't empty if (mSteps[s].mActorInstances.size() > 0) @@ -101,7 +100,7 @@ namespace EMotionFX } else // otherwise remove it { - mSteps.Remove(s); + mSteps.erase(AZStd::next(begin(mSteps), s)); } } } @@ -112,7 +111,7 @@ namespace EMotionFX { MCore::LockGuardRecursive guard(mMutex); - uint32 numSteps = mSteps.GetLength(); + uint32 numSteps = mSteps.size(); if (numSteps == 0) { return; @@ -124,7 +123,7 @@ namespace EMotionFX { mCleanTimer = 0.0f; RemoveEmptySteps(); - numSteps = mSteps.GetLength(); + numSteps = mSteps.size(); } //----------------------------------------------------------- @@ -216,7 +215,7 @@ namespace EMotionFX bool MultiThreadScheduler::FindNextFreeItem(ActorInstance* actorInstance, uint32 startStep, uint32* outStepNr) { // try out all steps - const uint32 numSteps = mSteps.GetLength(); + const uint32 numSteps = mSteps.size(); for (uint32 s = startStep; s < numSteps; ++s) { // if there is a conflicting dependency, skip this step @@ -236,7 +235,7 @@ namespace EMotionFX bool MultiThreadScheduler::HasActorInstanceInSteps(const ActorInstance* actorInstance) const { - const uint32 numSteps = mSteps.GetLength(); + const uint32 numSteps = mSteps.size(); for (uint32 s = 0; s < numSteps; ++s) { const ScheduleStep& step = mSteps[s]; @@ -258,9 +257,9 @@ namespace EMotionFX uint32 outStep = startStep; if (!FindNextFreeItem(instance, startStep, &outStep)) { - mSteps.Reserve(10); - mSteps.AddEmpty(); - outStep = mSteps.GetLength() - 1; + mSteps.reserve(10); + mSteps.emplace_back(); + outStep = mSteps.size() - 1; } // pre-allocate step size @@ -269,9 +268,9 @@ namespace EMotionFX mSteps[outStep].mActorInstances.reserve(mSteps[outStep].mActorInstances.size() + 10); } - if (mSteps[outStep].mDependencies.GetLength() % 5 == 0) + if (mSteps[outStep].mDependencies.size() % 5 == 0) { - mSteps[outStep].mDependencies.Reserve(mSteps[outStep].mDependencies.GetLength() + 5); + mSteps[outStep].mDependencies.reserve(mSteps[outStep].mDependencies.size() + 5); } // add the actor instance and its dependencies @@ -298,7 +297,7 @@ namespace EMotionFX MCore::LockGuardRecursive guard(mMutex); // for all scheduler steps, starting from the specified start step number - const uint32 numSteps = mSteps.GetLength(); + const uint32 numSteps = mSteps.size(); for (uint32 s = startStep; s < numSteps; ++s) { ScheduleStep& step = mSteps[s]; @@ -312,7 +311,7 @@ namespace EMotionFX if (step.mActorInstances.size() < numActorInstancesPreRemove) { // clear the dependencies (but don't delete the memory) - step.mDependencies.Clear(false); + step.mDependencies.clear(); // calculate the new dependencies for this step for (ActorInstance* stepActorInstance : step.mActorInstances) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h index 75a5a6519a..4deebae866 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 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); - } }; /** @@ -128,10 +120,10 @@ namespace EMotionFX void Unlock(); const ScheduleStep& GetScheduleStep(uint32 index) const { return mSteps[index]; } - uint32 GetNumScheduleSteps() const { return mSteps.GetLength(); } + size_t GetNumScheduleSteps() const { return mSteps.size(); } protected: - MCore::Array< ScheduleStep > mSteps; /**< An array of update steps, that together form the schedule. */ + AZStd::vector< 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp index 8ab7fa540d..a712ffe337 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp @@ -20,10 +20,6 @@ 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 @@ -45,10 +41,6 @@ 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 @@ -167,8 +159,8 @@ namespace EMotionFX result->mSemanticNameID = mSemanticNameID; // copy the node attributes - result->mAttributes.Reserve(mAttributes.GetLength()); - for (uint32 i = 0; i < mAttributes.GetLength(); i++) + result->mAttributes.reserve(mAttributes.size()); + for (uint32 i = 0; i < mAttributes.size(); i++) { result->AddAttribute(mAttributes[i]->Clone()); } @@ -181,10 +173,10 @@ namespace EMotionFX // removes all attributes void Node::RemoveAllAttributes() { - while (mAttributes.GetLength()) + while (mAttributes.size()) { - mAttributes.GetLast()->Destroy(); - mAttributes.RemoveLast(); + mAttributes.back()->Destroy(); + mAttributes.pop_back(); } } @@ -213,7 +205,7 @@ namespace EMotionFX numNodes++; // recurse down the hierarchy - const uint32 numChildNodes = mChildIndices.GetLength(); + const uint32 numChildNodes = mChildIndices.size(); for (uint32 i = 0; i < numChildNodes; ++i) { mSkeleton->GetNode(mChildIndices[i])->RecursiveCountChildNodes(numNodes); @@ -405,20 +397,20 @@ namespace EMotionFX void Node::AddAttribute(NodeAttribute* attribute) { - mAttributes.Add(attribute); + mAttributes.emplace_back(attribute); } - uint32 Node::GetNumAttributes() const + size_t Node::GetNumAttributes() const { - return mAttributes.GetLength(); + return mAttributes.size(); } NodeAttribute* Node::GetAttribute(uint32 attributeNr) { // make sure we are in range - MCORE_ASSERT(attributeNr < mAttributes.GetLength()); + MCORE_ASSERT(attributeNr < mAttributes.size()); // return the attribute return mAttributes[attributeNr]; @@ -428,7 +420,7 @@ namespace EMotionFX uint32 Node::FindAttributeNumber(uint32 attributeTypeID) const { // check all attributes, and find where the specific attribute is - const uint32 numAttributes = mAttributes.GetLength(); + const uint32 numAttributes = mAttributes.size(); for (uint32 i = 0; i < numAttributes; ++i) { if (mAttributes[i]->GetType() == attributeTypeID) @@ -445,7 +437,7 @@ namespace EMotionFX NodeAttribute* Node::GetAttributeByType(uint32 attributeType) { // check all attributes - const uint32 numAttributes = mAttributes.GetLength(); + const uint32 numAttributes = mAttributes.size(); for (uint32 i = 0; i < numAttributes; ++i) { if (mAttributes[i]->GetType() == attributeType) @@ -462,13 +454,13 @@ namespace EMotionFX // remove the given attribute void Node::RemoveAttribute(uint32 index) { - mAttributes.Remove(index); + mAttributes.erase(AZStd::next(begin(mAttributes), index)); } void Node::AddChild(uint32 nodeIndex) { - mChildIndices.AddExact(nodeIndex); + mChildIndices.emplace_back(nodeIndex); } @@ -480,31 +472,34 @@ namespace EMotionFX void Node::SetNumChildNodes(uint32 numChildNodes) { - mChildIndices.Resize(numChildNodes); + mChildIndices.resize(numChildNodes); } void Node::PreAllocNumChildNodes(uint32 numChildNodes) { - mChildIndices.Reserve(numChildNodes); + mChildIndices.reserve(numChildNodes); } void Node::RemoveChild(uint32 nodeIndex) { - mChildIndices.RemoveByValue(nodeIndex); + if (const auto it = AZStd::find(begin(mChildIndices), end(mChildIndices), nodeIndex); it != end(mChildIndices)) + { + mChildIndices.erase(it); + } } void Node::RemoveAllChildNodes() { - mChildIndices.Clear(); + mChildIndices.clear(); } bool Node::GetHasChildNodes() const { - return (mChildIndices.GetLength() > 0); + return (mChildIndices.size() > 0); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h index b8618018d2..73e8a41c01 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 @@ -168,7 +168,7 @@ namespace EMotionFX * 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 mChildIndices.size(); } /** * Get the number of child nodes down the hierarchy of this node. @@ -189,7 +189,7 @@ namespace EMotionFX * @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(uint32 nodeIndex) const { return (AZStd::find(begin(mChildIndices), end(mChildIndices), nodeIndex) != end(mChildIndices)); } /** * Add a child to 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. @@ -421,8 +421,8 @@ namespace EMotionFX 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. */ + AZStd::vector mChildIndices; /**< The indices that point to the child nodes. */ + AZStd::vector mAttributes; /**< The node attributes. */ uint8 mNodeFlags; /**< The node flags are used to store boolean attributes of the node as single bits. */ /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp index 8f2e752917..edc1ea37cd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp @@ -41,14 +41,14 @@ namespace EMotionFX // preallocate space void NodeMap::Reserve(uint32 numEntries) { - mEntries.Reserve(numEntries); + mEntries.reserve(numEntries); } // resize the entries array void NodeMap::Resize(uint32 numEntries) { - mEntries.Resize(numEntries); + mEntries.resize(numEntries); } @@ -101,15 +101,15 @@ 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); + mEntries.emplace_back(); + SetEntry(mEntries.size() - 1, firstName, secondName); } // remove a given entry by its index void NodeMap::RemoveEntryByIndex(uint32 entryIndex) { - mEntries.Remove(entryIndex); + mEntries.erase(AZStd::next(begin(mEntries), entryIndex)); } @@ -122,7 +122,7 @@ namespace EMotionFX return; } - mEntries.Remove(entryIndex); + mEntries.erase(AZStd::next(begin(mEntries), entryIndex)); } @@ -135,7 +135,7 @@ namespace EMotionFX return; } - mEntries.Remove(entryIndex); + mEntries.erase(AZStd::next(begin(mEntries), entryIndex)); } @@ -211,7 +211,7 @@ namespace EMotionFX uint32 numBytes = sizeof(FileFormat::NodeMapChunk); // for all entries - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { numBytes += CalcFileStringSize(GetFirstNameString(i)); @@ -265,7 +265,7 @@ namespace EMotionFX // the main info FileFormat::NodeMapChunk nodeMapChunk{}; - nodeMapChunk.mNumEntries = mEntries.GetLength(); + nodeMapChunk.mNumEntries = mEntries.size(); MCore::Endian::ConvertUnsignedInt32To(&nodeMapChunk.mNumEntries, targetEndianType); if (f.Write(&nodeMapChunk, sizeof(FileFormat::NodeMapChunk)) == 0) { @@ -282,7 +282,7 @@ namespace EMotionFX } // for all entries - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { if (WriteFileString(&f, GetFirstNameString(i), targetEndianType) == false) @@ -320,9 +320,9 @@ namespace EMotionFX // get the number of entries - uint32 NodeMap::GetNumEntries() const + size_t NodeMap::GetNumEntries() const { - return mEntries.GetLength(); + return mEntries.size(); } @@ -364,7 +364,7 @@ namespace EMotionFX // find an entry index by its name uint32 NodeMap::FindEntryIndexByName(const char* firstName) const { - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { const AZStd::string& firstNameEntry = GetFirstName(i); @@ -381,7 +381,7 @@ namespace EMotionFX // find an entry index by its name ID uint32 NodeMap::FindEntryIndexByNameID(uint32 firstNameID) const { - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = mEntries.size(); for (uint32 i = 0; i < numEntries; ++i) { if (mEntries[i].mFirstNameID == firstNameID) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h index d033d0a36f..6db38efc32 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 @@ -54,7 +54,7 @@ namespace EMotionFX void Resize(uint32 numEntries); // get data - uint32 GetNumEntries() const; + size_t GetNumEntries() const; const char* GetFirstName(uint32 entryIndex) const; const char* GetSecondName(uint32 entryIndex) const; const AZStd::string& GetFirstNameString(uint32 entryIndex) const; @@ -88,7 +88,7 @@ namespace EMotionFX bool Save(const char* fileName, MCore::Endian::EEndianType targetEndianType) const; private: - MCore::Array mEntries; /**< The array of entries. */ + AZStd::vector mEntries; /**< The array of entries. */ AZStd::string mFileName; /**< The filename. */ Actor* mSourceActor; /**< The source actor. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp index 6c2c070e50..41c7c1e929 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" @@ -101,7 +102,6 @@ namespace EMotionFX mLastRecordTime = 0.0f; mCurrentPlayTime = 0.0f; - mObjects.SetMemoryCategory(EMFX_MEMCATEGORY_RECORDER); EMotionFX::ActorInstanceNotificationBus::Handler::BusConnect(); } @@ -345,7 +345,7 @@ namespace EMotionFX if (mRecordSettings.mRecordMorphs) { const uint32 numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); - actorInstanceData.mMorphTracks.Resize(numMorphs); + actorInstanceData.mMorphTracks.resize(numMorphs); for (uint32 m = 0; m < numMorphs; ++m) { actorInstanceData.mMorphTracks[m].Reserve(256); @@ -547,32 +547,31 @@ namespace EMotionFX const AnimGraph* animGraph = animGraphInstance->GetAnimGraph(); // add a new frame - MCore::Array& frames = animGraphInstanceData.mFrames; - if (frames.GetLength() > 0) + AZStd::vector& frames = animGraphInstanceData.mFrames; + if (frames.size() > 0) { - const uint32 byteOffset = frames.GetLast().mByteOffset + frames.GetLast().mNumBytes; - frames.AddEmpty(); - frames.GetLast().mByteOffset = byteOffset; - frames.GetLast().mNumBytes = 0; + const uint32 byteOffset = frames.back().mByteOffset + frames.back().mNumBytes; + frames.emplace_back(); + frames.back().mByteOffset = byteOffset; + frames.back().mNumBytes = 0; } else { - frames.AddEmpty(); - frames.GetLast().mByteOffset = 0; - frames.GetLast().mNumBytes = 0; + frames.emplace_back(); + frames.back().mByteOffset = 0; + frames.back().mNumBytes = 0; } // get the current frame - AnimGraphAnimFrame& currentFrame = frames.GetLast(); + AnimGraphAnimFrame& currentFrame = frames.back(); currentFrame.mTimeValue = mRecordTime; // save the parameter values const uint32 numParams = static_cast(animGraphInstance->GetAnimGraph()->GetNumValueParameters()); - currentFrame.mParameterValues.SetMemoryCategory(EMFX_MEMCATEGORY_RECORDER); - currentFrame.mParameterValues.Resize(numParams); + currentFrame.mParameterValues.resize(numParams); for (uint32 p = 0; p < numParams; ++p) { - currentFrame.mParameterValues[p] = animGraphInstance->GetParameterValue(p)->Clone(); + currentFrame.mParameterValues[p] = AZStd::unique_ptr(animGraphInstance->GetParameterValue(p)->Clone()); } // recursively save all unique datas @@ -595,19 +594,19 @@ namespace EMotionFX bool Recorder::SaveUniqueData(AnimGraphInstance* animGraphInstance, AnimGraphObject* object, AnimGraphInstanceData& animGraphInstanceData) { // get the current frame's data pointer - AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames.GetLast(); + AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames.back(); const uint32 frameOffset = currentFrame.mByteOffset; // prepare the objects array - mObjects.Clear(false); - mObjects.Reserve(1024); + mObjects.clear(); + mObjects.reserve(1024); // collect the objects we are going to save for this frame object->RecursiveCollectObjects(mObjects); // resize the object infos array - const uint32 numObjects = mObjects.GetLength(); - currentFrame.mObjectInfos.Resize(numObjects); + const uint32 numObjects = mObjects.size(); + currentFrame.mObjectInfos.resize(numObjects); // calculate how much memory we need for this frame uint32 requiredFrameBytes = 0; @@ -773,7 +772,7 @@ namespace EMotionFX { const size_t index = iterator - recordedActorInstances.begin(); const ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[index]; - const uint32 numMorphs = actorInstanceData.mMorphTracks.GetLength(); + const uint32 numMorphs = actorInstanceData.mMorphTracks.size(); if (numMorphs == actorInstance->GetMorphSetupInstance()->GetNumMorphTargets()) { for (uint32 i = 0; i < numMorphs; ++i) @@ -848,27 +847,27 @@ namespace EMotionFX AnimGraphInstance* animGraphInstance = animGraphInstanceData.mAnimGraphInstance; // get the real frame number (clamped) - const uint32 realFrameNumber = MCore::Min(frameNumber, animGraphInstanceData.mFrames.GetLength() - 1); + const uint32 realFrameNumber = MCore::Min(frameNumber, animGraphInstanceData.mFrames.size() - 1); const AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames[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 AZStd::vector& frameObjects = currentFrame.mObjectInfos; // first lets update all parameter values - MCORE_ASSERT(currentFrame.mParameterValues.GetLength() == animGraphInstance->GetAnimGraph()->GetNumParameters()); - const uint32 numParameters = currentFrame.mParameterValues.GetLength(); + MCORE_ASSERT(currentFrame.mParameterValues.size() == animGraphInstance->GetAnimGraph()->GetNumParameters()); + const uint32 numParameters = currentFrame.mParameterValues.size(); for (uint32 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]); + animGraphInstance->GetParameterValue(p)->InitFrom(currentFrame.mParameterValues[p].get()); } // process all objects for this frame uint32 totalBytesRead = 0; - const uint32 numObjects = frameObjects.GetLength(); + const uint32 numObjects = frameObjects.size(); for (uint32 a = 0; a < numObjects; ++a) { const AnimGraphAnimObjectInfo& objectInfo = frameObjects[a]; @@ -917,11 +916,11 @@ namespace EMotionFX animGraphInstance->CollectActiveAnimGraphNodes(&mActiveNodes); // get the history items as shortcut - MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; // finalize items const size_t numActiveNodes = mActiveNodes.size(); - const uint32 numHistoryItems = historyItems.GetLength(); + const uint32 numHistoryItems = historyItems.size(); for (uint32 h = 0; h < numHistoryItems; ++h) { NodeHistoryItem* curItem = historyItems[h]; @@ -1023,7 +1022,7 @@ namespace EMotionFX } } - historyItems.Add(item); + historyItems.emplace_back(item); } // add the weight key and update infos @@ -1053,8 +1052,8 @@ namespace EMotionFX // try to find a given node history item Recorder::NodeHistoryItem* Recorder::FindNodeHistoryItem(const ActorInstanceData& actorInstanceData, AnimGraphNode* node, float recordTime) const { - const MCore::Array& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.GetLength(); + const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { NodeHistoryItem* curItem = historyItems[i]; @@ -1076,8 +1075,8 @@ namespace EMotionFX // find a free track uint32 Recorder::FindFreeNodeHistoryItemTrack(const ActorInstanceData& actorInstanceData, NodeHistoryItem* item) const { - const MCore::Array& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.GetLength(); + const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const uint32 numItems = historyItems.size(); bool found = false; uint32 trackIndex = 0; @@ -1144,8 +1143,8 @@ namespace EMotionFX uint32 Recorder::CalcMaxNodeHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const { uint32 result = 0; - const MCore::Array& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.GetLength(); + const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { NodeHistoryItem* curItem = historyItems[i]; @@ -1163,8 +1162,8 @@ namespace EMotionFX uint32 Recorder::CalcMaxEventHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const { uint32 result = 0; - const MCore::Array& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.GetLength(); + const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { EventHistoryItem* curItem = historyItems[i]; @@ -1210,10 +1209,10 @@ namespace EMotionFX animGraphInstance->CollectActiveAnimGraphNodes(&mActiveNodes); // get the history items as shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; // finalize all items - const uint32 numItems = historyItems.GetLength(); + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { // remove unneeded key frames @@ -1246,7 +1245,7 @@ namespace EMotionFX const AnimGraphEventBuffer& eventBuffer = animGraphInstance->GetEventBuffer(); // iterate over all events - MCore::Array& historyItems = actorInstanceData->mEventHistoryItems; + AZStd::vector& historyItems = actorInstanceData->mEventHistoryItems; const uint32 numEvents = eventBuffer.GetNumEvents(); for (uint32 i = 0; i < numEvents; ++i) { @@ -1271,7 +1270,7 @@ namespace EMotionFX item->mTrackIndex = FindFreeEventHistoryItemTrack(*actorInstanceData, item); - historyItems.Add(item); + historyItems.emplace_back(item); } item->mEndTime = mRecordTime; @@ -1284,8 +1283,8 @@ 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(); + const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { EventHistoryItem* curItem = historyItems[i]; @@ -1303,8 +1302,8 @@ namespace EMotionFX // find a free event track index uint32 Recorder::FindFreeEventHistoryItemTrack(const ActorInstanceData& actorInstanceData, EventHistoryItem* item) const { - const MCore::Array& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.GetLength(); + const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; + const uint32 numItems = historyItems.size(); bool found = false; uint32 trackIndex = 0; while (found == false) @@ -1341,7 +1340,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()) @@ -1357,7 +1356,7 @@ namespace EMotionFX return MCORE_INVALIDINDEX32; } - const uint32 numFrames = animGraphData->mFrames.GetLength(); + const uint32 numFrames = animGraphData->mFrames.size(); if (numFrames == 0) { return MCORE_INVALIDINDEX32; @@ -1373,9 +1372,9 @@ namespace EMotionFX return 0; } - if (timeValue > animGraphData->mFrames.GetLast().mTimeValue) + if (timeValue > animGraphData->mFrames.back().mTimeValue) { - return animGraphData->mFrames.GetLength() - 1; + return animGraphData->mFrames.size() - 1; } for (uint32 i = 0; i < numFrames - 1; ++i) @@ -1459,11 +1458,11 @@ namespace EMotionFX // 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) { // clear the map array const uint32 maxIndex = CalcMaxNodeHistoryTrackIndex(actorInstanceData); - outItems->Resize(maxIndex + 1); + outItems->resize(maxIndex + 1); for (uint32 i = 0; i <= maxIndex; ++i) { ExtractedNodeHistoryItem item; @@ -1471,12 +1470,12 @@ namespace EMotionFX item.mValue = 0.0f; item.mKeyTrackSampleTime = 0.0f; item.mNodeHistoryItem = nullptr; - outItems->SetElem(i, item); + 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(); + const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { NodeHistoryItem* curItem = historyItems[i]; @@ -1506,25 +1505,25 @@ namespace EMotionFX item.mValue = curItem->mGlobalWeights.GetValueAtTime(item.mKeyTrackSampleTime, nullptr, nullptr, mRecordSettings.mInterpolate); } - outItems->SetElem(curItem->mTrackIndex, item); + outItems->emplace(AZStd::next(begin(*outItems), curItem->mTrackIndex), item); } } // build the map - outMap->Resize(maxIndex + 1); + outMap->resize(maxIndex + 1); for (uint32 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) { - outMap->SetElem(outItems->GetItem(i).mTrackIndex, i); + outMap->emplace(AZStd::next(begin(*outMap), outItems->at(i).mTrackIndex), i); } } } @@ -1539,7 +1538,7 @@ namespace EMotionFX const size_t maxNumTracks = static_cast(CalcMaxNodeHistoryTrackIndex()) + 1; trackFlags.resize(maxNumTracks); - const uint32 numNodeHistoryItems = actorInstanceData.mNodeHistoryItems.GetLength(); + const uint32 numNodeHistoryItems = actorInstanceData.mNodeHistoryItems.size(); for (uint32 i = 0; i < numNodeHistoryItems; ++i) { EMotionFX::Recorder::NodeHistoryItem* item = actorInstanceData.mNodeHistoryItems[i]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h index 3c9ec5ece8..02a61627a4 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 @@ -201,43 +201,59 @@ namespace EMotionFX 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 mTimeValue = 0.0f; + uint32 mByteOffset = 0; + uint32 mNumBytes = 0; + AZStd::vector mObjectInfos{}; + AZStd::vector> mParameterValues{}; + }; - ~AnimGraphAnimFrame() + struct EMFX_API AnimGraphInstanceData + { + AnimGraphInstance* mAnimGraphInstance = nullptr; + uint32 mNumFrames = 0; + uint32 mDataBufferSize = 0; + uint8* mDataBuffer = nullptr; + AZStd::vector mFrames{}; + + 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; } + mAnimGraphInstance = rhs.mAnimGraphInstance; + mNumFrames = rhs.mNumFrames; + mDataBufferSize = rhs.mDataBufferSize; + mDataBuffer = rhs.mDataBuffer; + mFrames = AZStd::move(rhs.mFrames); + rhs.mAnimGraphInstance = nullptr; + rhs.mNumFrames = 0; + rhs.mDataBufferSize = 0; + rhs.mDataBuffer = nullptr; + rhs.mFrames = {}; } - }; - 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; + } + mAnimGraphInstance = rhs.mAnimGraphInstance; + mNumFrames = rhs.mNumFrames; + mDataBufferSize = rhs.mDataBufferSize; + mDataBuffer = rhs.mDataBuffer; + mFrames = AZStd::move(rhs.mFrames); + rhs.mAnimGraphInstance = nullptr; + rhs.mNumFrames = 0; + rhs.mDataBufferSize = 0; + rhs.mDataBuffer = nullptr; + rhs.mFrames = {}; + return *this; } ~AnimGraphInstanceData() @@ -254,19 +270,16 @@ namespace EMotionFX ActorInstance* mActorInstance; // the actor instance this data is about AnimGraphInstanceData* mAnimGraphData; // 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 + AZStd::vector mNodeHistoryItems; // node history items + AZStd::vector mEventHistoryItems; // event history item TransformTracks mActorLocalTransform; // the actor instance's local transformation - MCore::Array< KeyTrackLinearDynamic > mMorphTracks; // morph animation data + AZStd::vector< KeyTrackLinearDynamic > mMorphTracks; // 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); + mNodeHistoryItems.reserve(64); + mEventHistoryItems.reserve(1024); + mMorphTracks.reserve(32); mAnimGraphData = nullptr; mActorInstance = nullptr; } @@ -274,20 +287,20 @@ namespace EMotionFX ~ActorInstanceData() { // clear the node history items - const uint32 numMotionItems = mNodeHistoryItems.GetLength(); + const uint32 numMotionItems = mNodeHistoryItems.size(); for (uint32 i = 0; i < numMotionItems; ++i) { delete mNodeHistoryItems[i]; } - mNodeHistoryItems.Clear(); + mNodeHistoryItems.clear(); // clear the event history items - const uint32 numEventItems = mEventHistoryItems.GetLength(); + const uint32 numEventItems = mEventHistoryItems.size(); for (uint32 i = 0; i < numEventItems; ++i) { delete mEventHistoryItems[i]; } - mEventHistoryItems.Clear(); + mEventHistoryItems.clear(); delete mAnimGraphData; } @@ -345,7 +358,7 @@ namespace EMotionFX AZ::u32 CalcMaxNumActiveMotions(const ActorInstanceData& actorInstanceData) const; AZ::u32 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); void StartPlayBack(); void StopPlayBack(); @@ -360,7 +373,7 @@ namespace EMotionFX RecordSettings mRecordSettings; AZStd::vector m_actorInstanceDatas; AZStd::vector m_timeDeltas; // The value of the time deltas whenever a key is made - MCore::Array mObjects; + AZStd::vector mObjects; AZStd::vector mActiveNodes; /**< A temp array to store active animgraph nodes in. */ MCore::Mutex mLock; AZ::TypeId m_sessionUuid; @@ -396,6 +409,6 @@ namespace EMotionFX 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 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..68c2f2a5c3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp @@ -26,7 +26,6 @@ namespace EMotionFX RepositioningLayerPass::RepositioningLayerPass(MotionLayerSystem* motionLayerSystem) : LayerPass(motionLayerSystem) { - mHierarchyPath.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MOTIONSYSTEMS); mLastReposNode = MCORE_INVALIDINDEX32; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h index a704f83e21..05f09d6329 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,7 +59,7 @@ namespace EMotionFX private: - MCore::Array mHierarchyPath; /**< The path of node indices to the repositioning node. */ + AZStd::vector 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. */ /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp index e1c6ca88f7..5860a0b452 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,7 +44,7 @@ namespace EMotionFX { Skeleton* result = Skeleton::Create(); - const uint32 numNodes = m_nodes.GetLength(); + const uint32 numNodes = m_nodes.size(); result->ReserveNodes(numNodes); result->m_rootNodes = m_rootNodes; @@ -65,14 +63,14 @@ namespace EMotionFX // reserve memory void Skeleton::ReserveNodes(uint32 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; } @@ -86,7 +84,7 @@ namespace EMotionFX m_nodes[nodeIndex]->Destroy(); } - m_nodes.Remove(nodeIndex); + m_nodes.erase(AZStd::next(begin(m_nodes), nodeIndex)); } @@ -95,14 +93,14 @@ namespace EMotionFX { if (delFromMem) { - const uint32 numNodes = m_nodes.GetLength(); + const uint32 numNodes = m_nodes.size(); for (uint32 i = 0; i < numNodes; ++i) { m_nodes[i]->Destroy(); } } - m_nodes.Clear(); + m_nodes.clear(); m_nodesMap.clear(); m_bindPose.Clear(); } @@ -134,7 +132,7 @@ namespace EMotionFX Node* Skeleton::FindNodeByNameNoCase(const char* name) const { // check the names for all nodes - const uint32 numNodes = m_nodes.GetLength(); + const uint32 numNodes = m_nodes.size(); for (uint32 i = 0; i < numNodes; ++i) { if (AzFramework::StringFunc::Equal(m_nodes[i]->GetNameString().c_str(), name, false /* no case */)) @@ -151,7 +149,7 @@ namespace EMotionFX Node* Skeleton::FindNodeByID(uint32 id) const { // check the ID's for all nodes - const uint32 numNodes = m_nodes.GetLength(); + const uint32 numNodes = m_nodes.size(); for (uint32 i = 0; i < numNodes; ++i) { if (m_nodes[i]->GetID() == id) @@ -180,8 +178,8 @@ namespace EMotionFX // set the number of nodes void Skeleton::SetNumNodes(uint32 numNodes) { - uint32 oldLength = m_nodes.GetLength(); - m_nodes.Resize(numNodes); + uint32 oldLength = m_nodes.size(); + m_nodes.resize(numNodes); for (uint32 i = oldLength; i < numNodes; ++i) { m_nodes[i] = nullptr; @@ -193,7 +191,7 @@ namespace EMotionFX // update the node indices void Skeleton::UpdateNodeIndexValues(uint32 startNode) { - const uint32 numNodes = m_nodes.GetLength(); + const uint32 numNodes = m_nodes.size(); for (uint32 i = startNode; i < numNodes; ++i) { m_nodes[i]->SetNodeIndex(i); @@ -204,35 +202,35 @@ namespace EMotionFX // reserve memory for the root nodes array void Skeleton::ReserveRootNodes(uint32 numNodes) { - m_rootNodes.Reserve(numNodes); + m_rootNodes.reserve(numNodes); } // add a root node void Skeleton::AddRootNode(uint32 nodeIndex) { - m_rootNodes.Add(nodeIndex); + m_rootNodes.emplace_back(nodeIndex); } // remove a given root node void Skeleton::RemoveRootNode(uint32 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(); + const uint32 numNodes = m_nodes.size(); for (uint32 i = 0; i < numNodes; ++i) { MCore::LogInfo("%d = '%s'", i, m_nodes[i]->GetName()); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h index 1b9c09749c..e5887df0f6 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,7 +32,7 @@ namespace EMotionFX Skeleton* Clone(); - MCORE_INLINE uint32 GetNumNodes() const { return m_nodes.GetLength(); } + MCORE_INLINE size_t GetNumNodes() const { return m_nodes.size(); } MCORE_INLINE Node* GetNode(uint32 index) const { return m_nodes[index]; } void ReserveNodes(uint32 numNodes); @@ -103,7 +103,7 @@ namespace EMotionFX * 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. @@ -144,9 +144,9 @@ namespace EMotionFX uint32 CalcHierarchyDepthForNode(uint32 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/StandardMaterial.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp index 8147116048..98a192936e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp @@ -356,8 +356,6 @@ namespace EMotionFX mIOR = 1.5f; mDoubleSided = true; mWireFrame = false; - - mLayers.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MATERIALS); } @@ -398,8 +396,8 @@ namespace EMotionFX standardMaterial->mWireFrame = mWireFrame; // copy the layers - const uint32 numLayers = mLayers.GetLength(); - standardMaterial->mLayers.Resize(numLayers); + const uint32 numLayers = mLayers.size(); + standardMaterial->mLayers.resize(numLayers); for (uint32 i = 0; i < numLayers; ++i) { standardMaterial->mLayers[i] = StandardMaterialLayer::Create(); @@ -420,7 +418,10 @@ namespace EMotionFX { layer->Destroy(); } - mLayers.RemoveByValue(layer); + if (const auto it = AZStd::find(begin(mLayers), end(mLayers), layer); it != end(mLayers)) + { + mLayers.erase(it); + } } } @@ -547,52 +548,52 @@ namespace EMotionFX StandardMaterialLayer* StandardMaterial::AddLayer(StandardMaterialLayer* layer) { - mLayers.Add(layer); + mLayers.emplace_back(layer); return layer; } - uint32 StandardMaterial::GetNumLayers() const + size_t StandardMaterial::GetNumLayers() const { - return mLayers.GetLength(); + return mLayers.size(); } StandardMaterialLayer* StandardMaterial::GetLayer(uint32 nr) { - MCORE_ASSERT(nr < mLayers.GetLength()); + MCORE_ASSERT(nr < mLayers.size()); return mLayers[nr]; } void StandardMaterial::RemoveLayer(uint32 nr, bool delFromMem) { - MCORE_ASSERT(nr < mLayers.GetLength()); + MCORE_ASSERT(nr < mLayers.size()); if (delFromMem) { mLayers[nr]->Destroy(); } - mLayers.Remove(nr); + mLayers.erase(AZStd::next(begin(mLayers), nr)); } void StandardMaterial::RemoveAllLayers() { - const uint32 numLayers = mLayers.GetLength(); + const uint32 numLayers = mLayers.size(); for (uint32 i = 0; i < numLayers; ++i) { mLayers[i]->Destroy(); } - mLayers.Clear(); + mLayers.clear(); } uint32 StandardMaterial::FindLayer(uint32 layerType) const { // search through all layers - const uint32 numLayers = mLayers.GetLength(); + const uint32 numLayers = mLayers.size(); for (uint32 i = 0; i < numLayers; ++i) { if (mLayers[i]->GetType() == layerType) @@ -607,6 +608,6 @@ namespace EMotionFX void StandardMaterial::ReserveLayers(uint32 numLayers) { - mLayers.Reserve(numLayers); + mLayers.reserve(numLayers); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h index 659157d96d..de637cf3df 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h @@ -415,7 +415,7 @@ 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. @@ -471,7 +471,7 @@ namespace EMotionFX protected: - MCore::Array< StandardMaterialLayer* > mLayers; /**< StandardMaterial layers. */ + AZStd::vector< StandardMaterialLayer* > mLayers; /**< StandardMaterial layers. */ MCore::RGBAColor mAmbient; /**< Ambient color. */ MCore::RGBAColor mDiffuse; /**< Diffuse color. */ MCore::RGBAColor mSpecular; /**< Specular color. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp index df7a38486a..fa60ed4033 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp @@ -30,7 +30,6 @@ namespace EMotionFX mStartPolygon = startPolygon; mMaterial = materialIndex; - mBones.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); SetNumBones(numBones); } @@ -51,7 +50,7 @@ namespace EMotionFX // clone the submesh SubMesh* SubMesh::Clone(Mesh* newParentMesh) { - SubMesh* clone = aznew SubMesh(newParentMesh, mStartVertex, mStartIndex, mStartPolygon, mNumVertices, mNumIndices, mNumPolygons, mMaterial, mBones.GetLength()); + SubMesh* clone = aznew SubMesh(newParentMesh, mStartVertex, mStartIndex, mStartPolygon, mNumVertices, mNumIndices, mNumPolygons, mMaterial, mBones.size()); clone->mBones = mBones; return clone; } @@ -61,7 +60,7 @@ namespace EMotionFX void SubMesh::RemapBone(uint16 oldNodeNr, uint16 newNodeNr) { // get the number of bones stored inside the submesh - const uint32 numBones = mBones.GetLength(); + const uint32 numBones = mBones.size(); // iterate through all bones and remap the bones for (uint32 i = 0; i < numBones; ++i) @@ -79,7 +78,7 @@ namespace EMotionFX void SubMesh::ReinitBonesArray(SkinningInfoVertexAttributeLayer* skinLayer) { // clear the bones array - mBones.Clear(false); + mBones.clear(); // get shortcuts to the original vertex numbers const uint32* orgVertices = (uint32*)mParentMesh->FindOriginalVertexData(Mesh::ATTRIB_ORGVTXNUMBERS); @@ -101,9 +100,9 @@ namespace EMotionFX const uint32 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(mBones), end(mBones), nodeNr) == end(mBones)) { - mBones.Add(nodeNr); + mBones.emplace_back(nodeNr); } } } @@ -231,7 +230,7 @@ namespace EMotionFX uint32 SubMesh::FindBoneIndex(uint32 nodeNr) const { - const uint32 numBones = mBones.GetLength(); + const uint32 numBones = mBones.size(); for (uint32 i = 0; i < numBones; ++i) { if (mBones[i] == nodeNr) @@ -247,7 +246,7 @@ namespace EMotionFX // remove the given bone void SubMesh::RemoveBone(uint16 index) { - mBones.Remove(index); + mBones.erase(AZStd::next(begin(mBones), index)); } @@ -255,11 +254,11 @@ namespace EMotionFX { if (numBones == 0) { - mBones.Clear(); + mBones.clear(); } else { - mBones.Resize(numBones); + mBones.resize(numBones); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h index df798536da..1cec56efc6 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 @@ -191,7 +191,7 @@ namespace EMotionFX * 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 mBones.size(); } /** * Get the node index for a given bone. @@ -205,21 +205,21 @@ namespace EMotionFX * 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 uint32* GetBones() { return mBones.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 mBones; } /** * 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 mBones; } /** * Reinitialize the bones. @@ -268,7 +268,7 @@ namespace EMotionFX protected: - MCore::Array mBones; /**< The collection of bones. These are stored as node numbers that point into the actor. */ + AZStd::vector 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. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h b/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h index 1cee75200c..cf66a1543e 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 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..c0867139e7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp @@ -432,7 +432,7 @@ namespace EMStudio } // add and return the manipulator - mTransformationManipulators.Add(manipulator); + mTransformationManipulators.emplace_back(manipulator); return manipulator; } @@ -440,12 +440,15 @@ 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(mTransformationManipulators), end(mTransformationManipulators), manipulator); it != end(mTransformationManipulators)) + { + mTransformationManipulators.erase(it); + } } // returns the gizmo array - MCore::Array* EMStudioManager::GetTransformationManipulators() + AZStd::vector* EMStudioManager::GetTransformationManipulators() { return &mTransformationManipulators; } 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..62c4b5e115 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h @@ -104,7 +104,7 @@ namespace EMStudio // 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 @@ -115,7 +115,7 @@ namespace EMStudio MCORE_INLINE bool GetSkipSourceControlCommands() { return m_skipSourceControlCommands; } MCORE_INLINE void SetSkipSourceControlCommands(bool skip) { m_skipSourceControlCommands = skip; } private: - MCore::Array mTransformationManipulators; + AZStd::vector mTransformationManipulators; QPointer mMainWindow; QApplication* mApp; PluginManager* mPluginManager; 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..baf721d2ce 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 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..c1c48b3480 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 @@ -1089,14 +1090,14 @@ namespace EMStudio const uint32 numPlugins = pluginManager->GetNumPlugins(); // add each plugin name in an array to sort them - MCore::Array sortedPlugins; - sortedPlugins.Reserve(numPlugins); + AZStd::vector sortedPlugins; + sortedPlugins.reserve(numPlugins); for (uint32 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(); @@ -1839,7 +1840,7 @@ namespace EMStudio dir.setSorting(QDir::Name); // add each layout - mLayoutNames.Clear(); + mLayoutNames.clear(); AZStd::string filename; const QFileInfoList list = dir.entryInfoList(); const int listSize = list.size(); @@ -1856,12 +1857,12 @@ namespace EMStudio if (extension == "layout") { AzFramework::StringFunc::Path::GetFileName(filename.c_str(), filename); - mLayoutNames.Add(filename); + mLayoutNames.emplace_back(filename); } } // add each menu - const uint32 numLayoutNames = mLayoutNames.GetLength(); + const uint32 numLayoutNames = mLayoutNames.size(); for (uint32 i = 0; i < numLayoutNames; ++i) { QAction* action = mLayoutsMenu->addAction(mLayoutNames[i].c_str()); 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..7217259bcb 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 @@ -148,7 +148,7 @@ namespace EMStudio FileManager* GetFileManager() const { return mFileManager; } PreferencesWindow* GetPreferencesWindow() const { return mPreferencesWindow; } - uint32 GetNumLayouts() const { return mLayoutNames.GetLength(); } + size_t GetNumLayouts() const { return mLayoutNames.size(); } const char* GetLayoutName(uint32 index) const { return mLayoutNames[index].c_str(); } const char* GetCurrentLayoutName() const; @@ -195,7 +195,7 @@ namespace EMStudio MysticQt::KeyboardShortcutManager* mShortcutManager; // layouts (application modes) - MCore::Array mLayoutNames; + AZStd::vector mLayoutNames; bool mLayoutLoaded; // menu actions 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..4aaebc3e3e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp @@ -51,8 +51,6 @@ namespace EMStudio mMeshIcon = new QIcon(meshIconFilename); mCharacterIcon = new QIcon(iconFilename("Character.svg")); - mActorInstanceIDs.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK); - QVBoxLayout* layout = new QVBoxLayout(); layout->setMargin(0); @@ -142,7 +140,7 @@ namespace EMStudio } - void NodeHierarchyWidget::Update(const MCore::Array& actorInstanceIDs, CommandSystem::SelectionList* selectionList) + void NodeHierarchyWidget::Update(const AZStd::vector& actorInstanceIDs, CommandSystem::SelectionList* selectionList) { mActorInstanceIDs = actorInstanceIDs; ConvertFromSelectionList(selectionList); @@ -153,7 +151,7 @@ namespace EMStudio void NodeHierarchyWidget::Update(uint32 actorInstanceID, CommandSystem::SelectionList* selectionList) { - mActorInstanceIDs.Clear(); + mActorInstanceIDs.clear(); if (actorInstanceID == MCORE_INVALIDINDEX32) { @@ -169,12 +167,12 @@ namespace EMStudio continue; } - mActorInstanceIDs.Add(actorInstance->GetID()); + mActorInstanceIDs.emplace_back(actorInstance->GetID()); } } else { - mActorInstanceIDs.Add(actorInstanceID); + mActorInstanceIDs.emplace_back(actorInstanceID); } Update(mActorInstanceIDs, selectionList); @@ -189,7 +187,7 @@ namespace EMStudio mHierarchy->clear(); // get the number actor instances and iterate over them - const uint32 numActorInstances = mActorInstanceIDs.GetLength(); + const uint32 numActorInstances = mActorInstanceIDs.size(); for (uint32 i = 0; i < numActorInstances; ++i) { // get the actor instance by its id @@ -267,7 +265,7 @@ namespace EMStudio 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(mBoneList), end(mBoneList), nodeIndex) != end(mBoneList)); const bool isNode = (isMeshNode == false && isBone == false); return CheckIfNodeVisible(nodeName, isMeshNode, isBone, isNode); @@ -296,7 +294,7 @@ namespace EMStudio const uint32 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(mBoneList), end(mBoneList), nodeIndex) != end(mBoneList)); const bool isNode = (isMeshNode == false && isBone == false); if (CheckIfNodeVisible(nodeName, isMeshNode, isBone, isNode)) @@ -563,7 +561,6 @@ namespace EMStudio UpdateSelection(); emit OnDoubleClicked(m_selectedNodes); - emit OnDoubleClicked(GetSelectedItemsAsMCoreArray()); } @@ -634,7 +631,6 @@ namespace EMStudio void NodeHierarchyWidget::FireSelectionDoneSignal() { emit OnSelectionDone(m_selectedNodes); - emit OnSelectionDone(GetSelectedItemsAsMCoreArray()); } @@ -645,23 +641,6 @@ 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) { @@ -706,7 +685,7 @@ namespace EMStudio m_selectedNodes.clear(); // get the number actor instances and iterate over them - const uint32 numActorInstances = mActorInstanceIDs.GetLength(); + const uint32 numActorInstances = mActorInstanceIDs.size(); for (uint32 i = 0; i < numActorInstances; ++i) { // add the actor to the node hierarchy widget 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..b55062f57b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h @@ -68,7 +68,7 @@ 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 AzQtComponents::FilteredSearchWidget* GetSearchWidget() { return m_searchWidget; } @@ -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); @@ -138,8 +133,8 @@ namespace EMStudio QIcon* mNodeIcon; QIcon* mMeshIcon; QIcon* mCharacterIcon; - MCore::Array mBoneList; - MCore::Array mActorInstanceIDs; + AZStd::vector mBoneList; + AZStd::vector mActorInstanceIDs; AZStd::string mItemName; AZStd::string mActorInstanceIDString; bool mUseSingleSelection; 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..e0d562ee0f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.cpp @@ -49,7 +49,7 @@ namespace EMStudio connect(mOKButton, &QPushButton::clicked, this, &NodeSelectionWindow::accept); connect(mCancelButton, &QPushButton::clicked, this, &NodeSelectionWindow::reject); connect(this, &NodeSelectionWindow::accepted, this, &NodeSelectionWindow::OnAccept); - connect(mHierarchyWidget, static_cast)>(&NodeHierarchyWidget::OnDoubleClicked), this, &NodeSelectionWindow::OnDoubleClicked); + connect(mHierarchyWidget, 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)) ); @@ -63,7 +63,7 @@ namespace EMStudio } - void NodeSelectionWindow::OnDoubleClicked(MCore::Array selection) + void NodeSelectionWindow::OnDoubleClicked(AZStd::vector selection) { MCORE_UNUSED(selection); accept(); 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..46eabf7b58 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.h @@ -30,7 +30,7 @@ namespace EMStudio * 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( mNodeSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); */ class EMSTUDIO_API NodeSelectionWindow : public QDialog @@ -43,11 +43,11 @@ namespace EMStudio 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); } + void Update(const AZStd::vector& actorInstanceIDs, CommandSystem::SelectionList* selectionList = nullptr) { mHierarchyWidget->Update(actorInstanceIDs, selectionList); } public slots: void OnAccept(); - void OnDoubleClicked(MCore::Array selection); + void OnDoubleClicked(AZStd::vector selection); private: NodeHierarchyWidget* mHierarchyWidget; 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..9eb2c7f23e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp @@ -33,7 +33,7 @@ namespace EMStudio // compute the height of all notification windows with the spacing int allNotificationWindowsHeight = 0; - const uint32 numNotificationWindows = mNotificationWindows.GetLength(); + const uint32 numNotificationWindows = mNotificationWindows.size(); for (uint32 i = 0; i < numNotificationWindows; ++i) { allNotificationWindowsHeight += mNotificationWindows[i]->geometry().height() + notificationWindowSpacing; @@ -45,7 +45,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); + mNotificationWindows.emplace_back(notificationWindow); } @@ -53,25 +53,24 @@ namespace EMStudio void NotificationWindowManager::RemoveNotificationWindow(NotificationWindow* notificationWindow) { // find the notification window - const uint32 index = mNotificationWindows.Find(notificationWindow); + auto windowIt = AZStd::find(begin(mNotificationWindows), end(mNotificationWindows), notificationWindow); // if not found, stop here - if (index == MCORE_INVALIDINDEX32) + if (windowIt == end(mNotificationWindows)) { 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(mNotificationWindows); ++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); + mNotificationWindows.erase(windowIt); } @@ -83,7 +82,7 @@ namespace EMStudio // move each notification window int currentNotificationWindowHeight = notificationWindowMainWindowPadding; - const uint32 numNotificationWindows = mNotificationWindows.GetLength(); + const uint32 numNotificationWindows = mNotificationWindows.size(); for (uint32 i = 0; i < numNotificationWindows; ++i) { // add the height of the notification window 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..8817f3d451 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 @@ -35,9 +35,9 @@ namespace EMStudio return mNotificationWindows[index]; } - MCORE_INLINE uint32 GetNumNotificationWindow() const + MCORE_INLINE size_t GetNumNotificationWindow() const { - return mNotificationWindows.GetLength(); + return mNotificationWindows.size(); } void OnMovedOrResized(); @@ -53,7 +53,7 @@ namespace EMStudio } private: - MCore::Array mNotificationWindows; + AZStd::vector mNotificationWindows; int32 mVisibleTime; }; } // namespace EMStudio 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 ef281b8301..abbb9b7d81 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,8 +27,6 @@ namespace EMStudio RenderPlugin::RenderPlugin() : DockWidgetPlugin() { - mActors.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); - mIsVisible = true; mRenderUtil = nullptr; mUpdateCallback = nullptr; @@ -130,7 +128,7 @@ namespace EMStudio void RenderPlugin::CleanEMStudioActors() { // get rid of the actors - const uint32 numActors = mActors.GetLength(); + const uint32 numActors = mActors.size(); for (uint32 i = 0; i < numActors; ++i) { if (mActors[i]) @@ -138,7 +136,7 @@ namespace EMStudio delete mActors[i]; } } - mActors.Clear(); + mActors.clear(); } @@ -159,7 +157,7 @@ namespace EMStudio // get rid of the emstudio actor delete emstudioActor; - mActors.Remove(index); + mActors.erase(AZStd::next(begin(mActors), index)); return true; } @@ -168,8 +166,8 @@ 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(); + const uint32 numGizmos = transformationManipulators->size(); // init the active manipulator to nullptr MCommon::TransformationManipulator* activeManipulator = nullptr; @@ -180,7 +178,7 @@ namespace EMStudio for (uint32 i = 0; i < numGizmos; ++i) { // get the current manipulator and check if it exists - MCommon::TransformationManipulator* currentManipulator = transformationManipulators->GetItem(i); + MCommon::TransformationManipulator* currentManipulator = transformationManipulators->at(i); if (currentManipulator == nullptr || currentManipulator->GetIsVisible() == false) { continue; @@ -319,7 +317,7 @@ namespace EMStudio RenderPlugin::EMStudioRenderActor* RenderPlugin::FindEMStudioActor(EMotionFX::ActorInstance* actorInstance, bool doubleCheckInstance) { // get the number of emstudio actors and iterate through them - const uint32 numEMStudioRenderActors = mActors.GetLength(); + const uint32 numEMStudioRenderActors = mActors.size(); for (uint32 i = 0; i < numEMStudioRenderActors; ++i) { EMStudioRenderActor* EMStudioRenderActor = mActors[i]; @@ -331,7 +329,7 @@ namespace EMStudio 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(); + const uint32 numActorInstances = EMStudioRenderActor->mActorInstances.size(); for (uint32 a = 0; a < numActorInstances; ++a) { if (EMStudioRenderActor->mActorInstances[a] == actorInstance) @@ -359,7 +357,7 @@ namespace EMStudio return nullptr; } - const uint32 numEMStudioRenderActors = mActors.GetLength(); + const uint32 numEMStudioRenderActors = mActors.size(); for (uint32 i = 0; i < numEMStudioRenderActors; ++i) { EMStudioRenderActor* EMStudioRenderActor = mActors[i]; @@ -378,7 +376,7 @@ namespace EMStudio uint32 RenderPlugin::FindEMStudioActorIndex(EMStudioRenderActor* EMStudioRenderActor) { // get the number of emstudio actors and iterate through them - const uint32 numEMStudioRenderActors = mActors.GetLength(); + const uint32 numEMStudioRenderActors = mActors.size(); for (uint32 i = 0; i < numEMStudioRenderActors; ++i) { // compare the two emstudio actors and return the current index in case of success @@ -407,7 +405,7 @@ namespace EMStudio void RenderPlugin::AddEMStudioActor(EMStudioRenderActor* emstudioActor) { // add the actor to the list and return success - mActors.Add(emstudioActor); + mActors.emplace_back(emstudioActor); } @@ -440,8 +438,7 @@ namespace EMStudio } } - // 2. Remove invalid, not ready or unused emstudio actors - for (uint32 i = 0; i < mActors.GetLength(); ++i) + for (uint32 i = 0; i < mActors.size(); ++i) { EMStudioRenderActor* emstudioActor = mActors[i]; EMotionFX::Actor* actor = emstudioActor->mActor; @@ -479,7 +476,7 @@ namespace EMStudio if (!emstudioActor) { - for (uint32 j = 0; j < mActors.GetLength(); ++j) + for (uint32 j = 0; j < mActors.size(); ++j) { EMStudioRenderActor* currentEMStudioActor = mActors[j]; if (actor == currentEMStudioActor->mActor) @@ -496,19 +493,17 @@ namespace EMStudio actorInstance->SetCustomData(emstudioActor->mRenderActor); // 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->mActorInstances), end(emstudioActor->mActorInstances), actorInstance) == end(emstudioActor->mActorInstances)) { - emstudioActor->mActorInstances.Add(actorInstance); + emstudioActor->mActorInstances.emplace_back(actorInstance); } } } // 4. Unlink invalid actor instances from the emstudio actors - for (uint32 i = 0; i < mActors.GetLength(); ++i) + for (EMStudioRenderActor* emstudioActor : mActors) { - EMStudioRenderActor* emstudioActor = mActors[i]; - - for (uint32 j = 0; j < emstudioActor->mActorInstances.GetLength();) + for (uint32 j = 0; j < emstudioActor->mActorInstances.size();) { EMotionFX::ActorInstance* emstudioActorInstance = emstudioActor->mActorInstances[j]; bool found = false; @@ -524,7 +519,7 @@ namespace EMStudio if (found == false) { - emstudioActor->mActorInstances.Remove(j); + emstudioActor->mActorInstances.erase(AZStd::next(begin(emstudioActor->mActorInstances), j)); } else { @@ -571,7 +566,7 @@ namespace EMStudio RenderPlugin::EMStudioRenderActor::~EMStudioRenderActor() { // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); + const uint32 numActorInstances = mActorInstances.size(); for (uint32 i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = mActorInstances[i]; @@ -1038,7 +1033,7 @@ namespace EMStudio MCommon::RenderUtil::TrajectoryTracePath* tracePath = new MCommon::RenderUtil::TrajectoryTracePath(); tracePath->mActorInstance = actorInstance; - tracePath->mTraceParticles.Reserve(512); + tracePath->mTraceParticles.reserve(512); m_trajectoryTracePaths.emplace_back(tracePath); return tracePath; @@ -1079,13 +1074,13 @@ namespace EMStudio const EMotionFX::Transform& worldTM = actorInstance->GetWorldSpaceTransform(); bool distanceTraveledEnough = false; - if (trajectoryPath->mTraceParticles.GetIsEmpty()) + if (trajectoryPath->mTraceParticles.empty()) { distanceTraveledEnough = true; } else { - const uint32 numParticles = trajectoryPath->mTraceParticles.GetLength(); + const uint32 numParticles = trajectoryPath->mTraceParticles.size(); const EMotionFX::Transform& oldWorldTM = trajectoryPath->mTraceParticles[numParticles - 1].mWorldTM; const AZ::Vector3& oldPos = oldWorldTM.mPosition; @@ -1109,7 +1104,7 @@ namespace EMStudio // 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); + trajectoryPath->mTraceParticles.emplace_back(trajectoryParticle); // reset the time passed as we just added a new particle trajectoryPath->mTimePassed = 0.0f; @@ -1117,9 +1112,9 @@ namespace EMStudio } // make sure we don't have too many items in our array - if (trajectoryPath->mTraceParticles.GetLength() > 50) + if (trajectoryPath->mTraceParticles.size() > 50) { - trajectoryPath->mTraceParticles.RemoveFirst(); + trajectoryPath->mTraceParticles.erase(begin(trajectoryPath->mTraceParticles)); } } } 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 7fa0a880d0..27e5504e72 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 @@ -53,9 +53,9 @@ namespace EMStudio MCORE_MEMORYOBJECTCATEGORY(RenderPlugin::EMStudioRenderActor, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); EMotionFX::Actor* mActor; - MCore::Array mBoneList; + AZStd::vector mBoneList; RenderGL::GLActor* mRenderActor; - MCore::Array mActorInstances; + AZStd::vector mActorInstances; float mNormalsScaleMultiplier; float mCharacterHeight; float mOffsetFromTrajectoryNode; @@ -203,7 +203,7 @@ namespace EMStudio RenderUpdateCallback* mUpdateCallback; RenderOptions mRenderOptions; - MCore::Array mActors; + AZStd::vector mActors; // view widgets AZStd::vector m_viewWidgets; 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 6de228fa52..24b4471280 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 @@ -84,13 +84,13 @@ namespace EMStudio const EMotionFX::Transform globalTM = transformData->GetCurrentPose()->GetWorldSpaceTransform(motionExtractionNode->GetNodeIndex()).ProjectedToGroundPlane(); bool distanceTraveledEnough = false; - if (trajectoryPath->mTraceParticles.GetIsEmpty()) + if (trajectoryPath->mTraceParticles.empty()) { distanceTraveledEnough = true; } else { - const uint32 numParticles = trajectoryPath->mTraceParticles.GetLength(); + const uint32 numParticles = trajectoryPath->mTraceParticles.size(); const EMotionFX::Transform& oldGlobalTM = trajectoryPath->mTraceParticles[numParticles - 1].mWorldTM; const AZ::Vector3& oldPos = oldGlobalTM.mPosition; @@ -115,7 +115,7 @@ namespace EMStudio // 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); + trajectoryPath->mTraceParticles.emplace_back(trajectoryParticle); // reset the time passed as we just added a new particle trajectoryPath->mTimePassed = 0.0f; @@ -123,9 +123,9 @@ namespace EMStudio } // make sure we don't have too many items in our array - if (trajectoryPath->mTraceParticles.GetLength() > 50) + if (trajectoryPath->mTraceParticles.size() > 50) { - trajectoryPath->mTraceParticles.RemoveFirst(); + trajectoryPath->mTraceParticles.erase(begin(trajectoryPath->mTraceParticles)); } } } 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 25ae2ba2d4..b123f62ac5 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 @@ -38,8 +38,6 @@ namespace EMStudio //mLines.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); //mLines.Reserve(2048); - mSelectedActorInstances.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); - // camera used to render the little axis on the bottom left mAxisFakeCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_FRONT); @@ -255,13 +253,13 @@ namespace EMStudio } // 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(); + const uint32 numGizmos = transformationManipulators->size(); for (uint32 i = 0; i < numGizmos; ++i) { - MCommon::TransformationManipulator* activeManipulator = transformationManipulators->GetItem(i); + MCommon::TransformationManipulator* activeManipulator = transformationManipulators->at(i); if (activeManipulator == nullptr) { continue; @@ -619,7 +617,7 @@ namespace EMStudio } } - mSelectedActorInstances.Clear(false); + mSelectedActorInstances.clear(); if (ctrlPressed) { @@ -627,13 +625,13 @@ namespace EMStudio const uint32 numSelectedActorInstances = selection.GetNumSelectedActorInstances(); for (uint32 i = 0; i < numSelectedActorInstances; ++i) { - mSelectedActorInstances.Add(selection.GetActorInstance(i)); + mSelectedActorInstances.emplace_back(selection.GetActorInstance(i)); } } if (selectedActorInstance) { - mSelectedActorInstances.Add(selectedActorInstance); + mSelectedActorInstances.emplace_back(selectedActorInstance); } CommandSystem::SelectActorInstancesUsingCommands(mSelectedActorInstances); @@ -1008,14 +1006,14 @@ namespace EMStudio return; } - MCore::Array* transformationManipulators = GetManager()->GetTransformationManipulators(); - const uint32 numGizmos = transformationManipulators->GetLength(); + AZStd::vector* transformationManipulators = GetManager()->GetTransformationManipulators(); + const uint32 numGizmos = transformationManipulators->size(); // render all visible gizmos for (uint32 i = 0; i < numGizmos; ++i) { // update the gizmos - MCommon::TransformationManipulator* activeManipulator = transformationManipulators->GetItem(i); + MCommon::TransformationManipulator* activeManipulator = transformationManipulators->at(i); // update the gizmos if there is an active manipulator if (activeManipulator == nullptr) @@ -1048,7 +1046,7 @@ namespace EMStudio } // render custom triangles - const uint32 numTriangles = mTriangles.GetLength(); + const uint32 numTriangles = mTriangles.size(); for (uint32 i = 0; i < numTriangles; ++i) { const Triangle& curTri = mTriangles[i]; 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 10722f744a..d2ec5d71ea 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 @@ -98,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) { mTriangles.emplace_back(Triangle(posA, posB, posC, normalA, normalB, normalC, color)); } + MCORE_INLINE void ClearTriangles() { mTriangles.clear(); } void RenderTriangles(); // helper rendering functions @@ -139,10 +139,10 @@ namespace EMStudio RenderPlugin* mPlugin; RenderViewWidget* mViewWidget; - MCore::Array mTriangles; + AZStd::vector mTriangles; EventHandler mEventHandler; - MCore::Array mSelectedActorInstances; + AZStd::vector mSelectedActorInstances; MCommon::TransformationManipulator* mActiveTransformManip; 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..5026af3b06 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 @@ -808,11 +808,11 @@ 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(); + AZStd::vector* gizmos = manager->GetTransformationManipulators(); + const uint32 numGizmos = gizmos->size(); for (uint32 i = 0; i < numGizmos; ++i) { - MCommon::TransformationManipulator* gizmo = gizmos->GetItem(i); + MCommon::TransformationManipulator* gizmo = gizmos->at(i); // check the gizmo name if (paramName == gizmo->GetName()) 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..ad4098308d 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 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.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.h index 048d79a696..4ec48bbffb 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 @@ -29,7 +29,7 @@ namespace EMStudio * 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( mNodeSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); */ class BlendNodeSelectionWindow : public QDialog 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..43225692ac 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 @@ -40,7 +40,7 @@ namespace EMStudio // add all input ports const AZStd::vector& inPorts = mEMFXNode->GetInputPorts(); const uint32 numInputs = static_cast(inPorts.size()); - mInputPorts.Reserve(numInputs); + mInputPorts.reserve(numInputs); for (uint32 i = 0; i < numInputs; ++i) { NodePort* port = AddInputPort(false); @@ -53,7 +53,7 @@ namespace EMStudio // add all output ports const AZStd::vector& outPorts = mEMFXNode->GetOutputPorts(); const uint32 numOutputs = static_cast(outPorts.size()); - mOutputPorts.Reserve(numOutputs); + mOutputPorts.reserve(numOutputs); for (uint32 i = 0; i < numOutputs; ++i) { NodePort* port = AddOutputPort(false); @@ -112,7 +112,6 @@ namespace EMStudio default: return QColor(50, 250, 250); } - ; } @@ -303,7 +302,7 @@ namespace EMStudio { // draw the input ports QColor portBrushColor, portPenColor; - const uint32 numInputs = mInputPorts.GetLength(); + const uint32 numInputs = mInputPorts.size(); for (uint32 i = 0; i < numInputs; ++i) { // get the input port and the corresponding rect @@ -322,7 +321,7 @@ namespace EMStudio if (GetHasVisualOutputPorts()) { // draw the output ports - const uint32 numOutputs = mOutputPorts.GetLength(); + const uint32 numOutputs = mOutputPorts.size(); for (uint32 i = 0; i < numOutputs; ++i) { // get the output port and the corresponding rect @@ -456,7 +455,7 @@ namespace EMStudio painter.setFont(mPortNameFont); // draw input port text - const uint32 numInputs = mInputPorts.GetLength(); + const uint32 numInputs = mInputPorts.size(); for (uint32 i = 0; i < numInputs; ++i) { NodePort* inputPort = &mInputPorts[i]; @@ -469,7 +468,7 @@ namespace EMStudio } // draw output port text - const uint32 numOutputs = mOutputPorts.GetLength(); + const uint32 numOutputs = mOutputPorts.size(); for (uint32 i = 0; i < numOutputs; ++i) { NodePort* outputPort = &mOutputPorts[i]; 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..5ce488ee70 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 @@ -346,11 +346,11 @@ namespace EMStudio // add all parameters // uint32 startRow = 0; - mParameterInfos.Clear(); + mParameterInfos.clear(); const EMotionFX::ValueParameterVector& parameters = animGraph->RecursivelyGetValueParameters(); const size_t numParameters = parameters.size(); - mParameterInfos.Reserve(static_cast(numParameters)); + mParameterInfos.reserve(static_cast(numParameters)); for (size_t parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex) { @@ -478,7 +478,7 @@ namespace EMStudio paramInfo.mMode = modeComboBox; paramInfo.mInvert = invertCheckbox; paramInfo.mValue = valueEdit; - mParameterInfos.Add(paramInfo); + mParameterInfos.emplace_back(paramInfo); // update the interface UpdateParameterInterface(¶mInfo); @@ -490,7 +490,7 @@ namespace EMStudio mButtonGridLayout->setMargin(0); // clear the button infos - mButtonInfos.Clear(); + mButtonInfos.clear(); // get the number of buttons and iterate through them #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER @@ -520,15 +520,15 @@ namespace EMStudio modeComboBox->setCurrentIndex(settingsInfo->m_mode); mButtonGridLayout->addWidget(modeComboBox, i, 1); - mButtonInfos.Add(ButtonInfo(i, modeComboBox)); + mButtonInfos.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); + mPreviewLabels.clear(); + mPreviewLabels.resize(GameController::NUM_ELEMENTS + 1); QVBoxLayout* realtimePreviewLayout = new QVBoxLayout(); QGridLayout* previewGridLayout = new QGridLayout(); previewGridLayout->setAlignment(Qt::AlignTop); @@ -701,7 +701,7 @@ namespace EMStudio GameControllerWindow::ButtonInfo* GameControllerWindow::FindButtonInfo(QWidget* widget) { // get the number of button infos and iterate through them - const uint32 numButtonInfos = mButtonInfos.GetLength(); + const uint32 numButtonInfos = mButtonInfos.size(); for (uint32 i = 0; i < numButtonInfos; ++i) { if (mButtonInfos[i].mWidget == widget) @@ -718,7 +718,7 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByModeComboBox(QComboBox* comboBox) { // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.GetLength(); + const uint32 numParamInfos = mParameterInfos.size(); for (uint32 i = 0; i < numParamInfos; ++i) { if (mParameterInfos[i].mMode == comboBox) @@ -736,7 +736,7 @@ 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(); + const uint32 numParamInfos = mParameterInfos.size(); for (uint32 i = 0; i < numParamInfos; ++i) { if (mParameterInfos[i].mParameter == parameter) @@ -1154,7 +1154,7 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByAxisComboBox(QComboBox* comboBox) { // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.GetLength(); + const uint32 numParamInfos = mParameterInfos.size(); for (uint32 i = 0; i < numParamInfos; ++i) { if (mParameterInfos[i].mAxis == comboBox) @@ -1232,7 +1232,7 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByCheckBox(QCheckBox* checkBox) { // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.GetLength(); + const uint32 numParamInfos = mParameterInfos.size(); for (uint32 i = 0; i < numParamInfos; ++i) { if (mParameterInfos[i].mInvert == checkBox) 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..c9ea776337 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 @@ -154,9 +154,9 @@ namespace EMStudio void UpdateGameControllerComboBox(); AnimGraphPlugin* mPlugin; - MCore::Array mPreviewLabels; - MCore::Array mParameterInfos; - MCore::Array mButtonInfos; + AZStd::vector mPreviewLabels; + AZStd::vector mParameterInfos; + AZStd::vector mButtonInfos; QBasicTimer mInterfaceTimer; QBasicTimer mGameControllerTimer; AZ::Debug::Timer mDeltaTimer; 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..6bf1c4d45a 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 @@ -25,10 +25,6 @@ namespace EMStudio GraphNode::GraphNode(const QModelIndex& modelIndex, const char* name, uint32 numInputs, uint32 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); @@ -66,8 +62,8 @@ namespace EMStudio mTextOptionsAlignRight.setAlignment(Qt::AlignRight | Qt::AlignVCenter); mTextOptionsAlignLeft.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); - mInputPorts.Resize(numInputs); - mOutputPorts.Resize(numOutputs); + mInputPorts.resize(numInputs); + mOutputPorts.resize(numOutputs); // initialize the port metrics mPortFontMetrics = new QFontMetrics(mPortNameFont); @@ -123,8 +119,8 @@ namespace EMStudio mInfoText.prepare(QTransform(), mSubTitleFont); // input ports - const uint32 numInputs = mInputPorts.GetLength(); - mInputPortText.Resize(numInputs); + const uint32 numInputs = mInputPorts.size(); + mInputPortText.resize(numInputs); for (uint32 i = 0; i < numInputs; ++i) { QStaticText& staticText = mInputPortText[i]; @@ -136,8 +132,8 @@ namespace EMStudio } // output ports - const uint32 numOutputs = mOutputPorts.GetLength(); - mOutputPortText.Resize(numOutputs); + const uint32 numOutputs = mOutputPorts.size(); + mOutputPortText.resize(numOutputs); for (uint32 i = 0; i < numOutputs; ++i) { QStaticText& staticText = mOutputPortText[i]; @@ -241,13 +237,13 @@ namespace EMStudio // remove all node connections void GraphNode::RemoveAllConnections() { - const uint32 numConnections = mConnections.GetLength(); + const uint32 numConnections = mConnections.size(); for (uint32 i = 0; i < numConnections; ++i) { delete mConnections[i]; } - mConnections.Clear(); + mConnections.clear(); } @@ -338,7 +334,7 @@ namespace EMStudio // update the input ports and reset the port highlight flags uint32 i; - const uint32 numInputPorts = mInputPorts.GetLength(); + const uint32 numInputPorts = mInputPorts.size(); for (i = 0; i < numInputPorts; ++i) { mInputPorts[i].SetRect(CalcInputPortRect(i)); @@ -346,7 +342,7 @@ namespace EMStudio } // update the output ports and reset the port highlight flags - const uint32 numOutputPorts = mOutputPorts.GetLength(); + const uint32 numOutputPorts = mOutputPorts.size(); for (i = 0; i < numOutputPorts; ++i) { mOutputPorts[i].SetRect(CalcOutputPortRect(i)); @@ -574,7 +570,7 @@ namespace EMStudio // draw the input ports QColor portBrushColor, portPenColor; - const uint32 numInputs = mInputPorts.GetLength(); + const uint32 numInputs = mInputPorts.size(); for (uint32 i = 0; i < numInputs; ++i) { // get the input port and the corresponding rect @@ -599,7 +595,7 @@ namespace EMStudio if (GetHasVisualOutputPorts()) { // draw the output ports - const uint32 numOutputs = mOutputPorts.GetLength(); + const uint32 numOutputs = mOutputPorts.size(); for (uint32 i = 0; i < numOutputs; ++i) { // get the output port and the corresponding rect @@ -827,7 +823,7 @@ namespace EMStudio const bool alwaysColor = GetAlwaysColor(); // for all connections - const uint32 numConnections = mConnections.GetLength(); + const uint32 numConnections = mConnections.size(); for (uint32 c = 0; c < numConnections; ++c) { NodeConnection* nodeConnection = mConnections[c]; @@ -922,7 +918,7 @@ namespace EMStudio { if (mIsCollapsed == false) { - uint32 numPorts = MCore::Max(mInputPorts.GetLength(), mOutputPorts.GetLength()); + uint32 numPorts = MCore::Max(mInputPorts.size(), mOutputPorts.size()); uint32 result = (numPorts * 15) + 34; return MCore::Math::Align(result, 10); } @@ -939,7 +935,7 @@ namespace EMStudio // calc the maximum input port width uint32 maxInputWidth = 0; uint32 width; - const uint32 numInputPorts = mInputPorts.GetLength(); + const uint32 numInputPorts = mInputPorts.size(); for (uint32 i = 0; i < numInputPorts; ++i) { const NodePort* nodePort = &mInputPorts[i]; @@ -956,7 +952,7 @@ namespace EMStudio // calc the maximum output port width uint32 width; uint32 maxOutputWidth = 0; - const uint32 numOutputPorts = mOutputPorts.GetLength(); + const uint32 numOutputPorts = mOutputPorts.size(); for (uint32 i = 0; i < numOutputPorts; ++i) { width = mPortFontMetrics->horizontalAdvance(mOutputPorts[i].GetName()); @@ -1052,40 +1048,40 @@ namespace EMStudio // remove all input ports void GraphNode::RemoveAllInputPorts() { - mInputPorts.Clear(false); + mInputPorts.clear(); } // remove all output ports void GraphNode::RemoveAllOutputPorts() { - mOutputPorts.Clear(false); + mOutputPorts.clear(); } // add a new input port NodePort* GraphNode::AddInputPort(bool updateTextPixMap) { - mInputPorts.AddEmpty(); - mInputPorts.GetLast().SetNode(this); + mInputPorts.emplace_back(); + mInputPorts.back().SetNode(this); if (updateTextPixMap) { UpdateTextPixmap(); } - return &mInputPorts.GetLast(); + return &mInputPorts.back(); } // add a new output port NodePort* GraphNode::AddOutputPort(bool updateTextPixMap) { - mOutputPorts.AddEmpty(); - mOutputPorts.GetLast().SetNode(this); + mOutputPorts.emplace_back(); + mOutputPorts.back().SetNode(this); if (updateTextPixMap) { UpdateTextPixmap(); } - return &mOutputPorts.GetLast(); + return &mOutputPorts.back(); } /* @@ -1129,7 +1125,7 @@ namespace EMStudio // check the input ports if (includeInputPorts) { - const uint32 numInputPorts = mInputPorts.GetLength(); + const uint32 numInputPorts = mInputPorts.size(); for (i = 0; i < numInputPorts; ++i) { QRect rect = CalcInputPortRect(i); @@ -1143,7 +1139,7 @@ namespace EMStudio } // check the output ports - const uint32 numOutputPorts = mOutputPorts.GetLength(); + const uint32 numOutputPorts = mOutputPorts.size(); for (i = 0; i < numOutputPorts; ++i) { QRect rect = CalcOutputPortRect(i); @@ -1161,7 +1157,7 @@ namespace EMStudio // remove a given connection bool GraphNode::RemoveConnection(const void* connection, bool removeFromMemory) { - const uint32 numConnections = mConnections.GetLength(); + const uint32 numConnections = mConnections.size(); for (uint32 i = 0; i < numConnections; ++i) { // if this is the connection we're searching for @@ -1171,7 +1167,7 @@ namespace EMStudio { delete mConnections[i]; } - mConnections.Remove(i); + mConnections.erase(AZStd::next(begin(mConnections), i)); return true; } } @@ -1182,7 +1178,7 @@ namespace EMStudio // Remove a given connection by model index bool GraphNode::RemoveConnection(const QModelIndex& modelIndex, bool removeFromMemory) { - const uint32 numConnections = mConnections.GetLength(); + const uint32 numConnections = mConnections.size(); for (uint32 i = 0; i < numConnections; ++i) { // if this is the connection we're searching for @@ -1192,7 +1188,7 @@ namespace EMStudio { delete mConnections[i]; } - mConnections.Remove(i); + mConnections.erase(AZStd::next(begin(mConnections), i)); return true; } } 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..ba6be3de28 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" @@ -44,7 +44,6 @@ 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(); } @@ -85,10 +84,10 @@ namespace EMStudio 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 AZStd::vector& GetConnections() { return mConnections; } + MCORE_INLINE size_t GetNumConnections() { return mConnections.size(); } MCORE_INLINE NodeConnection* GetConnection(uint32 index) { return mConnections[index]; } - MCORE_INLINE NodeConnection* AddConnection(NodeConnection* con) { mConnections.Add(con); return con; } + MCORE_INLINE NodeConnection* AddConnection(NodeConnection* con) { mConnections.emplace_back(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]; } @@ -135,8 +134,8 @@ namespace EMStudio MCORE_INLINE float GetOpacity() const { return mOpacity; } MCORE_INLINE void SetOpacity(float opacity) { mOpacity = opacity; } - uint32 GetNumInputPorts() const { return mInputPorts.GetLength(); } - uint32 GetNumOutputPorts() const { return mOutputPorts.GetLength(); } + size_t GetNumInputPorts() const { return mInputPorts.size(); } + size_t GetNumOutputPorts() const { return mOutputPorts.size(); } NodePort* AddInputPort(bool updateTextPixMap); NodePort* AddOutputPort(bool updateTextPixMap); @@ -227,7 +226,7 @@ namespace EMStudio QColor mBorderColor; QColor mVisualizeColor; QColor mHasChildIndicatorColor; - MCore::Array mConnections; + AZStd::vector mConnections; float mOpacity; bool mIsVisible; static QColor mPortHighlightColor; @@ -251,15 +250,15 @@ namespace EMStudio QStaticText mSubTitleText; QStaticText mInfoText; - MCore::Array mInputPortText; - MCore::Array mOutputPortText; + AZStd::vector mInputPortText; + AZStd::vector mOutputPortText; int32 mRequiredWidth; bool mNameAndPortsUpdated; NodeGraph* mParentGraph; - MCore::Array mInputPorts; - MCore::Array mOutputPorts; + AZStd::vector mInputPorts; + AZStd::vector mOutputPorts; bool mConFromOutputOnly; bool mIsDeletable; bool mIsCollapsed; 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..39a9a0630d 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 @@ -2013,8 +2013,8 @@ 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(); + AZStd::vector& connections = target.second->GetConnections(); + const uint32 connectionsCount = connections.size(); for (uint32 i = 0; i < connectionsCount; ++i) { if (connections[i]->GetType() == StateConnection::TYPE_ID) @@ -2023,7 +2023,7 @@ namespace EMStudio if (visualStateConnection->GetModelIndex() == modelIndex) { delete connections[i]; - connections.Remove(i); + connections.erase(AZStd::next(begin(connections), i)); break; } } @@ -2086,8 +2086,8 @@ namespace EMStudio GraphNode* targetGraphNode = FindGraphNode(targetNode); bool foundConnection = false; - MCore::Array& connections = targetGraphNode->GetConnections(); - const uint32 connectionsCount = connections.GetLength(); + AZStd::vector& connections = targetGraphNode->GetConnections(); + const uint32 connectionsCount = connections.size(); for (uint32 i = 0; i < connectionsCount; ++i) { if (connections[i]->GetType() == StateConnection::TYPE_ID) @@ -2110,13 +2110,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,8 +2174,8 @@ 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(); + AZStd::vector& connections = target.second->GetConnections(); + const uint32 connectionsCount = connections.size(); for (uint32 i = 0; i < connectionsCount; ++i) { if (connections[i]->GetType() == StateConnection::TYPE_ID) @@ -2205,8 +2203,8 @@ namespace EMStudio GraphNode* target = FindGraphNode(parentModelIndex); if (target) { - MCore::Array& connections = target->GetConnections(); - const uint32 connectionsCount = connections.GetLength(); + AZStd::vector& connections = target->GetConnections(); + const uint32 connectionsCount = connections.size(); for (uint32 i = 0; i < connectionsCount; ++i) { if (connections[i]->GetType() == NodeConnection::TYPE_ID) 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..51b170c5aa 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,6 +8,7 @@ #include #include +#include #include #include #include @@ -160,8 +161,6 @@ namespace EMStudio mTableWidget = nullptr; mAddAction = nullptr; - mWidgetTable.SetMemoryCategory(MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - // create and register the command callbacks mCreateCallback = new CommandAnimGraphAddNodeGroupCallback(false); mRemoveCallback = new CommandAnimGraphRemoveNodeGroupCallback(false); @@ -280,7 +279,7 @@ namespace EMStudio void NodeGroupWindow::Init() { // selected node groups array - MCore::Array selectedNodeGroups; + AZStd::vector selectedNodeGroups; // get the current selection const QList selectedItems = mTableWidget->selectedItems(); @@ -289,19 +288,19 @@ namespace EMStudio const uint32 numSelectedItems = selectedItems.count(); // filter the items - selectedNodeGroups.Reserve(numSelectedItems); + selectedNodeGroups.reserve(numSelectedItems); for (uint32 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) + if (AZStd::find(begin(selectedNodeGroups), end(selectedNodeGroups), nodeGroupName) == end(selectedNodeGroups)) { - selectedNodeGroups.Add(nodeGroupName); + selectedNodeGroups.emplace_back(nodeGroupName); } } // clear the lookup array - mWidgetTable.Clear(false); + mWidgetTable.clear(); // get the anim graph EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); @@ -331,7 +330,7 @@ namespace EMStudio 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; @@ -365,7 +364,7 @@ namespace EMStudio colorLayout->addWidget(colorWidget); colorLayoutWidget->setLayout(colorLayout); - mWidgetTable.Add(WidgetLookup(colorWidget, i)); + mWidgetTable.emplace_back(WidgetLookup{colorWidget, i}); connect(colorWidget, &AzQtComponents::ColorLabel::colorChanged, this, &NodeGroupWindow::OnColorChanged); // add the color label in the table @@ -456,7 +455,7 @@ namespace EMStudio uint32 NodeGroupWindow::FindGroupIndexByWidget(QObject* widget) const { // for all table entries - const uint32 numWidgets = mWidgetTable.GetLength(); + const uint32 numWidgets = mWidgetTable.size(); for (uint32 i = 0; i < numWidgets; ++i) { if (mWidgetTable[i].mWidget == widget) // this is button we search for @@ -582,23 +581,23 @@ namespace EMStudio } // filter the items - MCore::Array rowIndices; - rowIndices.Reserve(numSelectedItems); + AZStd::vector rowIndices; + rowIndices.reserve(numSelectedItems); for (uint32 i = 0; i < numSelectedItems; ++i) { const uint32 rowIndex = selectedItems[i]->row(); - if (rowIndices.Find(rowIndex) == MCORE_INVALIDINDEX32) + 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 uint32 numRowIndices = rowIndices.size(); // set the command group name AZStd::string commandGroupName; @@ -731,14 +730,14 @@ namespace EMStudio } // filter the items - MCore::Array rowIndices; - rowIndices.Reserve(numSelectedItems); + AZStd::vector rowIndices; + rowIndices.reserve(numSelectedItems); for (uint32 i = 0; i < numSelectedItems; ++i) { const uint32 rowIndex = selectedItems[i]->row(); - if (rowIndices.Find(rowIndex) == MCORE_INVALIDINDEX32) + if (AZStd::find(begin(rowIndices), end(rowIndices), rowIndex) == end(rowIndices)) { - rowIndices.Add(rowIndex); + rowIndices.emplace_back(rowIndex); } } @@ -746,14 +745,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.size() > 0) { 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..5f0354b223 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 @@ -104,15 +104,8 @@ namespace EMStudio 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; - } }; AnimGraphPlugin* mPlugin; @@ -121,6 +114,6 @@ namespace EMStudio QAction* mAddAction; AzQtComponents::FilteredSearchWidget* m_searchWidget; AZStd::string m_searchWidgetText; - MCore::Array mWidgetTable; + AZStd::vector mWidgetTable; }; } // 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..25e717f473 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 @@ -28,7 +28,7 @@ namespace EMStudio * 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( mParameterSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); */ class ParameterSelectionWindow : public QDialog 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..0c4f8b8138 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 @@ -649,8 +649,8 @@ namespace EMStudio // mTextOptions.setAlignment( Qt::AlignCenter ); - mInputPorts.Resize(1); - mOutputPorts.Resize(4); + mInputPorts.resize(1); + mOutputPorts.resize(4); } StateGraphNode::~StateGraphNode() @@ -856,7 +856,6 @@ namespace EMStudio MCORE_ASSERT(false); return QRect(); } - ; //MCore::LOG("CalcOutputPortRect: (%i, %i, %i, %i)", rect.top(), rect.left(), rect.bottom(), rect.right()); } 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..3b24552035 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 @@ -110,8 +110,8 @@ namespace EMStudio 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(mNodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &AttachmentNodesWindow::NodeSelectionFinished); + connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnDoubleClicked, this, &AttachmentNodesWindow::NodeSelectionFinished); } @@ -322,10 +322,10 @@ namespace EMStudio // 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.size() == 0) { return; } @@ -333,7 +333,7 @@ namespace EMStudio // generate node list string AZStd::string nodeList; nodeList.reserve(16384); - const uint32 numSelectedNodes = selectionList.GetLength(); + const uint32 numSelectedNodes = selectionList.size(); for (uint32 i = 0; i < numSelectedNodes; ++i) { nodeList += AZStd::string::format("%s;", selectionList[i].GetNodeName()); 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..3a3c3f096e 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: 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..c78d37dd7b 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 @@ -204,7 +204,7 @@ namespace EMStudio 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->GetNodeHierarchyWidget(), &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); @@ -766,10 +766,10 @@ namespace EMStudio // 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; 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..b3bd45fb22 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 @@ -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(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp index b4bef2faea..51c7e1d8de 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp @@ -6,6 +6,7 @@ * */ +#include #include "LogWindowCallback.h" #include #include @@ -289,22 +290,22 @@ namespace EMStudio } // filter the items - MCore::Array rowIndices; - rowIndices.Reserve(numSelectedItems); + AZStd::vector rowIndices; + rowIndices.reserve(numSelectedItems); for (uint32 i = 0; i < numSelectedItems; ++i) { const uint32 rowIndex = items[i]->row(); - if (rowIndices.Find(rowIndex) == MCORE_INVALIDINDEX32) + 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 uint32 numSelectedRows = rowIndices.size(); // genereate the clipboard text QString clipboardText; 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..441c9555a7 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 @@ -33,7 +33,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,7 +70,7 @@ namespace EMStudio tableWidget->verticalHeader()->setVisible(false); // set the number of rows - const uint32 numMotions = motions.GetLength(); + const uint32 numMotions = motions.size(); tableWidget->setRowCount(numMotions); // add each motion in the table 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..368f5bd9c7 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); }; 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..ac284a5777 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 @@ -130,7 +130,7 @@ namespace EMStudio // create the node selection windows mMotionExtractionNodeSelectionWindow = new NodeSelectionWindow(this, true); - connect(mMotionExtractionNodeSelectionWindow->GetNodeHierarchyWidget(), static_cast)>(&NodeHierarchyWidget::OnSelectionDone), this, &MotionExtractionWindow::OnMotionExtractionNodeSelected); + connect(mMotionExtractionNodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &MotionExtractionWindow::OnMotionExtractionNodeSelected); // set some layout for our window mMainVerticalLayout = new QVBoxLayout(); @@ -393,7 +393,7 @@ namespace EMStudio } - 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..cb7371a74d 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 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..481718ab66 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,7 @@ // inlude required headers #include "NodeGroupWidget.h" #include "../../../../EMStudioSDK/Source/EMStudioManager.h" +#include "AzCore/std/iterator.h" #include #include @@ -127,11 +128,8 @@ namespace EMStudio 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(mNodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &NodeGroupWidget::NodeSelectionFinished); + connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnDoubleClicked, this, &NodeGroupWidget::NodeSelectionFinished); } @@ -334,21 +332,21 @@ namespace EMStudio // add / select nodes - void NodeGroupWidget::NodeSelectionFinished(MCore::Array selectionList) + void NodeGroupWidget::NodeSelectionFinished(AZStd::vector selectionList) { // return if no nodes are selected - if (selectionList.GetLength() == 0) + if (selectionList.size() == 0) { 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( 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..f128fd8082 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(AZStd::vector selectionList); void OnItemSelectionChanged(); private: 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..3d7e44dac3 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 @@ -292,7 +292,7 @@ namespace EMStudio 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 @@ -308,7 +308,7 @@ namespace EMStudio const uint32 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/SceneManager/ActorPropertiesWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.cpp index 04fbc9e412..cc5811b1f7 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 @@ -215,30 +215,6 @@ namespace EMStudio 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; - } - void ActorPropertiesWindow::GetNodeName(const AZStd::vector& joints, AZStd::string* outNodeName, uint32* outActorID) { outNodeName->clear(); 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..67568d80b0 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: 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..271f277ed1 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 @@ -525,7 +525,7 @@ namespace EMStudio typeItem->setIcon(*mMeshIcon); } else - if (mCurrentBoneList.Contains(node->GetNodeIndex())) + if (AZStd::find(begin(mCurrentBoneList), end(mCurrentBoneList), node->GetNodeIndex()) != end(mCurrentBoneList)) { typeItem->setIcon(*mBoneIcon); } 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..13bb98334c 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 @@ -79,7 +79,7 @@ namespace EMStudio QIcon* mNodeIcon; QIcon* mMeshIcon; QIcon* mMappedIcon; - MCore::Array mCurrentBoneList; + AZStd::vector mCurrentBoneList; AZStd::vector mSourceBoneList; AZStd::vector mMap; 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..e909e9ead3 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 @@ -107,7 +107,7 @@ namespace EMStudio delete mZoomOutCursor; // get rid of the motion infos - const uint32 numMotionInfos = mMotionInfos.GetLength(); + const uint32 numMotionInfos = mMotionInfos.size(); for (uint32 i = 0; i < numMotionInfos; ++i) { delete mMotionInfos[i]; @@ -285,7 +285,7 @@ namespace EMStudio // add a new track void TimeViewPlugin::AddTrack(TimeTrack* track) { - mTracks.Add(track); + mTracks.emplace_back(track); SetRedrawFlag(); } @@ -294,20 +294,20 @@ namespace EMStudio void TimeViewPlugin::RemoveAllTracks() { // get the number of time tracks and iterate through them - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 i = 0; i < numTracks; ++i) { delete mTracks[i]; } - mTracks.Clear(); + mTracks.clear(); SetRedrawFlag(); } TimeTrack* TimeViewPlugin::FindTrackByElement(TimeTrackElement* element) const { // get the number of time tracks and iterate through them - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 i = 0; i < numTracks; ++i) { TimeTrack* timeTrack = mTracks[i]; @@ -328,7 +328,7 @@ namespace EMStudio AZ::Outcome TimeViewPlugin::FindTrackIndex(const TimeTrack* track) const { - const AZ::u32 numTracks = mTracks.GetLength(); + const AZ::u32 numTracks = mTracks.size(); for (AZ::u32 i = 0; i < numTracks; ++i) { if (mTracks[i] == track) @@ -472,7 +472,7 @@ namespace EMStudio TimeTrackElement* TimeViewPlugin::GetElementAt(int32 x, int32 y) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 i = 0; i < numTracks; ++i) { // check if the absolute pixel is inside @@ -491,7 +491,7 @@ namespace EMStudio TimeTrack* TimeViewPlugin::GetTrackAt(int32 y) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 i = 0; i < numTracks; ++i) { // check if the absolute pixel is inside @@ -509,7 +509,7 @@ namespace EMStudio void TimeViewPlugin::UnselectAllElements() { // for all tracks - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 t = 0; t < numTracks; ++t) { TimeTrack* track = mTracks[t]; @@ -603,7 +603,7 @@ namespace EMStudio } // for all tracks - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 t = 0; t < numTracks; ++t) { TimeTrack* track = mTracks[t]; @@ -646,7 +646,7 @@ namespace EMStudio void TimeViewPlugin::RenderElementTimeHandles(QPainter& painter, uint32 dataWindowHeight, const QPen& pen) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 t = 0; t < numTracks; ++t) { TimeTrack* track = mTracks[t]; @@ -682,7 +682,7 @@ namespace EMStudio void TimeViewPlugin::DisableAllToolTips() { // for all tracks - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 t = 0; t < numTracks; ++t) { TimeTrack* track = mTracks[t]; @@ -703,7 +703,7 @@ namespace EMStudio bool TimeViewPlugin::FindResizePoint(int32 x, int32 y, TimeTrackElement** outElement, uint32* outID) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 t = 0; t < numTracks; ++t) { TimeTrack* track = mTracks[t]; @@ -1179,7 +1179,7 @@ namespace EMStudio void TimeViewPlugin::UpdateSelection() { - mSelectedEvents.Clear(false); + mSelectedEvents.clear(); if (!mMotion) { return; @@ -1221,7 +1221,7 @@ namespace EMStudio selectionItem.mMotion = mMotion; selectionItem.mTrackNr = trackNr.GetValue(); selectionItem.mEventNr = element->GetElementNumber(); - mSelectedEvents.Add(selectionItem); + mSelectedEvents.emplace_back(selectionItem); } } } @@ -1298,7 +1298,7 @@ namespace EMStudio } // Select the element if in mSelectedEvents. - const AZ::u32 numSelectedEvents = mSelectedEvents.GetLength(); + const AZ::u32 numSelectedEvents = mSelectedEvents.size(); for (AZ::u32 selectedEventIndex = 0; selectedEventIndex < numSelectedEvents; ++selectedEventIndex) { const EventSelectionItem& selectionItem = mSelectedEvents[selectedEventIndex]; @@ -1447,7 +1447,7 @@ namespace EMStudio // find the motion info for the given motion id TimeViewPlugin::MotionInfo* TimeViewPlugin::FindMotionInfo(uint32 motionID) { - const uint32 numMotionInfos = mMotionInfos.GetLength(); + const uint32 numMotionInfos = mMotionInfos.size(); for (uint32 i = 0; i < numMotionInfos; ++i) { MotionInfo* motionInfo = mMotionInfos[i]; @@ -1462,12 +1462,12 @@ namespace EMStudio MotionInfo* motionInfo = new MotionInfo(); motionInfo->mMotionID = motionID; motionInfo->mInitialized = false; - mMotionInfos.Add(motionInfo); + mMotionInfos.emplace_back(motionInfo); return motionInfo; } - void TimeViewPlugin::Select(const MCore::Array& selection) + void TimeViewPlugin::Select(const AZStd::vector& selection) { uint32 i; @@ -1488,7 +1488,7 @@ namespace EMStudio } } - const uint32 numSelectedEvents = selection.GetLength(); + const uint32 numSelectedEvents = selection.size(); for (i = 0; i < numSelectedEvents; ++i) { const EventSelectionItem* selectionItem = &selection[i]; @@ -1643,7 +1643,7 @@ namespace EMStudio // 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(); @@ -1656,7 +1656,7 @@ 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(); @@ -1666,7 +1666,7 @@ namespace EMStudio if (element->GetIsSelected() && element->GetIsVisible()) { - eventNumbers.Add(j); + eventNumbers.emplace_back(j); } } @@ -1702,7 +1702,7 @@ namespace EMStudio // 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(); @@ -1715,7 +1715,7 @@ 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(); @@ -1724,7 +1724,7 @@ namespace EMStudio TimeTrackElement* element = track->GetElement(j); if (element->GetIsVisible()) { - eventNumbers.Add(j); + eventNumbers.emplace_back(j); } } @@ -1928,7 +1928,7 @@ namespace EMStudio { if (mMotion) { - const uint32 numTracks = mTracks.GetLength(); + const uint32 numTracks = mTracks.size(); for (uint32 i = 0; i < numTracks; ++i) { TimeTrack* track = mTracks[i]; 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..386117d3a3 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,8 +36,6 @@ namespace EMStudio struct EventSelectionItem { - MCORE_MEMORYOBJECTCATEGORY(EventSelectionItem, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS); - EMotionFX::MotionEvent* GetMotionEvent(); EMotionFX::MotionEventTrack* GetEventTrack(); @@ -118,7 +116,7 @@ namespace EMStudio void AddTrack(TimeTrack* track); void RemoveAllTracks(); TimeTrack* GetTrack(uint32 index) { return mTracks[index]; } - uint32 GetNumTracks() const { return mTracks.GetLength(); } + size_t GetNumTracks() const { return mTracks.size(); } AZ::Outcome FindTrackIndex(const TimeTrack* track) const; TimeTrack* FindTrackByElement(TimeTrackElement* element) const; @@ -153,10 +151,10 @@ namespace EMStudio void ZoomRect(const QRect& rect); - uint32 GetNumSelectedEvents() { return mSelectedEvents.GetLength(); } + size_t GetNumSelectedEvents() { return mSelectedEvents.size(); } EventSelectionItem GetSelectedEvent(uint32 index) const { return mSelectedEvents[index]; } - void Select(const MCore::Array& selection); + void Select(const AZStd::vector& selection); MCORE_INLINE EMotionFX::Motion* GetMotion() const { return mMotion; } void SetRedrawFlag(); @@ -220,7 +218,7 @@ namespace EMStudio MotionEventsPlugin* mMotionEventsPlugin; MotionListWindow* mMotionListWindow; MotionSetsWindowPlugin* m_motionSetPlugin; - MCore::Array mSelectedEvents; + AZStd::vector mSelectedEvents; EMotionFX::Recorder::ActorInstanceData* mActorInstanceData; EMotionFX::Recorder::NodeHistoryItem* mNodeHistoryItem; @@ -238,8 +236,8 @@ namespace EMStudio MotionInfo* FindMotionInfo(uint32 motionID); void UpdateCurrentMotionInfo(); - MCore::Array mMotionInfos; - MCore::Array mTracks; + AZStd::vector mMotionInfos; + AZStd::vector mTracks; double mPixelsPerSecond; // pixels per second double mScrollX; // horizontal scroll offset 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..30fa3a741e 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 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..fc60867864 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 @@ -341,7 +341,7 @@ namespace EMStudio painter.setRenderHint(QPainter::Antialiasing, true); // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; int32 windowWidth = geometry().width(); RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); @@ -369,7 +369,7 @@ namespace EMStudio const uint32 graphContentsCode = mPlugin->mTrackHeaderWidget->mGraphContentsComboBox->currentIndex(); - const uint32 numItems = historyItems.GetLength(); + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { EMotionFX::Recorder::NodeHistoryItem* curItem = historyItems[i]; @@ -456,7 +456,7 @@ namespace EMStudio // display the values and names uint32 offset = 0; - const uint32 numActiveItems = mActiveItems.GetLength(); + const uint32 numActiveItems = mActiveItems.size(); for (uint32 i = 0; i < numActiveItems; ++i) { EMotionFX::Recorder::NodeHistoryItem* curItem = mActiveItems[i].mNodeHistoryItem; @@ -516,7 +516,7 @@ namespace EMStudio } // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->mEventHistoryItems; QRect clipRect = rect; clipRect.setRight(aznumeric_cast(mPlugin->TimeToPixel(animationLength))); @@ -528,7 +528,7 @@ namespace EMStudio const float tickHeight = 16; QPointF tickPoints[6]; - const uint32 numItems = historyItems.GetLength(); + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { EMotionFX::Recorder::EventHistoryItem* curItem = historyItems[i]; @@ -620,7 +620,7 @@ namespace EMStudio } // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; int32 windowWidth = geometry().width(); // calculate the remapped track list, based on sorted global weight, with the most influencing track on top @@ -639,7 +639,7 @@ namespace EMStudio // for all history items QRectF itemRect; - const uint32 numItems = historyItems.GetLength(); + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { EMotionFX::Recorder::NodeHistoryItem* curItem = historyItems[i]; @@ -923,7 +923,7 @@ namespace EMStudio visibleEndTime = mPlugin->PixelToTime(width); //mPlugin->CalcTime( width, &visibleEndTime, nullptr, nullptr, nullptr, nullptr ); // for all tracks - const uint32 numTracks = mPlugin->mTracks.GetLength(); + const uint32 numTracks = mPlugin->mTracks.size(); for (uint32 i = 0; i < numTracks; ++i) { TimeTrack* track = mPlugin->mTracks[i]; @@ -1916,7 +1916,7 @@ namespace EMStudio return; } - MCore::Array eventNumbers; + AZStd::vector eventNumbers; // calculate the number of selected events const uint32 numEvents = timeTrack->GetNumElements(); @@ -1927,7 +1927,7 @@ namespace EMStudio // increase the counter in case the element is selected if (element->GetIsSelected()) { - eventNumbers.Add(i); + eventNumbers.emplace_back(i); } } @@ -1950,13 +1950,13 @@ namespace EMStudio 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) { - eventNumbers.Add(i); + eventNumbers.emplace_back(i); } // remove the motion events @@ -2315,7 +2315,7 @@ namespace EMStudio // if we recorded node history mNodeHistoryRect = QRect(); - if (actorInstanceData && actorInstanceData->mNodeHistoryItems.GetLength() > 0) + if (actorInstanceData && actorInstanceData->mNodeHistoryItems.size() > 0) { const uint32 height = (recorder.CalcMaxNodeHistoryTrackIndex(*actorInstanceData) + 1) * (mNodeHistoryItemHeight + 3) + mNodeRectsStartHeight; mNodeHistoryRect.setTop(mNodeRectsStartHeight); @@ -2325,7 +2325,7 @@ namespace EMStudio } mEventHistoryTotalHeight = 0; - if (actorInstanceData && actorInstanceData->mEventHistoryItems.GetLength() > 0) + if (actorInstanceData && actorInstanceData->mEventHistoryItems.size() > 0) { mEventHistoryTotalHeight = (recorder.CalcMaxEventHistoryTrackIndex(*actorInstanceData) + 1) * 20; } @@ -2353,10 +2353,10 @@ namespace EMStudio // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; QRect rect; - const uint32 numItems = historyItems.GetLength(); + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { EMotionFX::Recorder::NodeHistoryItem* curItem = historyItems[i]; @@ -2462,20 +2462,20 @@ namespace EMStudio EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(item->mNodeId); if (node) { - 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 (uint32 i = 0; i < nodePath.size(); ++i) { nodePathString += nodePath[i]->GetName(); - if (i != nodePath.GetLength() - 1) + if (i != nodePath.size() - 1) { nodePathString += " > "; } @@ -2551,11 +2551,11 @@ namespace EMStudio return nullptr; } - const MCore::Array& historyItems = actorInstanceData->mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->mEventHistoryItems; const float tickHalfWidth = 7; const float tickHeight = 16; - const uint32 numItems = historyItems.GetLength(); + const uint32 numItems = historyItems.size(); for (uint32 i = 0; i < numItems; ++i) { EMotionFX::Recorder::EventHistoryItem* curItem = historyItems[i]; @@ -2648,20 +2648,20 @@ namespace EMStudio outString += AZStd::string::format("

Emitted By: 

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

%s

", 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 (uint32 i = 0; i < nodePath.size(); ++i) { nodePathString += nodePath[i]->GetName(); - if (i != nodePath.GetLength() - 1) + if (i != nodePath.size() - 1) { nodePathString += " > "; } 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..2709927254 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 @@ -136,8 +136,8 @@ namespace EMStudio uint32 mNodeRectsStartHeight; double mOldCurrentTime; - MCore::Array mActiveItems; - MCore::Array mTrackRemap; + AZStd::vector mActiveItems; + AZStd::vector mTrackRemap; // copy and paste struct CopyElement 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..363a278b8e 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 @@ -173,7 +173,7 @@ namespace EMStudio setVisible(true); mStackWidget->setVisible(false); - const uint32 numTracks = mPlugin->mTracks.GetLength(); + const uint32 numTracks = mPlugin->mTracks.size(); if (numTracks == 0) { return; 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/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/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/LogManager.cpp b/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp index a4e0a71cee..ecf4eb9168 100644 --- a/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp @@ -10,8 +10,6 @@ #include #include "LogManager.h" -#include - namespace MCore { // static mutex @@ -60,8 +58,6 @@ namespace MCore // constructor LogManager::LogManager() { - mLogCallbacks.SetMemoryCategory(MCORE_MEMCATEGORY_LOGMANAGER); - // initialize the enabled log levels InitLogLevels(); } @@ -82,7 +78,7 @@ namespace MCore LockGuard lock(mMutex); // add the callback to the stack - mLogCallbacks.Add(callback); + mLogCallbacks.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)); + MCORE_ASSERT(index < mLogCallbacks.size()); LockGuard lock(mMutex); // delete it from memory delete mLogCallbacks[index]; // remove the callback from the stack - mLogCallbacks.Remove(index); + mLogCallbacks.erase(AZStd::next(begin(mLogCallbacks), index)); // collect the enabled log levels InitLogLevels(); @@ -110,25 +106,16 @@ namespace MCore { LockGuard lock(mMutex); - // 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 + mLogCallbacks.erase(AZStd::remove_if(begin(mLogCallbacks), end(mLogCallbacks), [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(); @@ -141,13 +128,12 @@ namespace MCore LockGuard lock(mMutex); // get rid of the callbacks - const uint32 num = mLogCallbacks.GetLength(); - for (uint32 i = 0; i < num; ++i) + for (auto* logCallback : mLogCallbacks) { - delete mLogCallbacks[i]; + delete logCallback; } - mLogCallbacks.Clear(true); + mLogCallbacks.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 number of log callbacks in the stack - uint32 LogManager::GetNumLogCallbacks() const + size_t LogManager::GetNumLogCallbacks() const { - return mLogCallbacks.GetLength(); + return mLogCallbacks.size(); } // collect all enabled log levels @@ -173,10 +159,9 @@ 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 : mLogCallbacks) { - logLevels |= (int32)mLogCallbacks[i]->GetLogLevels(); + logLevels |= (int32)logCallback->GetLogLevels(); } mLogLevels = (LogCallback::ELogLevel)logLevels; @@ -187,10 +172,9 @@ 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 : mLogCallbacks) { - mLogCallbacks[i]->SetLogLevels(logLevels); + logCallback->SetLogLevels(logLevels); } // force set the log manager's log levels to the given one as well @@ -204,23 +188,21 @@ namespace MCore LockGuard lock(mMutex); // iterate through all callbacks - const uint32 num = mLogCallbacks.GetLength(); - for (uint32 i = 0; i < num; ++i) + for (auto* logCallback : mLogCallbacks) { - 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 < mLogCallbacks.size(); ++i) { if (mLogCallbacks[i] == callback) { @@ -228,7 +210,7 @@ namespace MCore } } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } diff --git a/Gems/EMotionFX/Code/MCore/Source/LogManager.h b/Gems/EMotionFX/Code/MCore/Source/LogManager.h index 1f8ac34cae..d5e2316436 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" @@ -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. @@ -252,7 +252,7 @@ namespace MCore static Mutex mGlobalMutex; /**< The multithread mutex, used by some global Log functions. */ private: - Array mLogCallbacks; /**< A collection of log callback instances. */ + AZStd::vector 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. */ }; diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h index dfa99523fb..3a6aaf33c6 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" diff --git a/Gems/EMotionFX/Code/MCore/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index 43a41b4a11..65b0cf6ca6 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -13,7 +13,6 @@ set(FILES Source/Algorithms.h Source/Algorithms.inl Source/AlignedArray.h - Source/Array.h Source/Array2D.h Source/Array2D.inl Source/Attribute.cpp @@ -79,8 +78,6 @@ set(FILES Source/FileSystem.cpp Source/FileSystem.h Source/HashFunctions.h - Source/HashTable.h - Source/HashTable.inl Source/IDGenerator.cpp Source/IDGenerator.h Source/LogManager.cpp diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp index 75d97fa065..36c0edf986 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp @@ -50,32 +50,10 @@ 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"); @@ -102,7 +80,7 @@ namespace MysticQt void DialogStack::Clear() { // destroy the dialogs - mDialogs.Clear(); + mDialogs.clear(); // update the scroll bars UpdateScrollBars(); @@ -123,7 +101,7 @@ namespace MysticQt // add the dialog widget // the splitter is hierarchical : {a, {b, c}} QSplitter* dialogSplitter; - if (mDialogs.GetLength() == 0) + if (mDialogs.empty()) { // add the dialog widget dialogSplitter = mRootSplitter; @@ -138,10 +116,10 @@ namespace MysticQt else { // check if one space is free on the last splitter - if (mDialogs.GetLast().mSplitter->count() == 1) + if (mDialogs.back().mSplitter->count() == 1) { // add the dialog widget - dialogSplitter = mDialogs.GetLast().mSplitter; + dialogSplitter = mDialogs.back().mSplitter; dialogSplitter->addWidget(dialogWidget); // stretch if needed @@ -151,16 +129,16 @@ namespace MysticQt } // less space used by the splitter when the last dialog is closed - if (mDialogs.GetLast().mFrame->isHidden()) + if (mDialogs.back().mFrame->isHidden()) { - mDialogs.GetLast().mSplitter->handle(1)->setFixedHeight(1); - mDialogs.GetLast().mSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); + mDialogs.back().mSplitter->handle(1)->setFixedHeight(1); + mDialogs.back().mSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); } // disable the splitter - if (mDialogs.GetLast().mFrame->isHidden()) + if (mDialogs.back().mFrame->isHidden()) { - mDialogs.GetLast().mSplitter->handle(1)->setDisabled(true); + mDialogs.back().mSplitter->handle(1)->setDisabled(true); } } else // already two dialogs in the splitter @@ -171,24 +149,24 @@ namespace MysticQt dialogSplitter->setChildrenCollapsible(false); // add the current last dialog and the new dialog after - dialogSplitter->addWidget(mDialogs.GetLast().mDialogWidget); + dialogSplitter->addWidget(mDialogs.back().mDialogWidget.get()); dialogSplitter->addWidget(dialogWidget); // stretch if needed - if (mDialogs.GetLast().mMaximizeSize && mDialogs.GetLast().mStretchWhenMaximize) + if (mDialogs.back().mMaximizeSize && mDialogs.back().mStretchWhenMaximize) { dialogSplitter->setStretchFactor(0, 1); } // less space used by the splitter when the last dialog is closed - if (mDialogs.GetLast().mFrame->isHidden()) + if (mDialogs.back().mFrame->isHidden()) { dialogSplitter->handle(1)->setFixedHeight(1); dialogSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); } // disable the splitter - if (mDialogs.GetLast().mFrame->isHidden()) + if (mDialogs.back().mFrame->isHidden()) { dialogSplitter->handle(1)->setDisabled(true); } @@ -200,24 +178,27 @@ namespace MysticQt } // replace the last dialog by the new splitter - mDialogs.GetLast().mSplitter->addWidget(dialogSplitter); + mDialogs.back().mSplitter->addWidget(dialogSplitter); // disable the splitter - const uint32 lastDialogIndex = mDialogs.GetLength() - 1; - if (mDialogs[lastDialogIndex - 1].mFrame->isHidden()) + if (mDialogs.size() > 1) { - mDialogs.GetLast().mSplitter->handle(1)->setDisabled(true); - } + const auto previousDialogIt = mDialogs.end() - 2; + if (previousDialogIt->mFrame->isHidden()) + { + mDialogs.back().mSplitter->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 ((mDialogs.back().mMaximizeSize && mDialogs.back().mStretchWhenMaximize) || (previousDialogIt->mMaximizeSize && previousDialogIt->mStretchWhenMaximize == false)) + { + mDialogs.back().mSplitter->setStretchFactor(1, 1); + } } // set the new splitter of the last dialog - mDialogs.GetLast().mSplitter = dialogSplitter; + mDialogs.back().mSplitter = dialogSplitter; } } @@ -280,17 +261,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; + mDialogs.emplace_back(Dialog{ + /*.mButton =*/ headerButton, + /*.mFrame =*/ frame, + /*.mWidget =*/ widget, + /*.mDialogWidget =*/ AZStd::unique_ptr{dialogWidget}, + /*.mSplitter =*/ dialogSplitter, + /*.mClosable =*/ closable, + /*.mMaximizeSize =*/ maximizeSize, + /*.mStretchWhenMaximize =*/ stretchWhenMaximize, + /*.mMinimumHeightBeforeClose =*/ 0, + /*.mMaximumHeightBeforeClose =*/ 0, + /*.mLayout =*/ layout, + /*.mDialogLayout =*/ dialogLayout, + }); // check if the dialog is closed if (closed) @@ -319,7 +303,7 @@ namespace MysticQt bool DialogStack::Remove(QWidget* widget) { - const uint32 numDialogs = mDialogs.GetLength(); + const uint32 numDialogs = mDialogs.size(); for (uint32 i = 0; i < numDialogs; ++i) { QLayout* layout = mDialogs[i].mFrame->layout(); @@ -333,7 +317,7 @@ namespace MysticQt // TODO : shift all dialogs needed as explained on the previous comment mDialogs[i].mDialogWidget->hide(); mDialogs[i].mDialogWidget->deleteLater(); - mDialogs.Remove(i); + mDialogs.erase(AZStd::next(begin(mDialogs), i)); // update the scroll bars UpdateScrollBars(); @@ -367,7 +351,7 @@ namespace MysticQt // find the dialog that goes with the given button uint32 DialogStack::FindDialog(QPushButton* pushButton) { - const uint32 numDialogs = mDialogs.GetLength(); + const uint32 numDialogs = mDialogs.size(); for (uint32 i = 0; i < numDialogs; ++i) { if (mDialogs[i].mButton == pushButton) @@ -401,20 +385,20 @@ namespace MysticQt 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 (dialogIndex < (mDialogs.size() - 1)) { mDialogs[dialogIndex].mSplitter->handle(1)->setFixedHeight(4); mDialogs[dialogIndex].mSplitter->setStyleSheet("QSplitter::handle{ height: 4px; background: transparent; }"); } // enable the splitter - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialogIndex < (mDialogs.size() - 1)) { mDialogs[dialogIndex].mSplitter->handle(1)->setEnabled(true); } // maximize the size if it's needed - if (mDialogs.GetLength() > 1) + if (mDialogs.size() > 1) { if (mDialogs[dialogIndex].mMaximizeSize) { @@ -440,7 +424,7 @@ namespace MysticQt } // special case if it's not the last dialog - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialogIndex < (mDialogs.size() - 1)) { // if the next dialog is closed, it's needed to expand to the max too if (mDialogs[dialogIndex + 1].mFrame->isHidden()) @@ -489,27 +473,27 @@ namespace MysticQt button->setIcon(GetMysticQt()->FindIcon("Images/Icons/ArrowRightGray.png")); // less space used by the splitter when the dialog is closed - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialogIndex < (mDialogs.size() - 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)) + if (dialogIndex < (mDialogs.size() - 1)) { mDialogs[dialogIndex].mSplitter->handle(1)->setDisabled(true); } // set the first splitter to the min if needed - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialogIndex < (mDialogs.size() - 1)) { static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMin(); } // maximize the first needed to avoid empty space bool findPreviousMaximizedDialogNeeded = true; - const uint32 numDialogs = mDialogs.GetLength(); + const uint32 numDialogs = mDialogs.size(); for (uint32 i = dialogIndex + 1; i < numDialogs; ++i) { if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) @@ -636,7 +620,7 @@ namespace MysticQt QScrollArea::resizeEvent(event); // maximize the first dialog needed - const uint32 numDialogs = mDialogs.GetLength(); + const uint32 numDialogs = mDialogs.size(); const int32 lastDialogIndex = static_cast(numDialogs) - 1; for (int32 i = lastDialogIndex; i >= 0; --i) { @@ -655,7 +639,7 @@ namespace MysticQt // replace an internal widget void DialogStack::ReplaceWidget(QWidget* oldWidget, QWidget* newWidget) { - for (uint32 i = 0; i < mDialogs.GetLength(); ++i) + for (uint32 i = 0; i < mDialogs.size(); ++i) { // go next if the widget is not the same if (mDialogs[i].mWidget != oldWidget) @@ -693,7 +677,7 @@ namespace MysticQt mDialogs[i].mDialogWidget->setFixedHeight(dialogHeight); // set the first splitter to the min if needed - if (i < (mDialogs.GetLength() - 1)) + if (i < (mDialogs.size() - 1)) { static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMin(); } diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h index ddd0796a6d..d5850a8cbf 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h @@ -11,10 +11,11 @@ // #if !defined(Q_MOC_RUN) +#include #include "MysticQtConfig.h" #include #include -#include +#include #endif // forward declarations @@ -36,7 +37,6 @@ namespace MysticQt : public QScrollArea { Q_OBJECT - MCORE_MEMORYOBJECTCATEGORY(DialogStack, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MYSTICQT); public: DialogStack(QWidget* parent = nullptr); @@ -61,21 +61,18 @@ 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* mButton = nullptr; + QWidget* mFrame = nullptr; + QWidget* mWidget = nullptr; + AZStd::unique_ptr mDialogWidget = nullptr; + QSplitter* mSplitter = nullptr; + bool mClosable = true; + bool mMaximizeSize = false; + bool mStretchWhenMaximize = false; + int mMinimumHeightBeforeClose = 0; + int mMaximumHeightBeforeClose = 0; + QLayout* mLayout = nullptr; + QLayout* mDialogLayout = nullptr; }; private: @@ -86,7 +83,7 @@ namespace MysticQt private: QSplitter* mRootSplitter; - MCore::Array mDialogs; + AZStd::vector mDialogs; int32 mPrevMouseX; int32 mPrevMouseY; }; diff --git a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp index 4020fd66ff..016664e017 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp @@ -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* mIcon : mIcons) { - delete mIcons[i]; + delete mIcon; } - mIcons.Clear(); + mIcons.clear(); } @@ -58,18 +57,17 @@ namespace MysticQt 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* mIcon : mIcons) { - if (AzFramework::StringFunc::Equal(mIcons[i]->mFileName.c_str(), filename, false /* no case */)) + if (AzFramework::StringFunc::Equal(mIcon->mFileName.c_str(), filename, false /* no case */)) { - return *(mIcons[i]->mIcon); + return *(mIcon->mIcon); } } // we haven't found it IconData* iconData = new IconData(filename); - mIcons.Add(iconData); + mIcons.emplace_back(iconData); return *(iconData->mIcon); } diff --git a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h index 8f7dad06bf..e0be07796e 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 @@ -74,7 +74,7 @@ namespace MysticQt }; QWidget* mMainWindow; - MCore::Array mIcons; + AZStd::vector mIcons; AZStd::string mAppDir; AZStd::string mDataDir; diff --git a/Gems/EMotionFX/Code/Platform/Windows/platform_windows.cmake b/Gems/EMotionFX/Code/Platform/Windows/platform_windows.cmake index 7a325ca97e..98a5170e23 100644 --- a/Gems/EMotionFX/Code/Platform/Windows/platform_windows.cmake +++ b/Gems/EMotionFX/Code/Platform/Windows/platform_windows.cmake @@ -5,3 +5,7 @@ # SPDX-License-Identifier: Apache-2.0 OR MIT # # + +if (PAL_TRAIT_COMPILER_ID STREQUAL "MSVC") + set(LY_COMPILE_OPTIONS PUBLIC /wd4267) +endif() diff --git a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp index fb359eb671..a5d7a67f51 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) @@ -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/PropertyWidgets/ActorGoalNodeHandler.cpp b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/ActorGoalNodeHandler.cpp index a05fbc9fa3..8cbee5924b 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) { @@ -133,10 +133,10 @@ namespace EMotionFX AZStd::string selectedNodeName = newSelection[0].GetNodeName(); AZ::u32 selectedActorInstanceId = newSelection[0].mActorInstanceID; - 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/SkeletonModel.cpp b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp index d71e0e1acf..5a4f14921d 100644 --- a/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp @@ -620,7 +620,7 @@ namespace EMotionFX const AZ::u32 numNodes = skeleton->GetNumNodes(); m_nodeInfos.resize(numNodes); - AZStd::vector > boneListPerLodLevel; + AZStd::vector > boneListPerLodLevel; boneListPerLodLevel.resize(numLodLevels); for (AZ::u32 lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) { @@ -635,7 +635,7 @@ namespace EMotionFX nodeInfo.m_isBone = false; for (AZ::u32 lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) { - if (boneListPerLodLevel[lodLevel].Find(nodeIndex) != MCORE_INVALIDINDEX32) + if (AZStd::find(begin(boneListPerLodLevel[lodLevel]), end(boneListPerLodLevel[lodLevel]), nodeIndex) != end(boneListPerLodLevel[lodLevel])) { nodeInfo.m_isBone = true; break; 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/BoolLogicNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp index b64c2a212f..9d2e1a11c6 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 { diff --git a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h index d3225759a1..90da8d5890 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h @@ -24,7 +24,7 @@ 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; diff --git a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h index 705bef9602..711392f6cf 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h @@ -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/Node.h b/Gems/EMotionFX/Code/Tests/Mocks/Node.h index 712eb257d5..9479883487 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/Node.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/Node.h @@ -28,7 +28,7 @@ namespace EMotionFX MOCK_METHOD1(SetParentIndex, void(uint32 parentNodeIndex)); MOCK_CONST_METHOD0(GetParentIndex, uint32()); 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&()); diff --git a/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp b/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp index 1af95b0a6a..28f139fe39 100644 --- a/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp @@ -46,8 +46,8 @@ namespace EMotionFX const Actor* actor = actorInstance->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); - const MCore::Array& enabledJoints = actorInstance->GetEnabledNodes(); - const AZ::u32 numEnabledJoints = enabledJoints.GetLength(); + const AZStd::vector& enabledJoints = actorInstance->GetEnabledNodes(); + const AZ::u32 numEnabledJoints = enabledJoints.size(); EXPECT_EQ(actorInstance->GetNumEnabledNodes(), actor->GetNumNodes() - static_cast(disabledJointNames.size())) << "The enabled joints on the actor instance are not in sync with the enabledJoints."; diff --git a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp index 9a11d1bd4b..65bb056654 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp @@ -90,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) { 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 { From 0a56c175193a70b9fecac3739a1cb2af71cf7583 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:40 -0700 Subject: [PATCH 160/251] Remove unused MCore::AbstractData class Signed-off-by: Chris Burel --- .../Code/MCore/Source/AbstractData.h | 107 ------------------ Gems/EMotionFX/Code/MCore/mcore_files.cmake | 1 - 2 files changed, 108 deletions(-) delete mode 100644 Gems/EMotionFX/Code/MCore/Source/AbstractData.h 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/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index 65b0cf6ca6..6352bac4ba 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -8,7 +8,6 @@ set(FILES Source/AABB.h - Source/AbstractData.h Source/Algorithms.cpp Source/Algorithms.h Source/Algorithms.inl From c3ff3f342d594df853c10c33efc2a557a40fef78 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:41 -0700 Subject: [PATCH 161/251] Update StringIdPool to use AZ::u32 instead of uint32 Signed-off-by: Chris Burel --- .../Code/MCore/Source/StringIdPool.cpp | 22 +++++-------------- .../Code/MCore/Source/StringIdPool.h | 21 +++++------------- 2 files changed, 12 insertions(+), 31 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp index 7c934084ce..279a7aec1e 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp @@ -29,10 +29,9 @@ namespace MCore { Lock(); - const size_t numStrings = mStrings.size(); - for (size_t i = 0; i < numStrings; ++i) + for (AZStd::basic_string*& mString : mStrings) { - delete mStrings[i]; + delete mString; } mStrings.clear(); @@ -69,24 +68,15 @@ namespace MCore } - const AZStd::string& StringIdPool::GetName(uint32 id) + const AZStd::string& StringIdPool::GetName(AZ::u32 id) { Lock(); - MCORE_ASSERT(id != MCORE_INVALIDINDEX32); + MCORE_ASSERT(id != 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]; - Unlock(); - return *stringAddress; - } - void StringIdPool::Reserve(size_t numStrings) { @@ -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; } diff --git a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h index 30ea434331..9f58adf028 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. @@ -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 From db622de75fedeb5d6f6227cf72333a5f54ffb956 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:43 -0700 Subject: [PATCH 162/251] Convert MCore Algorithms to use size_t Signed-off-by: Chris Burel --- .../Code/MCore/Source/Algorithms.cpp | 93 ++----------------- Gems/EMotionFX/Code/MCore/Source/Algorithms.h | 17 +--- 2 files changed, 8 insertions(+), 102 deletions(-) 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. From a04a0965ccabbea7054b94a307a7126f4121f682 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:44 -0700 Subject: [PATCH 163/251] Convert AlignedArray uint32->size_t Signed-off-by: Chris Burel --- .../Code/MCore/Source/AlignedArray.h | 122 +++++++++--------- 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h b/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h index 00663ffca9..ef1d157e03 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 @@ -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) + MCORE_INLINE explicit AlignedArray(T* elems, size_t num, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) : mLength(num) , mMaxLength(AllocSize(num)) , mMemCategory(memCategory) { mData = (T*)AlignedAllocate(mMaxLength * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < mLength; ++i) { Construct(i, elems[i]); } @@ -68,7 +68,7 @@ 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) + MCORE_INLINE explicit AlignedArray(size_t initSize, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) : mData(nullptr) , mLength(initSize) , mMaxLength(initSize) @@ -77,7 +77,7 @@ namespace MCore if (mMaxLength > 0) { mData = (T*)AlignedAllocate(mMaxLength * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < mLength; ++i) { Construct(i); } @@ -106,20 +106,20 @@ 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 < mLength; ++i)
             {
                 Destruct(i);
             }
@@ -160,7 +160,7 @@ namespace MCore
          * @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 mData[pos]; }
 
         /**
          * Get the first element.
@@ -185,7 +185,7 @@ namespace MCore
          * @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 mData[pos]; }
 
         /**
          * Get a read-only reference to the first element.
@@ -210,13 +210,13 @@ namespace MCore
          * @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 < mLength); }
 
         /**
          * 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 mLength; }
 
         /**
          * 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 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
+        MCORE_INLINE size_t CalcMemoryUsage(bool includeMembers = true) const
         {
-            uint32 result = mMaxLength * sizeof(T);
+            size_t result = mMaxLength * sizeof(T);
             if (includeMembers)
             {
                 result += sizeof(AlignedArray);
@@ -246,7 +246,7 @@ 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)                   { mData[pos] = value; }
 
         /**
          * Add a given element to the back of the array.
@@ -266,9 +266,9 @@ namespace MCore
          */
         MCORE_INLINE void Add(const AlignedArray& a)
         {
-            uint32 l = mLength;
+            size_t l = mLength;
             Grow(mLength + a.mLength);
-            for (uint32 i = 0; i < a.GetLength(); ++i)
+            for (size_t i = 0; i < a.GetLength(); ++i)
             {
                 Construct(l + i, a[i]);
             }
@@ -291,7 +291,7 @@ namespace MCore
         {
             if (mLength > 0)
             {
-                Remove((uint32)0);
+                Remove(0);
             }
         }
 
@@ -310,20 +310,20 @@ 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(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); }
+        MCORE_INLINE void Insert(size_t 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)
+        MCORE_INLINE void Remove(size_t pos)
         {
             Destruct(pos);
             if (mLength > 1)
@@ -338,9 +338,9 @@ 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);
             }
@@ -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,7 +372,7 @@ 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) @@ -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,7 +403,7 @@ namespace MCore */ MCORE_INLINE void Clear(bool clearMem = true) { - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < mLength; ++i) { Destruct(i); } @@ -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) { return; } - uint32 oldLen = mLength; + size_t oldLen = mLength; Grow(newLength); - for (uint32 i = oldLen; i < newLength; ++i) + for (size_t i = oldLen; i < newLength; ++i) { Construct(i); } @@ -436,7 +436,7 @@ 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) { @@ -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 < mLength; ++i) { if (mData[i] == x) { return i; } } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } /** @@ -533,12 +533,12 @@ namespace MCore * 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; } @@ -563,7 +563,7 @@ 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) { @@ -583,7 +583,7 @@ 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) { @@ -594,9 +594,9 @@ namespace MCore if (newLength > mLength) { // growing array, construct empty elements at end of array - const uint32 oldLen = mLength; + const size_t oldLen = mLength; GrowExact(newLength); - for (uint32 i = oldLen; i < newLength; ++i) + for (size_t i = oldLen; i < newLength; ++i) { Construct(i); } @@ -604,7 +604,7 @@ namespace MCore else { // shrinking array, destruct elements at end of array - for (uint32 i = newLength; i < mLength; ++i) + for (size_t i = newLength; i < mLength; ++i) { Destruct(i); } @@ -620,7 +620,7 @@ 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) { @@ -635,7 +635,7 @@ namespace MCore { return false; } - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < mLength; ++i) { if (mData[i] != other.mData[i]) { @@ -651,7 +651,7 @@ namespace MCore Clear(false); mMemCategory = other.mMemCategory; Grow(other.mLength); - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < mLength; ++i) { Construct(i, other.mData[i]); } @@ -676,17 +676,17 @@ namespace MCore } 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 < mLength); return mData[index]; } + MCORE_INLINE const T& operator[](size_t index) const { MCORE_ASSERT(index < mLength); 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. */ + size_t mLength; /**< The number of used elements in the array. */ + size_t 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) + MCORE_INLINE void Grow(size_t newLength) { mLength = newLength; if (mMaxLength >= newLength) @@ -695,7 +695,7 @@ namespace MCore } Realloc(AllocSize(newLength)); } - MCORE_INLINE void GrowExact(uint32 newLength) + MCORE_INLINE void GrowExact(size_t newLength) { mLength = newLength; if (mMaxLength < newLength) @@ -703,9 +703,9 @@ namespace MCore 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) { mData = (T*)AlignedAllocate(num * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } + MCORE_INLINE void Realloc(size_t newSize) { if (newSize == 0) { @@ -733,9 +733,9 @@ namespace MCore 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) + MCORE_INLINE void Construct(size_t index, const T& original) { ::new(mData + index)T(original); } // copy-construct an element at which is a copy of + MCORE_INLINE void Construct(size_t index) { ::new(mData + 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 From b8695742d976f2294e650c8e794f4643c934194e Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:46 -0700 Subject: [PATCH 164/251] Convert MCore Attribute classes uint32 -> size_t Signed-off-by: Chris Burel --- .../Source/AnimGraphAttributeTypes.h | 8 ++--- .../EMotionFX/Code/MCore/Source/Attribute.cpp | 4 +-- Gems/EMotionFX/Code/MCore/Source/Attribute.h | 12 ++++---- .../Code/MCore/Source/AttributeBool.h | 6 ++-- .../Code/MCore/Source/AttributeColor.h | 6 ++-- .../Code/MCore/Source/AttributeFactory.cpp | 29 ++++++++----------- .../Code/MCore/Source/AttributeFactory.h | 6 ++-- .../Code/MCore/Source/AttributeFloat.h | 6 ++-- .../Code/MCore/Source/AttributeInt32.h | 6 ++-- .../Code/MCore/Source/AttributePointer.h | 4 +-- .../Code/MCore/Source/AttributeQuaternion.h | 6 ++-- .../Code/MCore/Source/AttributeString.h | 4 +-- .../Code/MCore/Source/AttributeVector2.h | 6 ++-- .../Code/MCore/Source/AttributeVector3.h | 6 ++-- .../Code/MCore/Source/AttributeVector4.h | 6 ++-- 15 files changed, 54 insertions(+), 61 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h index 9f7b33a66d..d63d67be43 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h @@ -68,8 +68,8 @@ namespace EMotionFX } 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; @@ -116,8 +116,8 @@ namespace EMotionFX } 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; diff --git a/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp b/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp index ed2bc1a535..416d493453 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp @@ -8,12 +8,10 @@ #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; } diff --git a/Gems/EMotionFX/Code/MCore/Source/Attribute.h b/Gems/EMotionFX/Code/MCore/Source/Attribute.h index c245e7d778..3b9b4459aa 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 mTypeID; } 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 mTypeID; /**< 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.h b/Gems/EMotionFX/Code/MCore/Source/AttributeBool.h index 9a923b5fda..3be04c3ce1 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeBool.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeBool.h @@ -39,7 +39,7 @@ namespace MCore MCORE_INLINE void SetValue(bool value) { mValue = value; } MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(bool); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(bool); } // overloaded from the attribute base class Attribute* Clone() const override { return AttributeBool::Create(mValue); } @@ -50,8 +50,8 @@ namespace MCore return AzFramework::StringFunc::LooksLikeBool(valueString.c_str(), &mValue); } 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; } + 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. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h b/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h index 6287239bf8..4ad488af47 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h @@ -42,7 +42,7 @@ namespace MCore MCORE_INLINE void SetValue(const RGBAColor& value) { mValue = value; } MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(RGBAColor); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(RGBAColor); } // overloaded from the attribute base class Attribute* Clone() const override { return AttributeColor::Create(mValue); } @@ -67,8 +67,8 @@ namespace MCore 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; } + size_t GetClassSize() const override { return sizeof(AttributeColor); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_COLOR; } private: RGBAColor mValue; /**< The color value. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp index d0129bdb03..53b91dbb98 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp @@ -54,8 +54,8 @@ namespace MCore 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()); return; @@ -68,8 +68,8 @@ namespace MCore 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; @@ -84,26 +84,21 @@ namespace MCore } - 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(mRegistered), end(mRegistered), [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(mRegistered) ? AZStd::distance(begin(mRegistered), 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; } diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h index 596ac24902..02bd5b0e1b 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h @@ -31,10 +31,10 @@ namespace MCore void RegisterStandardTypes(); size_t GetNumRegisteredAttributes() const { return mRegistered.size(); } - Attribute* GetRegisteredAttribute(uint32 index) const { return mRegistered[index]; } + Attribute* GetRegisteredAttribute(size_t index) const { return mRegistered[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; diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h b/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h index ef650a1430..fee4494ba5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h @@ -40,7 +40,7 @@ namespace MCore MCORE_INLINE void SetValue(float value) { mValue = value; } MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(float); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(float); } // overloaded from the attribute base class Attribute* Clone() const override { return AttributeFloat::Create(mValue); } @@ -51,8 +51,8 @@ namespace MCore return AzFramework::StringFunc::LooksLikeFloat(valueString.c_str(), &mValue); } 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; } + size_t GetClassSize() const override { return sizeof(AttributeFloat); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_FLOATSPINNER; } private: float mValue; /**< The float value. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h b/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h index f13246d438..b1fd1da686 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h @@ -40,7 +40,7 @@ namespace MCore MCORE_INLINE void SetValue(int32 value) { mValue = value; } MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(int32); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(int32); } // overloaded from the attribute base class Attribute* Clone() const override { return AttributeInt32::Create(mValue); } @@ -51,8 +51,8 @@ namespace MCore return AzFramework::StringFunc::LooksLikeInt(valueString.c_str(), &mValue); } 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; } + size_t GetClassSize() const override { return sizeof(AttributeInt32); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_INTSPINNER; } private: int32 mValue; /**< The signed integer value. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h b/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h index 8f7a6cbc65..98eb5f602b 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h @@ -53,8 +53,8 @@ namespace MCore } 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. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h b/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h index 3380cac957..39d9243197 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h @@ -39,7 +39,7 @@ namespace MCore 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 size_t GetRawDataSize() const { return sizeof(AZ::Quaternion); } // adjust values MCORE_INLINE const AZ::Quaternion& GetValue() const { return mValue; } @@ -68,8 +68,8 @@ namespace MCore 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; } + size_t GetClassSize() const override { return sizeof(AttributeQuaternion); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_DEFAULT; } private: AZ::Quaternion mValue; /**< The Quaternion value. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeString.h b/Gems/EMotionFX/Code/MCore/Source/AttributeString.h index 4f3f8df6f9..a05c057023 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeString.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeString.h @@ -36,7 +36,7 @@ namespace MCore 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 size_t GetRawDataSize() const { return mValue.size(); } // adjust values MCORE_INLINE const char* AsChar() const { return mValue.c_str(); } @@ -57,7 +57,7 @@ namespace MCore } 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); } + size_t GetClassSize() const override { return sizeof(AttributeString); } uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_STRING; } private: diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h b/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h index b82c7778f7..826899186a 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h @@ -43,7 +43,7 @@ namespace MCore static AttributeVector2* Create(float x, float y); MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeofVector2; } + MCORE_INLINE size_t GetRawDataSize() const { return sizeofVector2; } // adjust values MCORE_INLINE const AZ::Vector2& GetValue() const { return mValue; } @@ -66,8 +66,8 @@ namespace MCore return AzFramework::StringFunc::LooksLikeVector2(valueString.c_str(), &mValue); } 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; } + size_t GetClassSize() const override { return sizeof(AttributeVector2); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR2; } private: AZ::Vector2 mValue; /**< The Vector2 value. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h b/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h index ea6b820944..066962fb8f 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h @@ -38,7 +38,7 @@ namespace MCore 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 size_t GetRawDataSize() const { return sizeof(AZ::Vector3); } // adjust values MCORE_INLINE const AZ::Vector3& GetValue() const { return mValue; } @@ -67,8 +67,8 @@ namespace MCore 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; } + size_t GetClassSize() const override { return sizeof(AttributeVector3); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR3; } private: AZ::Vector3 mValue; /**< The Vector3 value. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h b/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h index 93dc4a527b..7b20e92a6b 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h @@ -39,7 +39,7 @@ namespace MCore 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 size_t GetRawDataSize() const { return sizeof(AZ::Vector4); } // adjust values MCORE_INLINE const AZ::Vector4& GetValue() const { return mValue; } @@ -63,8 +63,8 @@ namespace MCore } 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; } + size_t GetClassSize() const override { return sizeof(AttributeVector4); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR4; } private: AZ::Vector4 mValue; /**< The Vector4 value. */ From d712c54e206cf4733908991a01aa7ade08d2e071 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:47 -0700 Subject: [PATCH 165/251] Convert BoundingSphere to use `int32_t` to match `AZ::Vector3::GetElement`'s signature Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp b/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp index f462e5499f..959cebe16d 100644 --- a/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp @@ -46,7 +46,7 @@ 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)) @@ -79,7 +79,7 @@ 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)) From 889cdd8c0aa30ebbd45ea55dbb7da9f6d2a45c08 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:49 -0700 Subject: [PATCH 166/251] Convert MCore::Command uint32 -> size_t Signed-off-by: Chris Burel --- .../EMStudioSDK/Source/MainWindow.cpp | 6 ++-- Gems/EMotionFX/Code/MCore/Source/Command.cpp | 36 +++++-------------- Gems/EMotionFX/Code/MCore/Source/Command.h | 8 ++--- 3 files changed, 16 insertions(+), 34 deletions(-) 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 c1c48b3480..7303c8d559 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp @@ -163,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 {} diff --git a/Gems/EMotionFX/Code/MCore/Source/Command.cpp b/Gems/EMotionFX/Code/MCore/Source/Command.cpp index 39e9fde965..8845e7c278 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 @@ -81,9 +82,9 @@ namespace MCore } - uint32 Command::GetNumCallbacks() const + size_t Command::GetNumCallbacks() const { - return static_cast(mCallbacks.size()); + return mCallbacks.size(); } @@ -123,37 +124,18 @@ namespace MCore // 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(mCallbacks), end(mCallbacks), 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 mCallbacks.size() - CalcNumPreCommandCallbacks(); } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Command.h b/Gems/EMotionFX/Code/MCore/Source/Command.h index 7309c5dc91..d6bfb3a0d7 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Command.h +++ b/Gems/EMotionFX/Code/MCore/Source/Command.h @@ -279,26 +279,26 @@ namespace MCore * 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 mCallbacks[index]; } /** * Add (register) a command callback. From a86e2ddf245dfff9ea67df4918729de157956dd5 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:51 -0700 Subject: [PATCH 167/251] Convert MCore::CommandLine uint32 -> size_t Signed-off-by: Chris Burel --- .../Code/MCore/Source/CommandLine.cpp | 105 +++++++++--------- .../EMotionFX/Code/MCore/Source/CommandLine.h | 10 +- 2 files changed, 55 insertions(+), 60 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp b/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp index 25ae5f548f..ae536101e6 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp @@ -26,8 +26,8 @@ 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; @@ -49,8 +49,8 @@ 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; @@ -72,8 +72,8 @@ 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; } @@ -93,8 +93,8 @@ 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; } @@ -114,8 +114,8 @@ 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; } @@ -135,8 +135,8 @@ 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; } @@ -157,8 +157,8 @@ 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; } @@ -178,8 +178,8 @@ 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; @@ -198,8 +198,8 @@ 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); } @@ -211,8 +211,8 @@ 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); } @@ -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,7 +236,7 @@ namespace MCore } else { - return MCORE_INVALIDINDEX32; + return InvalidIndexT; } } @@ -248,8 +248,8 @@ namespace MCore 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)) @@ -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)) @@ -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)) @@ -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)) @@ -337,21 +337,21 @@ namespace MCore // 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; } // 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; } @@ -361,8 +361,8 @@ 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; } @@ -373,42 +373,37 @@ namespace MCore // 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.mName, 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,7 +540,7 @@ 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()); } diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandLine.h b/Gems/EMotionFX/Code/MCore/Source/CommandLine.h index 8eef67ca3c..8a4e5172e8 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. @@ -278,6 +278,6 @@ namespace MCore 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 From f4442425ed2a0bdcaa6e0b70f995f069e8af8325 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:52 -0700 Subject: [PATCH 168/251] Convert CommandManagerCallback uint32 -> size_t Signed-off-by: Chris Burel --- .../EMStudioSDK/Source/EMStudioManager.h | 6 +-- .../EMStudioSDK/Source/MainWindow.h | 6 +-- .../ActionHistory/ActionHistoryCallback.cpp | 40 +++++++------------ .../ActionHistory/ActionHistoryCallback.h | 6 +-- .../MCore/Source/CommandManagerCallback.h | 6 +-- 5 files changed, 27 insertions(+), 37 deletions(-) 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 62c4b5e115..915c45bc18 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h @@ -146,9 +146,9 @@ 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; }; 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 7217259bcb..d49d47452b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h @@ -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/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.cpp index 0d36f19c5a..e99838b7bb 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 @@ -125,7 +125,7 @@ namespace EMStudio } // 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(); @@ -135,28 +135,28 @@ namespace EMStudio } // 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); + delete mList->takeItem(aznumeric_caster(historyIndex)); mIsRemoving = false; } // Set the current command. - void ActionHistoryCallback::OnSetCurrentCommand(uint32 index) + void ActionHistoryCallback::OnSetCurrentCommand(size_t index) { if (mIsRemoving) { return; } - if (index == MCORE_INVALIDINDEX32) + if (index == InvalidIndex) { mList->setCurrentRow(-1); // Darken all history items. - const int numCommands = static_cast(GetCommandManager()->GetNumHistoryItems()); + const int numCommands = mList->count(); for (int i = 0; i < numCommands; ++i) { mList->item(i)->setForeground(m_darkenedBrush); @@ -165,19 +165,19 @@ namespace EMStudio } // get the list of selected items - mList->setCurrentRow(index); + mList->setCurrentRow(aznumeric_caster(index)); // Get the current history index. const uint32 historyIndex = GetCommandManager()->GetHistoryIndex(); - if (historyIndex == MCORE_INVALIDINDEX32) + 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) { @@ -195,7 +195,7 @@ namespace EMStudio // try to undo outResult.clear(); const bool result = GetCommandManager()->Undo(outResult); - if (outResult.size() > 0) + if (!outResult.empty()) { if (!result) { @@ -212,7 +212,7 @@ namespace EMStudio { outResult.clear(); const bool result = GetCommandManager()->Redo(outResult); - if (outResult.size() > 0) + if (!outResult.empty()) { if (!result) { @@ -222,13 +222,6 @@ 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) { @@ -236,12 +229,9 @@ namespace EMStudio } // 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); - } + mList->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..0433b22d5d 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,11 +37,11 @@ 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; 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. From 38217651c5e0ee3a8cde0f09d7ab3b766ed9b04d Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:54 -0700 Subject: [PATCH 169/251] Convert CommandSyntax uint32->size_t Signed-off-by: Chris Burel --- .../Code/MCore/Source/CommandSyntax.cpp | 62 +++++++++---------- .../Code/MCore/Source/CommandSyntax.h | 18 +++--- 2 files changed, 37 insertions(+), 43 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp index 676366ff8a..fb10da4eb4 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; } // 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(); } // 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(); } // 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]); } @@ -135,29 +136,23 @@ namespace MCore // 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.mName, 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; } @@ -165,8 +160,8 @@ namespace MCore 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; } @@ -179,8 +174,8 @@ 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; } @@ -215,8 +210,8 @@ namespace MCore 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.mName.c_str()); + if (paramIndex != InvalidIndex) { const AZStd::string& value = commandLine.GetParameterValue(paramIndex); const AZStd::string& paramName = parameter.mName; @@ -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.mName.size() < right.mName.size(); + }).second->mName.size(); - uint32 offset2 = offset; - uint32 offset3 = offset; + size_t offset2 = offset; + size_t offset3 = offset; // log the header AZStd::string header = "Name"; diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h index a077f0212a..730dd9047a 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h +++ b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h @@ -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(...). From 24fa61f59e8d71939627742d3406aab703275e6e Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:55 -0700 Subject: [PATCH 170/251] Convert DiskFile to not need uint32 Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp | 59 ++++++------------- 1 file changed, 19 insertions(+), 40 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp b/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp index f1fd5543a8..27e94489e6 100644 --- a/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp @@ -43,47 +43,26 @@ namespace MCore 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) - { - 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) + const char* fileMode = [mode]() -> const char* { - 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; From 5a4b0f5770e7eeae1a5ce5898b5b963b3886cd44 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:57 -0700 Subject: [PATCH 171/251] Convert Math::Align to a template, so it doesn't depend on the uint32 type Signed-off-by: Chris Burel --- .../Source/AnimGraph/GraphNode.cpp | 40 ++++++++----------- .../Source/AnimGraph/GraphNode.h | 8 ++-- Gems/EMotionFX/Code/MCore/Source/FastMath.h | 15 ++----- Gems/EMotionFX/Code/MCore/Source/FastMath.inl | 15 ++----- 4 files changed, 26 insertions(+), 52 deletions(-) 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 6bf1c4d45a..f0c06bc7e0 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 @@ -918,8 +918,8 @@ namespace EMStudio { if (mIsCollapsed == false) { - uint32 numPorts = MCore::Max(mInputPorts.size(), mOutputPorts.size()); - uint32 result = (numPorts * 15) + 34; + int32 numPorts = aznumeric_caster(AZStd::max(mInputPorts.size(), mOutputPorts.size())); + int32 result = (numPorts * 15) + 34; return MCore::Math::Align(result, 10); } else @@ -930,33 +930,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.size(); - for (uint32 i = 0; i < numInputPorts; ++i) + int maxInputWidth = 0; + for (const NodePort& nodePort : mInputPorts) { - const NodePort* nodePort = &mInputPorts[i]; - width = mPortFontMetrics->horizontalAdvance(nodePort->GetName()); - maxInputWidth = MCore::Max(maxInputWidth, width); + maxInputWidth = AZStd::max(maxInputWidth, mPortFontMetrics->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.size(); - for (uint32 i = 0; i < numOutputPorts; ++i) + int maxOutputWidth = 0; + for (const NodePort& nodePort : mOutputPorts) { - width = mPortFontMetrics->horizontalAdvance(mOutputPorts[i].GetName()); - maxOutputWidth = MCore::Max(maxOutputWidth, width); + maxOutputWidth = AZStd::max(maxOutputWidth, mPortFontMetrics->horizontalAdvance(nodePort.GetName())); } return maxOutputWidth; @@ -974,18 +967,17 @@ namespace EMStudio mMaxInputWidth = CalcMaxInputPortWidth(); mMaxOutputWidth = CalcMaxOutputPortWidth(); - const uint32 infoWidth = mInfoFontMetrics->horizontalAdvance(mElidedNodeInfo); - const uint32 totalPortWidth = mMaxInputWidth + mMaxOutputWidth + 40 + infoWidth; + const int infoWidth = mInfoFontMetrics->horizontalAdvance(mElidedNodeInfo); + const int totalPortWidth = mMaxInputWidth + mMaxOutputWidth + 40 + infoWidth; // make sure the node is at least 100 units in width - uint32 headerWidth = mHeaderFontMetrics->horizontalAdvance(mElidedName) + 40; - headerWidth = MCore::Max(headerWidth, 100); - - mRequiredWidth = MCore::Max(headerWidth, totalPortWidth); - mNameAndPortsUpdated = true; + const int headerWidth = AZStd::max(mHeaderFontMetrics->horizontalAdvance(mElidedName) + 40, 100); + mRequiredWidth = AZStd::max(headerWidth, totalPortWidth); mRequiredWidth = MCore::Math::Align(mRequiredWidth, 10); + mNameAndPortsUpdated = true; + return mRequiredWidth; } 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 ba6be3de28..061444f9d1 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 @@ -150,8 +150,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; @@ -273,8 +273,8 @@ namespace EMStudio bool mHasVisualGraph; bool mHasVisualOutputPorts; - uint32 mMaxInputWidth; // will be calculated automatically in CalcRequiredWidth() - uint32 mMaxOutputWidth; // will be calculated automatically in CalcRequiredWidth() + int mMaxInputWidth; // will be calculated automatically in CalcRequiredWidth() + int mMaxOutputWidth; // will be calculated automatically in CalcRequiredWidth() // has child node indicator QPolygonF mSubstPoly; 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); From ce139d6ae96c795349a624d4cb8fc51d1b8bf627 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:59 -0700 Subject: [PATCH 172/251] Remove unused HashFunctions functions Signed-off-by: Chris Burel --- .../Code/MCore/Source/HashFunctions.h | 80 ------------------- Gems/EMotionFX/Code/MCore/mcore_files.cmake | 1 - 2 files changed, 81 deletions(-) delete mode 100644 Gems/EMotionFX/Code/MCore/Source/HashFunctions.h 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/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index 6352bac4ba..47b35e004b 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -76,7 +76,6 @@ set(FILES Source/File.h Source/FileSystem.cpp Source/FileSystem.h - Source/HashFunctions.h Source/IDGenerator.cpp Source/IDGenerator.h Source/LogManager.cpp From 387a1faf233b7e24c453cde46078cb540c38b749 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:00 -0700 Subject: [PATCH 173/251] Convert IDGenerator uint32 -> size_t Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp | 8 ++++---- Gems/EMotionFX/Code/MCore/Source/IDGenerator.h | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp index 33dcf1e74d..7e4ff9b16e 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() + : mNextID{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 = mNextID++; + 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..1418b7d3d1 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 mNextID; /**< The id used for the next GenerateID() call. */ /** * Default constructor. From 916b3a94d6b167b36983b05353daabf64078d743 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:02 -0700 Subject: [PATCH 174/251] Convert MCoreCommandManager uint32 -> size_t Signed-off-by: Chris Burel --- .../Code/MCore/Source/MCoreCommandManager.cpp | 44 +++++++++---------- .../Code/MCore/Source/MCoreCommandManager.h | 16 +++---- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp index cd64af15c6..657c5e0303 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp @@ -15,7 +15,7 @@ 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; @@ -28,15 +28,15 @@ namespace MCore // 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 ""; @@ -88,7 +88,7 @@ namespace MCore if (mCommandHistory.size() >= mMaxHistoryEntries) { PopCommandHistory(); - mHistoryIndex = static_cast(mCommandHistory.size()) - 1; + mHistoryIndex = static_cast(mCommandHistory.size()) - 1; } if (!mCommandHistory.empty()) @@ -137,7 +137,7 @@ namespace MCore if (mCommandHistory.size() >= mMaxHistoryEntries) { PopCommandHistory(); - mHistoryIndex = static_cast(mCommandHistory.size()) - 1; + mHistoryIndex = static_cast(mCommandHistory.size()) - 1; } // remove unneeded commands @@ -540,7 +540,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; @@ -689,11 +689,11 @@ 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); @@ -734,11 +734,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); @@ -799,8 +799,8 @@ namespace MCore 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) @@ -1130,8 +1130,8 @@ namespace MCore // 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, mCommandHistory[i].mExecutedCommand->GetName(), mCommandHistory[i].mParameters.GetNumParameters()); + if (i == mHistoryIndex) { LogDetailedInfo("-> %s", text.c_str()); } @@ -1180,15 +1180,15 @@ namespace MCore } // set the max num history items - void CommandManager::SetMaxHistoryItems(uint32 maxItems) + void CommandManager::SetMaxHistoryItems(size_t maxItems) { - maxItems = AZStd::max(1u, maxItems); + maxItems = AZStd::max(size_t{1}, maxItems); mMaxHistoryEntries = maxItems; while (mCommandHistory.size() > mMaxHistoryEntries) { PopCommandHistory(); - mHistoryIndex = static_cast(mCommandHistory.size()) - 1; + mHistoryIndex = static_cast(mCommandHistory.size()) - 1; } } @@ -1197,7 +1197,7 @@ namespace MCore return mMaxHistoryEntries; } - int32 CommandManager::GetHistoryIndex() const + ptrdiff_t CommandManager::GetHistoryIndex() const { return mHistoryIndex; } @@ -1229,7 +1229,7 @@ namespace MCore mHistoryIndex = -1; } - const CommandLine& CommandManager::GetHistoryCommandLine(uint32 historyIndex) const + const CommandLine& CommandManager::GetHistoryCommandLine(size_t historyIndex) const { return mCommandHistory[historyIndex].mParameters; } diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h index 3a6aaf33c6..566c3d17fd 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h @@ -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. */ + 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. @@ -302,8 +302,8 @@ namespace MCore 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. */ + ptrdiff_t mHistoryIndex; /**< 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. */ /** From 88a9a4fb5d6037abf8804ddf94442a2e44b23221 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:03 -0700 Subject: [PATCH 175/251] Correct signature of MCore::MemSet to match memset Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/MCore/Source/MemoryManager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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); } From 404ab514397e5ed704aca0b13b326a2ae489608d Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:06 -0700 Subject: [PATCH 176/251] uint32 -> size_t Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/MCore/Source/ReflectionSerializer.cpp | 4 ++-- Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) 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/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) { From 85c96c75969ec85a06e30d0defb05a8923bfbe99 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:08 -0700 Subject: [PATCH 177/251] Remove `static_cast` from MemoryFile Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp b/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp index 811dcbde42..09021a105a 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp @@ -172,9 +172,9 @@ namespace MCore { const size_t numRead = length - ((mCurrentPos + length) - ((uint8*)mMemoryStart + mLength)); MCore::MemCopy(data, mCurrentPos, numRead); - Forward(static_cast(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); @@ -186,7 +186,7 @@ namespace MCore // returns the filesize in bytes size_t MemoryFile::GetFileSize() const { - return static_cast(mUsedLength); // TODO: convert to size_t later + return mUsedLength; } From 0999a7f6e4b28982b692bba6d98765937f3f8a89 Mon Sep 17 00:00:00 2001 From: Scott Romero <24445312+AMZN-ScottR@users.noreply.github.com> Date: Mon, 9 Aug 2021 08:48:51 -0700 Subject: [PATCH 178/251] [development] s3 upload script now replicates directory structure relative to search root (#2947) Previously the script was using the full local path as the artifact key when uploading to s3. This was causing the installer artifacts to be uploaded incorrectly and non-functional for normal use. Signed-off-by: AMZN-ScottR 24445312+AMZN-ScottR@users.noreply.github.com --- scripts/build/tools/upload_to_s3.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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) From 86d0ba7e6b2b16f9136f4e8586e0f0e7f87ba6bb Mon Sep 17 00:00:00 2001 From: John Jones-Steele Date: Mon, 9 Aug 2021 17:00:53 +0100 Subject: [PATCH 179/251] Minor changes to tests Signed-off-by: John Jones-Steele --- .../Tests/FloatToStringConversionTests.cpp | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp index 21db675324..39593a1c58 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp @@ -13,94 +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 testLocal{ QLocale() }; + QLocale testLocale{ QLocale() }; const bool showThousandsSeparator = false; const int numDecimalPlaces = 2; - QString testString = "0" + QString(testLocal.decimalPoint()) + "12"; - EXPECT_EQ(testString, AzQtComponents::toString(0.1234, numDecimalPlaces, testLocal, showThousandsSeparator)); + QString testString = "0" + QString(testLocale.decimalPoint()) + "12"; + EXPECT_EQ(testString, AzQtComponents::toString(0.1234, numDecimalPlaces, testLocale, showThousandsSeparator)); } TEST(AzQtComponents, FloatToString_AllZerosButOneWithLocale) { - QLocale testLocal{ QLocale() }; + QLocale testLocale{ QLocale() }; const bool showThousandsSeparator = false; const int numDecimalPlaces = 2; - QString testString = "1" + QString(testLocal.decimalPoint()) + "0"; - EXPECT_EQ(testString, AzQtComponents::toString(1.0000, numDecimalPlaces, testLocal, showThousandsSeparator)); + QString testString = "1" + QString(testLocale.decimalPoint()) + "0"; + EXPECT_EQ(testString, AzQtComponents::toString(1.0000, numDecimalPlaces, testLocale, showThousandsSeparator)); } TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorTruncateNoRoundWithLocale) { - QLocale testLocal{ QLocale() }; + QLocale testLocale{ QLocale() }; const bool showThousandsSeparator = true; const int numDecimalPlaces = 3; - QString testString = "1" + QString(testLocal.groupSeparator()) + "000" + QString(testLocal.decimalPoint()) + "123"; - EXPECT_EQ(testString, AzQtComponents::toString(1000.1236, numDecimalPlaces, testLocal, showThousandsSeparator)); + 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 testLocal{ QLocale() }; + QLocale testLocale{ QLocale() }; const bool showThousandsSeparator = true; int numDecimalPlaces = 2; - QString testString = "1" + QString(testLocal.groupSeparator()) + "000" + QString(testLocal.decimalPoint()) + "0"; - EXPECT_EQ(testString, AzQtComponents::toString(1000.000, numDecimalPlaces, testLocal, showThousandsSeparator)); + QString testString = "1" + QString(testLocale.groupSeparator()) + "000" + QString(testLocale.decimalPoint()) + "0"; + EXPECT_EQ(testString, AzQtComponents::toString(1000.000, numDecimalPlaces, testLocale, showThousandsSeparator)); } From 382ca192c8f729b8038ca4ccd40b89aa1c425e80 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:10 -0700 Subject: [PATCH 180/251] Fix Node/Skeleton uint32->size_t Signed-off-by: Chris Burel --- .../Source/AnimGraphTriggerActionCommands.cpp | 16 +- .../Source/MotionEventCommands.cpp | 6 +- .../ExporterLib/Exporter/EndianConversion.cpp | 5 + .../Exporters/ExporterLib/Exporter/Exporter.h | 3 +- .../ExporterLib/Exporter/FileHeaderExport.cpp | 12 +- .../Exporter/MorphTargetExport.cpp | 2 +- .../Rendering/OpenGL2/Source/GLActor.cpp | 22 +- .../Rendering/OpenGL2/Source/Material.h | 6 +- .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 323 +++++++++--------- Gems/EMotionFX/Code/EMotionFX/Source/Actor.h | 54 +-- .../Code/EMotionFX/Source/ActorInstance.cpp | 8 +- .../Source/BlendTreeBlend2AdditiveNode.cpp | 2 +- .../Source/BlendTreeBlend2LegacyNode.cpp | 2 +- .../EMotionFX/Source/BlendTreeBlend2Node.cpp | 2 +- .../EMotionFX/Source/BlendTreeFootIKNode.cpp | 2 +- .../EMotionFX/Source/BlendTreeFootIKNode.h | 4 +- .../EMotionFX/Source/DualQuatSkinDeformer.h | 2 +- .../Source/Importer/ChunkProcessors.cpp | 24 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h | 4 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp | 236 ++++--------- Gems/EMotionFX/Code/EMotionFX/Source/Node.h | 58 ++-- .../Code/EMotionFX/Source/NodeAttribute.h | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp | 34 +- Gems/EMotionFX/Code/EMotionFX/Source/Pose.h | 26 +- .../Code/EMotionFX/Source/RagdollInstance.cpp | 4 +- .../Code/EMotionFX/Source/Recorder.cpp | 4 +- .../EMotionFX/Source/SimulatedObjectSetup.cpp | 2 +- .../Code/EMotionFX/Source/Skeleton.cpp | 80 ++--- .../Code/EMotionFX/Source/Skeleton.h | 28 +- .../Code/EMotionFX/Source/SoftSkinDeformer.h | 2 +- .../Code/EMotionFX/Source/SpringSolver.cpp | 46 +-- .../Code/EMotionFX/Source/SpringSolver.h | 22 +- .../EMotionFX/Code/EMotionFX/Source/SubMesh.h | 10 +- .../Attachments/AttachmentNodesWindow.cpp | 8 +- .../Source/NodeGroups/NodeGroupWidget.cpp | 2 +- Gems/EMotionFX/Code/MCore/Source/Endian.h | 6 + Gems/EMotionFX/Code/MCore/Source/Endian.inl | 38 +++ .../Platform/Windows/platform_windows.cmake | 4 - .../Code/Source/Editor/SkeletonModel.cpp | 11 +- .../Tests/AdditiveMotionSamplingTests.cpp | 14 +- .../Code/Tests/AnimGraphMotionNodeTests.cpp | 30 +- .../Code/Tests/BlendTreeFootIKNodeTests.cpp | 4 +- .../Tests/BlendTreeMirrorPoseNodeTests.cpp | 12 +- .../BlendTreeSimulatedObjectNodeTests.cpp | 4 +- .../Tests/BlendTreeTwoLinkIKNodeTests.cpp | 22 +- .../Code/Tests/Mocks/CommandManagerCallback.h | 6 +- .../Code/Tests/MotionExtractionTests.cpp | 10 +- Gems/EMotionFX/Code/Tests/PoseTests.cpp | 34 +- .../Tests/SimulatedObjectSerializeTests.cpp | 4 +- .../Code/Tests/TestAssetCode/JackActor.cpp | 2 +- 52 files changed, 592 insertions(+), 676 deletions(-) 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/MotionEventCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp index 76ba6f37b7..e4b8d38147 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; + mOldTrackIndex = InvalidIndex; } @@ -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()))); + mMotionEventNr = eventTrack->AddEvent(m_startTime, m_endTime, m_eventDatas.value_or(EMotionFX::EventDataSet())); - if (mMotionEventNr == MCORE_INVALIDINDEX32) + if (mMotionEventNr == InvalidIndex) { outResult = AZStd::string::format("Cannot create motion event. The returned motion event index is not valid."); return 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..153ec6e701 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp @@ -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) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h index 09c0646509..290f9d4470 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h @@ -57,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); @@ -113,7 +114,7 @@ namespace ExporterLib // 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/FileHeaderExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/FileHeaderExport.cpp index 5a7f8d13e0..bafc899d4e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/FileHeaderExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/FileHeaderExport.cpp @@ -38,9 +38,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, @@ -62,9 +62,9 @@ namespace ExporterLib EMotionFX::FileFormat::Actor_Info3 infoChunk; memset(&infoChunk, 0, sizeof(EMotionFX::FileFormat::Actor_Info3)); - infoChunk.mNumLODs = numLODLevels; - infoChunk.mMotionExtractionNodeIndex = motionExtractionNodeIndex; - infoChunk.mRetargetRootNodeIndex = retargetRootNodeIndex; + infoChunk.mNumLODs = aznumeric_caster(numLODLevels); + infoChunk.mMotionExtractionNodeIndex = aznumeric_caster(motionExtractionNodeIndex); + infoChunk.mRetargetRootNodeIndex = aznumeric_caster(retargetRootNodeIndex); infoChunk.mExporterHighVersion = static_cast(EMotionFX::GetEMotionFX().GetHighVersion()); infoChunk.mExporterLowVersion = static_cast(EMotionFX::GetEMotionFX().GetLowVersion()); infoChunk.mUnitType = static_cast(unitType); diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp index b2d88295b4..eefa92f21d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp @@ -168,7 +168,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()); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp index 7a78b5749d..5a7d2032a7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp @@ -113,8 +113,8 @@ namespace RenderGL mTexturePath = 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); @@ -149,7 +149,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); @@ -171,7 +171,7 @@ namespace RenderGL EMotionFX::Mesh::EMeshType meshType = ClassifyMeshType(node, mesh, lodLevel); // get the number of submeshes and iterate through them - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); + const size_t numSubMeshes = mesh->GetNumSubMeshes(); for (uint32 s = 0; s < numSubMeshes; ++s) { // get the current submesh @@ -278,7 +278,7 @@ namespace RenderGL for (uint32 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); @@ -577,8 +577,8 @@ namespace RenderGL EMotionFX::Skeleton* skeleton = mActor->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 = mActor->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { // get the current node EMotionFX::Node* node = skeleton->GetNode(n); @@ -703,7 +703,7 @@ namespace RenderGL } // get the number of nodes - const uint32 numNodes = mActor->GetNumNodes(); + const size_t numNodes = mActor->GetNumNodes(); if (numNodes == 0) { return; @@ -722,7 +722,7 @@ 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); @@ -793,7 +793,7 @@ namespace RenderGL } // get the number of dynamic nodes - const uint32 numNodes = mActor->GetNumNodes(); + const size_t numNodes = mActor->GetNumNodes(); if (numNodes == 0) { return; @@ -812,7 +812,7 @@ 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h index ed5ab18609..9c0522a6da 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h @@ -29,18 +29,18 @@ namespace RenderGL mNumTriangles = 0; mNumVertices = 0; - mNodeIndex = MCORE_INVALIDINDEX32; + mNodeIndex = InvalidIndex; mMaterialIndex = MCORE_INVALIDINDEX32; } - uint32 mNodeIndex; /**< The index of the node to which this primitive belongs to. */ + size_t 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. */ - AZStd::vector mBoneNodeIndices;/**< Mapping from local bones 0-50 to nodes. */ + AZStd::vector mBoneNodeIndices;/**< Mapping from local bones 0-50 to nodes. */ }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index 541ab65071..d8377f2d0e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -75,8 +75,8 @@ namespace EMotionFX mSkeleton = Skeleton::Create(); - mMotionExtractionNode = MCORE_INVALIDINDEX32; - mRetargetRootNode = MCORE_INVALIDINDEX32; + mMotionExtractionNode = InvalidIndex; + mRetargetRootNode = InvalidIndex; mThreadIndex = 0; mCustomData = nullptr; mID = MCore::GetIDGenerator().GenerateID(); @@ -172,7 +172,7 @@ namespace EMotionFX result->mSkeleton = mSkeleton->Clone(); // clone lod data - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->GetNumNodes(); const size_t numLodLevels = m_meshLodData.m_lodLevels.size(); MeshLODData& resultMeshLodData = result->m_meshLodData; @@ -184,7 +184,7 @@ namespace EMotionFX AZStd::vector& resultNodeInfos = resultMeshLodData.m_lodLevels[lodLevel].mNodeInfos; resultNodeInfos.resize(numNodes); - for (uint32 n = 0; n < numNodes; ++n) + for (size_t n = 0; n < numNodes; ++n) { NodeLODInfo& resultNodeInfo = resultNodeInfos[n]; const NodeLODInfo& sourceNodeInfo = nodeInfos[n]; @@ -230,11 +230,11 @@ namespace EMotionFX // init node mirror info void Actor::AllocateNodeMirrorInfos() { - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->GetNumNodes(); mNodeMirrorInfos.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; @@ -253,20 +253,15 @@ namespace EMotionFX // check if we have our axes detected bool Actor::GetHasMirrorAxesDetected() const { - if (mNodeMirrorInfos.size() == 0) + if (mNodeMirrorInfos.empty()) { return false; } - for (uint32 i = 0; i < mNodeMirrorInfos.size(); ++i) + return AZStd::all_of(begin(mNodeMirrorInfos), end(mNodeMirrorInfos), [](const NodeMirrorInfo& nodeMirrorInfo) { - if (mNodeMirrorInfos[i].mAxis == MCORE_INVALIDINDEX8) - { - return false; - } - } - - return true; + return nodeMirrorInfo.mAxis != MCORE_INVALIDINDEX8; + }); } @@ -274,13 +269,12 @@ namespace EMotionFX void Actor::RemoveAllMaterials() { // for all LODs - for (uint32 i = 0; i < mMaterials.size(); ++i) + for (AZStd::vector& mMaterial : mMaterials) { // delete all materials - const uint32 numMats = mMaterials[i].size(); - for (uint32 m = 0; m < numMats; ++m) + for (Material* m : mMaterial) { - mMaterials[i][m]->Destroy(); + m->Destroy(); } } @@ -295,7 +289,7 @@ namespace EMotionFX lodLevels.emplace_back(); LODLevel& newLOD = lodLevels.back(); - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->GetNumNodes(); newLOD.mNodeInfos.resize(numNodes); const size_t numLODs = lodLevels.size(); @@ -339,11 +333,11 @@ namespace EMotionFX lodLevels.emplace(lodLevels.begin()+insertAt); LODLevel& newLOD = lodLevels[insertAt]; const uint32 lodIndex = insertAt; - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->GetNumNodes(); newLOD.mNodeInfos.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; @@ -366,8 +360,8 @@ 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 = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Node* node = mSkeleton->GetNode(i); Node* copyNode = copyActor->GetSkeleton()->FindNodeByID(node->GetID()); @@ -410,14 +404,14 @@ namespace EMotionFX } // copy the materials - const uint32 numMaterials = copyActor->GetNumMaterials(copyLODLevel); - for (uint32 i = 0; i < mMaterials[replaceLODLevel].size(); ++i) + const size_t numMaterials = copyActor->GetNumMaterials(copyLODLevel); + for (Material* i : mMaterials[replaceLODLevel]) { - mMaterials[replaceLODLevel][i]->Destroy(); + i->Destroy(); } mMaterials[replaceLODLevel].clear(); mMaterials[replaceLODLevel].reserve(numMaterials); - for (uint32 i = 0; i < numMaterials; ++i) + for (size_t i = 0; i < numMaterials; ++i) { AddMaterial(replaceLODLevel, copyActor->GetMaterial(copyLODLevel, i)->Clone()); } @@ -449,22 +443,19 @@ namespace EMotionFX if (adjustMorphSetup) { mMorphSetups.resize(numLODs); - for (uint32 i = 0; i < numLODs; ++i) - { - mMorphSetups[i] = nullptr; - } + AZStd::fill(begin(mMorphSetups), AZStd::next(begin(mMorphSetups), numLODs), nullptr); } } // removes all node meshes and stacks void Actor::RemoveAllNodeMeshes() { - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->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); @@ -482,8 +473,8 @@ namespace EMotionFX uint32 totalVerts = 0; uint32 totalIndices = 0; - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); if (!mesh) @@ -520,8 +511,8 @@ namespace EMotionFX uint32 totalIndices = 0; // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -564,8 +555,8 @@ namespace EMotionFX uint32 totalIndices = 0; // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -605,8 +596,8 @@ namespace EMotionFX { uint32 maxInfluences = 0; - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); if (!mesh) @@ -627,7 +618,7 @@ namespace EMotionFX uint32 n; // get the number of nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->GetNumNodes(); // check if the conflict node flag array's size is set to the number of nodes inside the actor if (conflictNodeFlags.size() != numNodes) @@ -694,8 +685,8 @@ namespace EMotionFX // 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) + const size_t numNodes = GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); if (!mesh) @@ -716,11 +707,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 = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { if (GetMesh(lodLevel, i)) { @@ -735,8 +726,8 @@ namespace EMotionFX bool Actor::CheckIfHasSkinnedMeshes(AZ::u32 lodLevel) const { - const AZ::u32 numNodes = mSkeleton->GetNumNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { const Mesh* mesh = GetMesh(lodLevel, i); if (mesh && mesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID)) @@ -768,13 +759,11 @@ 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.size(); ++i) + for (uint32 i = 0; i < mMorphSetups.size(); ++i) { if (mMorphSetups[i]) { @@ -788,8 +777,8 @@ namespace EMotionFX if (deleteMeshDeformers) { // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (i = 0; i < numNodes; ++i) + const size_t numNodes = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // process all LOD levels for (uint32 lod = 0; lod < numLODs; ++lod) @@ -825,8 +814,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) @@ -843,18 +832,14 @@ namespace EMotionFX bool Actor::CheckIfIsMaterialUsed(uint32 lodLevel, uint32 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 = mSkeleton->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 @@ -883,14 +868,14 @@ namespace EMotionFX uint32 maxNumChilds = 0; // traverse through all root nodes - const uint32 numRootNodes = mSkeleton->GetNumRootNodes(); - for (uint32 i = 0; i < numRootNodes; ++i) + const size_t numRootNodes = mSkeleton->GetNumRootNodes(); + for (size_t i = 0; i < numRootNodes; ++i) { // get the given root node from the actor Node* rootNode = mSkeleton->GetNode(mSkeleton->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 @@ -919,8 +904,8 @@ namespace EMotionFX outBoneList->clear(); // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = mSkeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { Mesh* mesh = GetMesh(lodLevel, n); @@ -946,7 +931,7 @@ namespace EMotionFX for (uint32 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 (AZStd::find(begin(*outBoneList), end(*outBoneList), nodeNr) == end(*outBoneList)) @@ -963,8 +948,8 @@ 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.emplace_back(*actor->GetDependency(i)); @@ -995,8 +980,8 @@ 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 = mSkeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { // get the node name const char* name = mSkeleton->GetNode(n)->GetName(); @@ -1052,21 +1037,21 @@ 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 = mSkeleton->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 = mSkeleton->FindNodeByNameNoCase(destNodeName)->GetNodeIndex(); + if (destNodeIndex == InvalidIndex) { return false; } // allocate the data if we haven't already - if (mNodeMirrorInfos.size() == 0) + if (mNodeMirrorInfos.empty()) { AllocateNodeMirrorInfos(); } @@ -1084,7 +1069,7 @@ namespace EMotionFX bool Actor::MapNodeMotionSource(uint16 sourceNodeIndex, uint16 targetNodeIndex) { // allocate the data if we haven't already - if (mNodeMirrorInfos.size() == 0) + if (mNodeMirrorInfos.empty()) { AllocateNodeMirrorInfos(); } @@ -1104,8 +1089,8 @@ 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 = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Node* node = mSkeleton->GetNode(i); @@ -1137,14 +1122,14 @@ namespace EMotionFX // find the first active parent node in a given skeletal LOD - uint32 Actor::FindFirstActiveParentBone(uint32 skeletalLOD, uint32 startNodeIndex) const + size_t Actor::FindFirstActiveParentBone(uint32 skeletalLOD, size_t startNodeIndex) const { - uint32 curNodeIndex = startNodeIndex; + size_t curNodeIndex = startNodeIndex; do { curNodeIndex = mSkeleton->GetNode(curNodeIndex)->GetParentIndex(); - if (curNodeIndex == MCORE_INVALIDINDEX32) + if (curNodeIndex == InvalidIndex) { return curNodeIndex; } @@ -1153,9 +1138,9 @@ namespace EMotionFX { 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 @@ -1169,8 +1154,8 @@ 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 = mSkeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { Node* node = mSkeleton->GetNode(n); @@ -1192,8 +1177,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); @@ -1214,8 +1199,8 @@ namespace EMotionFX if (mSkeleton->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; @@ -1250,7 +1235,7 @@ namespace EMotionFX // generate a path from the current node towards the root - void Actor::GenerateUpdatePathToRoot(uint32 endNodeIndex, AZStd::vector& outPath) const + void Actor::GenerateUpdatePathToRoot(size_t endNodeIndex, AZStd::vector& outPath) const { outPath.clear(); outPath.reserve(32); @@ -1279,7 +1264,7 @@ namespace EMotionFX } } - void Actor::SetMotionExtractionNodeIndex(uint32 nodeIndex) + void Actor::SetMotionExtractionNodeIndex(size_t nodeIndex) { mMotionExtractionNode = nodeIndex; ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnMotionExtractionNodeChanged, this, GetMotionExtractionNode()); @@ -1287,7 +1272,7 @@ namespace EMotionFX Node* Actor::GetMotionExtractionNode() const { - if (mMotionExtractionNode != MCORE_INVALIDINDEX32 && + if (mMotionExtractionNode != InvalidIndex && mMotionExtractionNode < mSkeleton->GetNumNodes()) { return mSkeleton->GetNode(mMotionExtractionNode); @@ -1298,9 +1283,9 @@ 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 = mSkeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Node* node = mSkeleton->GetNode(i); @@ -1327,9 +1312,9 @@ namespace EMotionFX // calculate the inverse bind pose matrices const Pose* bindPose = GetBindPose(); - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->GetNumNodes(); mInvBindPoseTransforms.resize(numNodes); - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { mInvBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); } @@ -1509,7 +1494,7 @@ namespace EMotionFX outPoints.clear(); const uint32 geomLODLevel = 0; - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = mSkeleton->GetNumNodes(); for (int nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { @@ -1532,8 +1517,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); @@ -1545,10 +1530,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(); @@ -1577,8 +1562,8 @@ namespace EMotionFX Pose pose; pose.LinkToActor(this); - const uint32 numNodes = mNodeMirrorInfos.size(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mNodeMirrorInfos.size(); + for (size_t i = 0; i < numNodes; ++i) { const uint16 motionSource = (GetHasMirrorInfo()) ? GetNodeMirrorInfo(i).mSourceNode : static_cast(i); @@ -1699,9 +1684,6 @@ namespace EMotionFX //MCore::LogInfo("best for %s = %f (axis=%d) (flags=%d)", mNodes[i]->GetName(), minDist, bestAxis, bestFlags); } } - - //for (uint32 i=0; iGetName(), mNodeMirrorInfos[i].mAxis, mNodeMirrorInfos[i].mFlags); } @@ -1766,10 +1748,10 @@ namespace EMotionFX 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 = mSkeleton->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 @@ -1791,8 +1773,8 @@ namespace EMotionFX if (numMatches == 1) { - const uint32 hierarchyDepth = mSkeleton->CalcHierarchyDepthForNode(nodeIndex); - const uint32 matchingHierarchyDepth = mSkeleton->CalcHierarchyDepthForNode(result); + const size_t hierarchyDepth = mSkeleton->CalcHierarchyDepthForNode(nodeIndex); + const size_t matchingHierarchyDepth = mSkeleton->CalcHierarchyDepthForNode(result); if (hierarchyDepth != matchingHierarchyDepth) { return MCORE_INVALIDINDEX16; @@ -1838,7 +1820,7 @@ namespace EMotionFX *mSkeleton->GetBindPose() = *other->GetSkeleton()->GetBindPose(); } - void Actor::SetNumNodes(uint32 numNodes) + void Actor::SetNumNodes(size_t numNodes) { mSkeleton->SetNumNodes(numNodes); @@ -1868,13 +1850,13 @@ namespace EMotionFX mSkeleton->GetBindPose()->SetLocalSpaceTransform(mSkeleton->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()); } @@ -1885,7 +1867,7 @@ namespace EMotionFX return node; } - void Actor::RemoveNode(uint32 nr, bool delMem) + void Actor::RemoveNode(size_t nr, bool delMem) { mSkeleton->RemoveNode(nr, delMem); @@ -2169,20 +2151,20 @@ namespace EMotionFX //--------------------------------- - 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; } - MeshDeformerStack* Actor::GetMeshDeformerStack(uint32 lodLevel, uint32 nodeIndex) const + MeshDeformerStack* Actor::GetMeshDeformerStack(uint32 lodLevel, size_t nodeIndex) const { const AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; return lodLevels[lodLevel].mNodeInfos[nodeIndex].mStack; } // set the mesh for a given node in a given LOD - void Actor::SetMesh(uint32 lodLevel, uint32 nodeIndex, Mesh* mesh) + void Actor::SetMesh(uint32 lodLevel, size_t nodeIndex, Mesh* mesh) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; lodLevels[lodLevel].mNodeInfos[nodeIndex].mMesh = mesh; @@ -2190,14 +2172,14 @@ namespace EMotionFX // 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(uint32 lodLevel, size_t nodeIndex, MeshDeformerStack* stack) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; lodLevels[lodLevel].mNodeInfos[nodeIndex].mStack = 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(uint32 lodLevel, size_t nodeIndex) const { // check if there is a mesh Mesh* mesh = GetMesh(lodLevel, nodeIndex); @@ -2217,7 +2199,7 @@ namespace EMotionFX } // remove the mesh for a given node in a given LOD - void Actor::RemoveNodeMeshForLOD(uint32 lodLevel, uint32 nodeIndex, bool destroyMesh) + void Actor::RemoveNodeMeshForLOD(uint32 lodLevel, size_t nodeIndex, bool destroyMesh) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; @@ -2273,8 +2255,8 @@ 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; @@ -2283,7 +2265,7 @@ namespace EMotionFX bindPose->ForceUpdateFullModelSpacePose(); // calculate the inverse bind pose matrices - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { mInvBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); } @@ -2293,10 +2275,10 @@ namespace EMotionFX 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) @@ -2344,8 +2326,8 @@ namespace EMotionFX // 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(mMotionExtractionNode != InvalidIndex); + if (mMotionExtractionNode == InvalidIndex) { return AXIS_Y; } @@ -2380,7 +2362,7 @@ namespace EMotionFX } - void Actor::SetRetargetRootNodeIndex(uint32 nodeIndex) + void Actor::SetRetargetRootNodeIndex(size_t nodeIndex) { mRetargetRootNode = nodeIndex; } @@ -2388,10 +2370,10 @@ namespace EMotionFX void Actor::SetRetargetRootNode(Node* node) { - mRetargetRootNode = node ? node->GetNodeIndex() : MCORE_INVALIDINDEX32; + mRetargetRootNode = 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()) @@ -2400,8 +2382,8 @@ namespace EMotionFX } // Add the parent. - const AZ::u32 parentIndex = mSkeleton->GetNode(jointIndex)->GetParentIndex(); - if (parentIndex != InvalidIndex32) + const size_t parentIndex = mSkeleton->GetNode(jointIndex)->GetParentIndex(); + if (parentIndex != InvalidIndex) { InsertJointAndParents(parentIndex, includedJointIndices); } @@ -2412,10 +2394,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(); @@ -2425,8 +2407,8 @@ namespace EMotionFX continue; } - const AZ::u32 numJoints = mSkeleton->GetNumNodes(); - for (AZ::u32 jointIndex = 0; jointIndex < numJoints; ++jointIndex) + const size_t numJoints = mSkeleton->GetNumNodes(); + for (size_t jointIndex = 0; jointIndex < numJoints; ++jointIndex) { const Mesh* mesh = GetMesh(lod, jointIndex); if (!mesh) @@ -2438,14 +2420,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 AZStd::vector& subMeshJoints = mesh->GetSubMesh(subMeshIndex)->GetBonesArray(); - const AZ::u32 numSubMeshJoints = subMeshJoints.size(); - 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 @@ -2456,7 +2437,7 @@ namespace EMotionFX // Force joints in our "always include list" to be included. for (const AZStd::string& jointName : alwaysIncludeJoints) { - AZ::u32 jointIndex = InvalidIndex32; + size_t jointIndex = InvalidIndex; if (!mSkeleton->FindNodeAndIndexByName(jointName, jointIndex)) { if (!jointName.empty()) @@ -2470,14 +2451,14 @@ 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); } // 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); } @@ -2485,7 +2466,7 @@ namespace EMotionFX 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) + for (size_t i = 0; i < mSkeleton->GetNumNodes(); ++i) { mSkeleton->GetNode(i)->SetSkeletalLODStatus(lod, true); } @@ -2496,17 +2477,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 = mSkeleton->GetNumNodes(); + for (size_t jointIndex = 0; jointIndex < numJoints; ++jointIndex) { const Node* joint = mSkeleton->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); } } } @@ -2530,7 +2511,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 = mSkeleton->GetNumNodes(); AZStd::vector flags; AZStd::unordered_map childParentMap; flags.resize(numNodes); @@ -2554,7 +2535,7 @@ 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); if (node->GetIsCritical() && nodesToKeep.find(node) == nodesToKeep.end()) @@ -2584,7 +2565,7 @@ 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]) { @@ -2597,7 +2578,7 @@ namespace EMotionFX // 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 < mSkeleton->GetNumNodes(); ++nodeIndex) { Node* node = mSkeleton->GetNode(nodeIndex); node->RemoveAllChildNodes(); @@ -2654,8 +2635,8 @@ 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 = mSkeleton->GetNumNodes(); // Remove all the materials and add them back based on the meshAsset. Eventually we will remove all the material from Actor and // GLActor. @@ -2679,7 +2660,7 @@ namespace EMotionFX continue; } - const AZ::u32 jointIndex = meshJoint->GetNodeIndex(); + const size_t jointIndex = meshJoint->GetNodeIndex(); NodeLODInfo& jointInfo = lodLevels[lodLevel].mNodeInfos[jointIndex]; jointInfo.mMesh = mesh; @@ -2690,8 +2671,8 @@ namespace EMotionFX } // 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) @@ -2703,7 +2684,7 @@ namespace EMotionFX 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 = localJointIndices.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. @@ -2801,7 +2782,7 @@ namespace EMotionFX continue; } - const AZ::u32 jointIndex = meshJoint->GetNodeIndex(); + const size_t jointIndex = meshJoint->GetNodeIndex(); NodeLODInfo& jointInfo = lodLevels[lodLevel].mNodeInfos[jointIndex]; Mesh* mesh = jointInfo.mMesh; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h index 0894d22c4c..21b97c0bd6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -131,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. @@ -188,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, AZStd::vector& outPath) const; + void GenerateUpdatePathToRoot(size_t endNodeIndex, AZStd::vector& outPath) const; /** * Set the motion extraction node. @@ -206,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. @@ -218,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 mMotionExtractionNode; } //--------------------------------------------------------------------- @@ -227,7 +227,7 @@ 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. @@ -529,8 +529,8 @@ namespace EMotionFX * @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 &mDependencies[nr]; } + MCORE_INLINE const Dependency* GetDependency(size_t nr) const { return &mDependencies[nr]; } /** * Recursively add dependencies that this actor has on other actors. @@ -649,14 +649,14 @@ 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 mNodeMirrorInfos[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 mNodeMirrorInfos[nodeIndex]; } MCORE_INLINE bool GetHasMirrorInfo() const { return (mNodeMirrorInfos.size() != 0); } @@ -735,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(uint32 skeletalLOD, size_t startNodeIndex) const; /** * Make the geometry LOD levels compatible with the skinning LOD levels. @@ -763,7 +763,7 @@ namespace EMotionFX * @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 mInvBindPoseTransforms[nodeIndex]; } void ReleaseTransformData(); void ResizeTransformData(); @@ -776,8 +776,8 @@ namespace EMotionFX void SetThreadIndex(uint32 index) { mThreadIndex = index; } uint32 GetThreadIndex() const { return mThreadIndex; } - 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(uint32 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. @@ -788,17 +788,17 @@ 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 size_t GetNumNodes() const { return mSkeleton->GetNumNodes(); } - void SetMesh(uint32 lodLevel, uint32 nodeIndex, Mesh* mesh); - void SetMeshDeformerStack(uint32 lodLevel, uint32 nodeIndex, MeshDeformerStack* stack); + void SetMesh(uint32 lodLevel, size_t nodeIndex, Mesh* mesh); + void SetMeshDeformerStack(uint32 lodLevel, size_t nodeIndex, MeshDeformerStack* stack); - bool CheckIfHasMorphDeformer(uint32 lodLevel, uint32 nodeIndex) const; - bool CheckIfHasSkinningDeformer(uint32 lodLevel, uint32 nodeIndex) const; + bool CheckIfHasMorphDeformer(uint32 lodLevel, size_t nodeIndex) const; + bool CheckIfHasSkinningDeformer(uint32 lodLevel, size_t nodeIndex) const; - void RemoveNodeMeshForLOD(uint32 lodLevel, uint32 nodeIndex, bool destroyMesh = true); + void RemoveNodeMeshForLOD(uint32 lodLevel, size_t nodeIndex, bool destroyMesh = true); - void SetNumNodes(uint32 numNodes); + void SetNumNodes(size_t numNodes); void SetUnitType(MCore::Distance::EUnitType unitType); MCore::Distance::EUnitType GetUnitType() const; @@ -808,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 mRetargetRootNode; } + MCORE_INLINE Node* GetRetargetRootNode() const { return (mRetargetRootNode != InvalidIndex) ? mSkeleton->GetNode(mRetargetRootNode) : nullptr; } + void SetRetargetRootNodeIndex(size_t nodeIndex); void SetRetargetRootNode(Node* node); void AutoSetupSkeletalLODsBasedOnSkinningData(const AZStd::vector& alwaysIncludeJoints); @@ -846,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(); @@ -932,8 +932,8 @@ namespace EMotionFX 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. */ + size_t 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. */ + size_t 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. */ AZ::Aabb m_staticAabb; /**< The static AABB. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index 34af57026a..eaa09f92c0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -1356,7 +1356,7 @@ namespace EMotionFX void ActorInstance::MotionExtractionCompensate(Transform& inOutMotionExtractionNodeTransform, EMotionExtractionFlags motionExtractionFlags) const { - MCORE_ASSERT(mActor->GetMotionExtractionNodeIndex() != MCORE_INVALIDINDEX32); + MCORE_ASSERT(mActor->GetMotionExtractionNodeIndex() != InvalidIndex); Transform bindPoseTransform = mTransformData->GetBindPose()->GetLocalSpaceTransform(mActor->GetMotionExtractionNodeIndex()); MotionExtractionCompensate(inOutMotionExtractionNodeTransform, bindPoseTransform, motionExtractionFlags); @@ -1365,8 +1365,8 @@ 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 = mActor->GetMotionExtractionNodeIndex(); + if (motionExtractIndex == InvalidIndex) { return; } @@ -1396,7 +1396,7 @@ namespace EMotionFX // Apply the motion extraction delta transform to the actor instance. void ActorInstance::ApplyMotionExtractionDelta(const Transform& trajectoryDelta) { - if (mActor->GetMotionExtractionNodeIndex() == MCORE_INVALIDINDEX32) + if (mActor->GetMotionExtractionNodeIndex() == InvalidIndex) { return; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp index 703838f22b..e6ce8c6119 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp @@ -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..7e2fdd4736 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp @@ -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..f3b9ee2014 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp @@ -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/BlendTreeFootIKNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp index 4e4f0ed4e4..8e0e67e95a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp @@ -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/DualQuatSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h index b1f3387df7..fc1c986b68 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h @@ -111,7 +111,7 @@ namespace EMotionFX * 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: /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp index 18ec99b435..b6b0b091a2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp @@ -1165,6 +1165,10 @@ namespace EMotionFX } actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); + if (fileInformation.mMotionExtractionNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); + } // actor->SetRetargetOffset( fileInformation.mRetargetRootOffset ); actor->SetUnitType(static_cast(fileInformation.mUnitType)); actor->SetFileUnitType(actor->GetUnitType()); @@ -1211,8 +1215,14 @@ namespace EMotionFX MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.mUnitType); } - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); - actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); + if (fileInformation.mMotionExtractionNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); + } + if (fileInformation.mRetargetRootNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); + } actor->SetUnitType(static_cast(fileInformation.mUnitType)); actor->SetFileUnitType(actor->GetUnitType()); @@ -1258,8 +1268,14 @@ namespace EMotionFX MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.mUnitType); } - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); - actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); + if (fileInformation.mMotionExtractionNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); + } + if (fileInformation.mRetargetRootNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); + } actor->SetUnitType(static_cast(fileInformation.mUnitType)); actor->SetFileUnitType(actor->GetUnitType()); actor->SetOptimizeSkeleton(fileInformation.mOptimizeSkeleton == 0? false : true); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index 36fc898ed1..1203e3762a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -850,7 +850,7 @@ namespace EMotionFX //--------------------------------------------------------------- - VertexAttributeLayer* Mesh::GetSharedVertexAttributeLayer(uint32 layerNr) + VertexAttributeLayer* Mesh::GetSharedVertexAttributeLayer(size_t layerNr) { MCORE_ASSERT(layerNr < mSharedVertexAttributes.size()); return mSharedVertexAttributes[layerNr]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index a0a99f2961..4a86a9875d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -242,7 +242,7 @@ namespace EMotionFX * @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. @@ -279,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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl index 4ee52eaf19..6a29a3de69 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl @@ -30,7 +30,7 @@ MCORE_INLINE size_t Mesh::GetNumSubMeshes() const } -MCORE_INLINE SubMesh* Mesh::GetSubMesh(uint32 nr) const +MCORE_INLINE SubMesh* Mesh::GetSubMesh(size_t nr) const { MCORE_ASSERT(nr < mSubMeshes.size()); return mSubMeshes[nr]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp index a712ffe337..5474087574 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp @@ -20,11 +20,11 @@ namespace EMotionFX Node::Node(const char* name, Skeleton* skeleton) : BaseObject() { - mParentIndex = MCORE_INVALIDINDEX32; - mNodeIndex = MCORE_INVALIDINDEX32; // hasn't been set yet + mParentIndex = InvalidIndex; + mNodeIndex = InvalidIndex; // 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; + mSemanticNameID = InvalidIndex; mNodeFlags = FLAG_INCLUDEINBOUNDSCALC; if (name) @@ -33,20 +33,20 @@ namespace EMotionFX } else { - mNameID = MCORE_INVALIDINDEX32; + mNameID = InvalidIndex; } } - Node::Node(uint32 nameID, Skeleton* skeleton) + Node::Node(size_t nameID, Skeleton* skeleton) : BaseObject() { - mParentIndex = MCORE_INVALIDINDEX32; - mNodeIndex = MCORE_INVALIDINDEX32; // hasn't been set yet + mParentIndex = InvalidIndex; + mNodeIndex = InvalidIndex; // 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; + mSemanticNameID = InvalidIndex; mNodeFlags = FLAG_INCLUDEINBOUNDSCALC; } @@ -69,82 +69,12 @@ namespace EMotionFX // create a node - Node* Node::Create(uint32 nameID, Skeleton* skeleton) + Node* Node::Create(size_t nameID, Skeleton* skeleton) { return aznew Node(nameID, skeleton); } - /* - // 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->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 { @@ -160,9 +90,9 @@ namespace EMotionFX // copy the node attributes result->mAttributes.reserve(mAttributes.size()); - for (uint32 i = 0; i < mAttributes.size(); i++) + for (const NodeAttribute* mAttribute : mAttributes) { - result->AddAttribute(mAttributes[i]->Clone()); + result->AddAttribute(mAttribute->Clone()); } // return the resulting clone @@ -173,7 +103,7 @@ namespace EMotionFX // removes all attributes void Node::RemoveAllAttributes() { - while (mAttributes.size()) + while (!mAttributes.empty()) { mAttributes.back()->Destroy(); mAttributes.pop_back(); @@ -182,16 +112,15 @@ namespace EMotionFX // 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 : mChildIndices) { - mSkeleton->GetNode(mChildIndices[i])->RecursiveCountChildNodes(result); + mSkeleton->GetNode(childIndex)->RecursiveCountChildNodes(result); } return result; @@ -199,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.size(); - for (uint32 i = 0; i < numChildNodes; ++i) + for (size_t childIndex : mChildIndices) { - mSkeleton->GetNode(mChildIndices[i])->RecursiveCountChildNodes(numNodes); + mSkeleton->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) { @@ -222,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)) @@ -243,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(mAttributes), end(mAttributes), [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; + }); + + mAttributes.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(mAttributes, [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; + }); } @@ -299,23 +201,23 @@ namespace EMotionFX // recursively find the root node (expensive call) Node* Node::FindRoot() const { - uint32 parentIndex = mParentIndex; - Node* curNode = const_cast(this); + size_t parentIndex = mParentIndex; + const Node* curNode = this; - while (parentIndex != MCORE_INVALIDINDEX32) + while (parentIndex != InvalidIndex) { curNode = mSkeleton->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 (mParentIndex != InvalidIndex) { return mSkeleton->GetNode(mParentIndex); } @@ -333,7 +235,7 @@ namespace EMotionFX } else { - mNameID = MCORE_INVALIDINDEX32; + mNameID = InvalidIndex; } } @@ -347,12 +249,12 @@ namespace EMotionFX } else { - mSemanticNameID = MCORE_INVALIDINDEX32; + mSemanticNameID = InvalidIndex; } } - void Node::SetParentIndex(uint32 parentNodeIndex) + void Node::SetParentIndex(size_t parentNodeIndex) { mParentIndex = parentNodeIndex; } @@ -389,7 +291,7 @@ namespace EMotionFX // returns true if this is a root node, so if it has no parents bool Node::GetIsRootNode() const { - return (mParentIndex == MCORE_INVALIDINDEX32); + return (mParentIndex == InvalidIndex); } @@ -407,7 +309,7 @@ namespace EMotionFX } - NodeAttribute* Node::GetAttribute(uint32 attributeNr) + NodeAttribute* Node::GetAttribute(size_t attributeNr) { // make sure we are in range MCORE_ASSERT(attributeNr < mAttributes.size()); @@ -417,72 +319,60 @@ namespace EMotionFX } - 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.size(); - for (uint32 i = 0; i < numAttributes; ++i) + const auto foundAttribute = AZStd::find_if(begin(mAttributes), end(mAttributes), [attributeTypeID](const NodeAttribute* attribute) { - if (mAttributes[i]->GetType() == attributeTypeID) - { - return i; - } - } - - // not found - return MCORE_INVALIDINDEX32; + return attribute->GetType() == attributeTypeID; + }); + return foundAttribute != end(mAttributes) ? AZStd::distance(begin(mAttributes), foundAttribute) : InvalidIndex; } NodeAttribute* Node::GetAttributeByType(uint32 attributeType) { // check all attributes - const uint32 numAttributes = mAttributes.size(); - for (uint32 i = 0; i < numAttributes; ++i) + const auto foundAttribute = AZStd::find_if(begin(mAttributes), end(mAttributes), [attributeType](const NodeAttribute* attribute) { - if (mAttributes[i]->GetType() == attributeType) - { - return mAttributes[i]; - } - } - - // not found - return nullptr; + return attribute->GetType() == attributeType; + }); + return foundAttribute != end(mAttributes) ? *foundAttribute : nullptr; } // remove the given attribute - void Node::RemoveAttribute(uint32 index) + void Node::RemoveAttribute(size_t index) { mAttributes.erase(AZStd::next(begin(mAttributes), index)); } - void Node::AddChild(uint32 nodeIndex) + void Node::AddChild(size_t nodeIndex) { mChildIndices.emplace_back(nodeIndex); } - void Node::SetChild(uint32 childNr, uint32 childNodeIndex) + void Node::SetChild(size_t childNr, size_t childNodeIndex) { mChildIndices[childNr] = childNodeIndex; } - void Node::SetNumChildNodes(uint32 numChildNodes) + void Node::SetNumChildNodes(size_t numChildNodes) { mChildIndices.resize(numChildNodes); } - void Node::PreAllocNumChildNodes(uint32 numChildNodes) + void Node::PreAllocNumChildNodes(size_t numChildNodes) { mChildIndices.reserve(numChildNodes); } - void Node::RemoveChild(uint32 nodeIndex) + void Node::RemoveChild(size_t nodeIndex) { if (const auto it = AZStd::find(begin(mChildIndices), end(mChildIndices), nodeIndex); it != end(mChildIndices)) { @@ -499,11 +389,11 @@ namespace EMotionFX bool Node::GetHasChildNodes() const { - return (mChildIndices.size() > 0); + return !mChildIndices.empty(); } - void Node::SetNodeIndex(uint32 index) + void Node::SetNodeIndex(size_t index) { mNodeIndex = index; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h index 73e8a41c01..fe22a12c8d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h @@ -70,7 +70,7 @@ namespace EMotionFX * @param nameID The name ID, generated using the MCore::GetStringIdPool(). * @param skeleton The skeleton where this node will belong to, you still need to manually add it to the skeleton though. */ - static Node* Create(uint32 nameID, Skeleton* skeleton); + static Node* Create(size_t nameID, Skeleton* skeleton); /** * Clone the node. @@ -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 mParentIndex; } /** * 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,14 +155,14 @@ 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 size_t GetID() const { return mNameID; } /** * 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 size_t GetSemanticID() const { return mSemanticNameID; } /** * Get the number of child nodes attached to this node. @@ -175,48 +175,48 @@ namespace EMotionFX * 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 mChildIndices[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 (AZStd::find(begin(mChildIndices), end(mChildIndices), nodeIndex) != end(mChildIndices)); } + MCORE_INLINE bool CheckIfIsChildNode(size_t nodeIndex) const { return (AZStd::find(begin(mChildIndices), end(mChildIndices), nodeIndex) != end(mChildIndices)); } /** * 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). @@ -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 mNodeIndex; } //------------------------------ @@ -364,7 +364,7 @@ namespace EMotionFX * @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 (mSkeletalLODs & (1 << lodLevel)) != 0; } //-------------------------------------------- @@ -415,13 +415,13 @@ 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. */ + size_t mNodeIndex; /**< The node index, which is the index into the array of nodes inside the Skeleton class. */ + size_t 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. */ + size_t mNameID; /**< The ID, which is generated from the name. You can use this for fast compares between nodes. */ + size_t 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. */ - AZStd::vector mChildIndices; /**< The indices that point to the child nodes. */ + AZStd::vector mChildIndices; /**< The indices that point to the child nodes. */ AZStd::vector mAttributes; /**< The node attributes. */ uint8 mNodeFlags; /**< The node flags are used to store boolean attributes of the node as single bits. */ @@ -437,7 +437,7 @@ namespace EMotionFX * @param nameID The name ID, generated using the MCore::GetStringIdPool(). * @param skeleton The skeleton where this node will belong to. */ - Node(uint32 nameID, Skeleton* skeleton); + Node(size_t nameID, Skeleton* skeleton); /** * The destructor. @@ -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/Pose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp index e42393212d..08581e919e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp @@ -114,16 +114,16 @@ namespace EMotionFX } // - void Pose::SetNumTransforms(uint32 numTransforms) + void Pose::SetNumTransforms(size_t numTransforms) { // resize the buffers mLocalSpaceTransforms.ResizeFast(numTransforms); mModelSpaceTransforms.ResizeFast(numTransforms); - const uint32 oldSize = mFlags.GetLength(); + const size_t oldSize = mFlags.GetLength(); mFlags.ResizeFast(numTransforms); - for (uint32 i = oldSize; i < numTransforms; ++i) + for (size_t i = oldSize; i < numTransforms; ++i) { mFlags[i] = 0; SetLocalSpaceTransform(i, Transform::CreateIdentity()); @@ -257,7 +257,7 @@ namespace EMotionFX // recursively update - void Pose::UpdateModelSpaceTransform(uint32 nodeIndex) const + void Pose::UpdateModelSpaceTransform(size_t nodeIndex) const { Skeleton* skeleton = mActor->GetSkeleton(); @@ -286,7 +286,7 @@ namespace EMotionFX // update the local transform - void Pose::UpdateLocalSpaceTransform(uint32 nodeIndex) const + void Pose::UpdateLocalSpaceTransform(size_t nodeIndex) const { const uint32 flags = mFlags[nodeIndex]; if (flags & FLAG_LOCALTRANSFORMREADY) @@ -316,28 +316,28 @@ namespace EMotionFX // get the local transform - const Transform& Pose::GetLocalSpaceTransform(uint32 nodeIndex) const + const Transform& Pose::GetLocalSpaceTransform(size_t nodeIndex) const { UpdateLocalSpaceTransform(nodeIndex); return mLocalSpaceTransforms[nodeIndex]; } - const Transform& Pose::GetModelSpaceTransform(uint32 nodeIndex) const + const Transform& Pose::GetModelSpaceTransform(size_t nodeIndex) const { UpdateModelSpaceTransform(nodeIndex); return mModelSpaceTransforms[nodeIndex]; } - Transform Pose::GetWorldSpaceTransform(uint32 nodeIndex) const + Transform Pose::GetWorldSpaceTransform(size_t nodeIndex) const { UpdateModelSpaceTransform(nodeIndex); return mModelSpaceTransforms[nodeIndex].Multiplied(mActorInstance->GetWorldSpaceTransform()); } - void Pose::GetWorldSpaceTransform(uint32 nodeIndex, Transform* outResult) const + void Pose::GetWorldSpaceTransform(size_t nodeIndex, Transform* outResult) const { UpdateModelSpaceTransform(nodeIndex); *outResult = mModelSpaceTransforms[nodeIndex]; @@ -346,7 +346,7 @@ namespace EMotionFX // 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) { @@ -357,7 +357,7 @@ namespace EMotionFX } - void Pose::GetModelSpaceTransform(uint32 nodeIndex, Transform* outResult) const + void Pose::GetModelSpaceTransform(size_t nodeIndex, Transform* outResult) const { UpdateModelSpaceTransform(nodeIndex); *outResult = mModelSpaceTransforms[nodeIndex]; @@ -365,7 +365,7 @@ namespace EMotionFX // 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; @@ -382,7 +382,7 @@ namespace EMotionFX // 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) @@ -396,15 +396,15 @@ namespace EMotionFX // 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; @@ -423,7 +423,7 @@ namespace EMotionFX } - 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h index ae3cfc7031..ef9653e728 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); @@ -202,7 +202,7 @@ namespace EMotionFX const Actor* mActor; const Skeleton* mSkeleton; - 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/RagdollInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp index 98b4275791..93d4cd19d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp @@ -67,7 +67,7 @@ namespace EMotionFX } else { - m_ragdollNodeIndices[jointIndex] = MCORE_INVALIDINDEX32; + m_ragdollNodeIndices[jointIndex] = InvalidIndex; } } @@ -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(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp index 41c7c1e929..923c74aa02 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp @@ -930,7 +930,7 @@ namespace EMotionFX } // check if we have an active node for the given item - size_t index = MCORE_INVALIDINDEX32; + size_t index = InvalidIndex; for (size_t x = 0; x < numActiveNodes; ++x) { if (mActiveNodes[x]->GetId() == curItem->mNodeId) @@ -941,7 +941,7 @@ namespace EMotionFX } // the node got deactivated, finalize the item - if (index == MCORE_INVALIDINDEX32) + if (index == InvalidIndex) { curItem->mGlobalWeights.Optimize(0.0001f); curItem->mLocalWeights.Optimize(0.0001f); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp index 8c98bad5a4..006be1d9a5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp @@ -280,7 +280,7 @@ namespace EMotionFX { if (m_object) { - return m_object->GetSimulatedRootJointIndex(this) != MCORE_INVALIDINDEX32; + return m_object->GetSimulatedRootJointIndex(this) != InvalidIndex; } return false; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp index 5860a0b452..24983c3a71 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp @@ -44,14 +44,13 @@ namespace EMotionFX { Skeleton* result = Skeleton::Create(); - const uint32 numNodes = m_nodes.size(); - 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; @@ -61,7 +60,7 @@ namespace EMotionFX // reserve memory - void Skeleton::ReserveNodes(uint32 numNodes) + void Skeleton::ReserveNodes(size_t numNodes) { m_nodes.reserve(numNodes); } @@ -76,7 +75,7 @@ namespace EMotionFX // 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) @@ -93,10 +92,9 @@ namespace EMotionFX { if (delFromMem) { - const uint32 numNodes = m_nodes.size(); - for (uint32 i = 0; i < numNodes; ++i) + for (Node* node : m_nodes) { - m_nodes[i]->Destroy(); + node->Destroy(); } } @@ -132,38 +130,28 @@ namespace EMotionFX Node* Skeleton::FindNodeByNameNoCase(const char* name) const { // check the names for all nodes - const uint32 numNodes = m_nodes.size(); - 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.size(); - 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]) { @@ -176,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.size(); + size_t oldLength = m_nodes.size(); m_nodes.resize(numNodes); - for (uint32 i = oldLength; i < numNodes; ++i) + for (size_t i = oldLength; i < numNodes; ++i) { m_nodes[i] = nullptr; } @@ -189,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.size(); - 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); } @@ -200,21 +188,21 @@ namespace EMotionFX // reserve memory for the root nodes array - void Skeleton::ReserveRootNodes(uint32 numNodes) + void Skeleton::ReserveRootNodes(size_t numNodes) { m_rootNodes.reserve(numNodes); } // add a root node - void Skeleton::AddRootNode(uint32 nodeIndex) + void Skeleton::AddRootNode(size_t nodeIndex) { m_rootNodes.emplace_back(nodeIndex); } // remove a given root node - void Skeleton::RemoveRootNode(uint32 nr) + void Skeleton::RemoveRootNode(size_t nr) { m_rootNodes.erase(AZStd::next(begin(m_rootNodes), nr)); } @@ -230,8 +218,8 @@ namespace EMotionFX // log all node names void Skeleton::LogNodes() { - const uint32 numNodes = m_nodes.size(); - 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()); } @@ -239,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++; @@ -253,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 e5887df0f6..01d3e9dee8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h @@ -33,11 +33,11 @@ namespace EMotionFX Skeleton* Clone(); MCORE_INLINE size_t GetNumNodes() const { return m_nodes.size(); } - MCORE_INLINE Node* GetNode(uint32 index) const { return m_nodes[index]; } + 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,7 +97,7 @@ 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. @@ -110,28 +110,28 @@ namespace EMotionFX * @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: AZStd::vector m_nodes; /**< The nodes, including root nodes. */ mutable AZStd::unordered_map m_nodesMap; - AZStd::vector 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/SoftSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h index 497f38f764..33596e6809 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h @@ -114,7 +114,7 @@ namespace EMotionFX * 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) { mNodeNumbers.reserve(numBones); mBoneMatrices.reserve(numBones); } protected: diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp index adaea2e6c2..8765a0e991 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,8 +409,8 @@ 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(); if (restLength > AZ::Constants::FloatEpsilon) @@ -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) @@ -564,14 +564,14 @@ namespace EMotionFX particle.m_joint = joint; particle.m_pos = m_actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(joint->GetSkeletonJointIndex()).mPosition; 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; } @@ -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) @@ -833,7 +833,7 @@ namespace EMotionFX // 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; } @@ -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/SubMesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h index 1cec56efc6..9455b6b7df 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h @@ -198,28 +198,28 @@ namespace EMotionFX * @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 mBones[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.data(); } + MCORE_INLINE size_t* GetBones() { return mBones.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 AZStd::vector& GetBonesArray() const { return mBones; } + MCORE_INLINE const AZStd::vector& GetBonesArray() const { return mBones; } /** * 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 AZStd::vector& GetBonesArray() { return mBones; } + MCORE_INLINE AZStd::vector& GetBonesArray() { return mBones; } /** * Reinitialize the bones. @@ -268,7 +268,7 @@ namespace EMotionFX protected: - AZStd::vector mBones; /**< The collection of bones. These are stored as node numbers that point into the actor. */ + AZStd::vector 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. */ 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 3b24552035..d84b22f5d5 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 @@ -144,11 +144,11 @@ namespace EMStudio mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (mNodeTable->selectedItems().size() != 0)); // counter for attachment nodes - uint16 numAttachmentNodes = 0; + size_t numAttachmentNodes = 0; // set the row count - const uint16 numNodes = mActor->GetNumNodes(); - for (uint16 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // get the nodegroup EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); @@ -162,7 +162,7 @@ namespace EMStudio mNodeTable->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 (%zu / %zu)", numAttachmentNodes, mActor->GetNumNodes()).c_str()); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignCenter); mNodeTable->setHorizontalHeaderItem(0, nameHeaderItem); 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 481718ab66..552a6d45e7 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 @@ -168,7 +168,7 @@ namespace EMStudio mNodeTable->setRowCount(mNodeGroup->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)", ((mNodeGroup->GetIsEnabledOnDefault()) ? "Enabled" : "Disabled"), mNodeGroup->GetNumNodes(), mActor->GetNumNodes()); QTableWidgetItem* nameHeaderItem = new QTableWidgetItem(headerText.c_str()); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignCenter); mNodeTable->setHorizontalHeaderItem(0, nameHeaderItem); 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/Platform/Windows/platform_windows.cmake b/Gems/EMotionFX/Code/Platform/Windows/platform_windows.cmake index 98a5170e23..7a325ca97e 100644 --- a/Gems/EMotionFX/Code/Platform/Windows/platform_windows.cmake +++ b/Gems/EMotionFX/Code/Platform/Windows/platform_windows.cmake @@ -5,7 +5,3 @@ # SPDX-License-Identifier: Apache-2.0 OR MIT # # - -if (PAL_TRAIT_COMPILER_ID STREQUAL "MSVC") - set(LY_COMPILE_OPTIONS PUBLIC /wd4267) -endif() diff --git a/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp index 5a4f14921d..8530521458 100644 --- a/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp @@ -632,15 +632,10 @@ namespace EMotionFX 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 (AZStd::find(begin(boneListPerLodLevel[lodLevel]), end(boneListPerLodLevel[lodLevel]), nodeIndex) != end(boneListPerLodLevel[lodLevel])) - { - nodeInfo.m_isBone = true; - break; - } - } + return AZStd::find(begin(lodLevel), end(lodLevel), nodeIndex) != end(lodLevel); + }); // Has mesh? nodeInfo.m_hasMesh = false; 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/AnimGraphMotionNodeTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp index 6fa1d962ab..2a199f5e8b 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_l_handIndex = InvalidIndex; + size_t m_l_loArmIndex = InvalidIndex; + size_t m_l_loLegIndex = InvalidIndex; + size_t m_l_ankleIndex = InvalidIndex; + size_t m_r_handIndex = InvalidIndex; + size_t m_r_loArmIndex = InvalidIndex; + size_t m_r_loLegIndex = InvalidIndex; + size_t m_r_ankleIndex = InvalidIndex; + size_t m_jack_rootIndex = InvalidIndex; + size_t m_bip01__pelvisIndex = InvalidIndex; AnimGraphMotionNode* m_motionNode = nullptr; BlendTree* m_blendTree = nullptr; BlendTreeFloatConstantNode* m_fltConstNode = nullptr; @@ -351,7 +351,7 @@ namespace EMotionFX AZ::Vector3 rootFinalPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; 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]); @@ -385,7 +385,7 @@ namespace EMotionFX rootFinalPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; // 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]); @@ -426,7 +426,7 @@ 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; @@ -460,7 +460,7 @@ namespace EMotionFX uint32 currentMotionIndex = uniqueData->mActiveMotionIndex; // 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; m_motionNode->Reinit(); @@ -476,7 +476,7 @@ 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; m_motionNode->Reinit(); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp index 5fddb5a94b..48350ce071 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp @@ -136,10 +136,10 @@ 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(); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp index 53e0e7de77..9851409a94 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp @@ -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); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp index a53a3d7e0b..df2f644eb4 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) diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp index 91b7687a02..820e6d9fa4 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp @@ -147,7 +147,7 @@ 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; + size_t testJointIndex; m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; @@ -187,7 +187,7 @@ namespace EMotionFX ParamSetValue("WeightParam", weight); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; + size_t testJointIndex; m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; @@ -202,7 +202,7 @@ namespace EMotionFX // Unique data only updates once unless reset mMustUpdate 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); @@ -234,9 +234,9 @@ namespace EMotionFX ParamSetValue("WeightParam", weight); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; - AZ::u32 linkedJoint0Index; - AZ::u32 linkedJoint1Index; + size_t testJointIndex; + size_t linkedJoint0Index; + size_t linkedJoint1Index; m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); m_jackSkeleton->FindNodeAndIndexByName(m_param.linkedJointNames[0], linkedJoint0Index); m_jackSkeleton->FindNodeAndIndexByName(m_param.linkedJointNames[1], linkedJoint1Index); @@ -287,7 +287,7 @@ namespace EMotionFX ParamSetValue("GoalPosParam", AZ::Vector3(0.0f, 1.0f, 1.0f)); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; + size_t testJointIndex; m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); const AZ::Quaternion testJointRotation = jackPose->GetModelSpaceTransform(testJointIndex).mRotation; @@ -334,8 +334,8 @@ namespace EMotionFX GetEMotionFX().Update(1.0f / 60.0f); Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testBendJointIndex; - AZ::u32 testJointIndex; + size_t testBendJointIndex; + size_t testJointIndex; AZStd::string& bendLoArm = m_param.linkedJointNames[0]; m_jackSkeleton->FindNodeAndIndexByName(bendLoArm, testBendJointIndex); m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); @@ -395,8 +395,8 @@ namespace EMotionFX GetEMotionFX().Update(1.0f / 60.0f); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; - AZ::u32 testBendJointIndex; + size_t testJointIndex; + size_t testBendJointIndex; AZStd::string& bendLoArm = m_param.linkedJointNames[0]; m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); m_jackSkeleton->FindNodeAndIndexByName(bendLoArm, testBendJointIndex); 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/MotionExtractionTests.cpp b/Gems/EMotionFX/Code/Tests/MotionExtractionTests.cpp index e1839d8d9f..85c0e4201f 100644 --- a/Gems/EMotionFX/Code/Tests/MotionExtractionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MotionExtractionTests.cpp @@ -119,8 +119,8 @@ namespace EMotionFX } protected: - AZ::u32 m_jack_rootIndex = MCORE_INVALIDINDEX32; - AZ::u32 m_jack_hipIndex = MCORE_INVALIDINDEX32; + size_t m_jack_rootIndex = InvalidIndex; + size_t m_jack_hipIndex = InvalidIndex; AnimGraphMotionNode* m_motionNode = nullptr; BlendTree* m_blendTree = nullptr; Motion* m_motion = nullptr; @@ -243,7 +243,7 @@ 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.durationMultipliers.size(); paramIndex++) { // Test motion extraction under different durations/time deltas const float motionDuration = 1.066f * m_param.durationMultipliers[paramIndex]; @@ -262,7 +262,7 @@ 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.durationMultipliers.size(); paramIndex++) { const float motionDuration = 1.066f * m_param.durationMultipliers[paramIndex]; const float originalPositionX = m_actorInstance->GetWorldSpaceTransform().mPosition.GetX(); @@ -290,7 +290,7 @@ 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.durationMultipliers.size(); paramIndex++) { const float originalPositionX = m_actorInstance->GetWorldSpaceTransform().mPosition.GetX(); const float originalPositionY = m_actorInstance->GetWorldSpaceTransform().mPosition.GetY(); diff --git a/Gems/EMotionFX/Code/Tests/PoseTests.cpp b/Gems/EMotionFX/Code/Tests/PoseTests.cpp index 0957176813..1785a4d512 100644 --- a/Gems/EMotionFX/Code/Tests/PoseTests.cpp +++ b/Gems/EMotionFX/Code/Tests/PoseTests.cpp @@ -742,7 +742,7 @@ 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'."; @@ -779,7 +779,7 @@ 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), @@ -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); @@ -820,7 +820,7 @@ 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), @@ -837,7 +837,7 @@ 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), @@ -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); @@ -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()); @@ -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); @@ -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,7 +1026,7 @@ 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); @@ -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), @@ -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); @@ -1222,7 +1222,7 @@ 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()); } @@ -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,7 +1255,7 @@ 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); } diff --git a/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp b/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp index 5f48cc145f..9ba4e4f6cb 100644 --- a/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp @@ -32,7 +32,7 @@ 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); @@ -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/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()); From 225798480ce9326a54b0a481937b352694ea4579 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:11 -0700 Subject: [PATCH 181/251] Fix Actor lod levels and material indexes uint32->size_t Signed-off-by: Chris Burel --- .../ExporterLib/Exporter/NodeExport.cpp | 2 +- .../EMotionFX/Rendering/Common/RenderUtil.cpp | 24 +-- .../EMotionFX/Rendering/Common/RenderUtil.h | 4 +- .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 152 +++++++--------- Gems/EMotionFX/Code/EMotionFX/Source/Actor.h | 58 +++---- .../Code/EMotionFX/Source/ActorInstance.h | 2 +- .../EMotionFX/Source/DualQuatSkinDeformer.cpp | 2 +- .../EMotionFX/Source/DualQuatSkinDeformer.h | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 22 +-- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h | 4 +- .../Code/EMotionFX/Source/MeshDeformer.cpp | 2 +- .../Code/EMotionFX/Source/MeshDeformer.h | 2 +- .../EMotionFX/Source/MeshDeformerStack.cpp | 6 +- .../Code/EMotionFX/Source/MeshDeformerStack.h | 2 +- .../EMotionFX/Source/MorphMeshDeformer.cpp | 2 +- .../Code/EMotionFX/Source/MorphMeshDeformer.h | 2 +- .../Code/EMotionFX/Source/MorphSetup.cpp | 2 +- .../Code/EMotionFX/Source/MorphSetup.h | 4 +- .../Code/EMotionFX/Source/MorphTarget.h | 4 +- .../EMotionFX/Source/MorphTargetStandard.cpp | 8 +- .../EMotionFX/Source/MorphTargetStandard.h | 10 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp | 10 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.h | 8 +- .../Code/EMotionFX/Source/NodeMap.cpp | 87 ++++------ .../EMotionFX/Code/EMotionFX/Source/NodeMap.h | 34 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Pose.h | 30 ++-- .../EMotionFX/Source/SoftSkinDeformer.cpp | 2 +- .../Code/EMotionFX/Source/SoftSkinDeformer.h | 2 +- .../Source/NodeHierarchyWidget.cpp | 16 +- .../EMStudioSDK/Source/NodeHierarchyWidget.h | 2 +- .../Source/RenderPlugin/RenderPlugin.h | 2 +- .../Source/NodeWindow/MeshInfo.cpp | 16 +- .../Source/NodeWindow/MeshInfo.h | 2 +- .../Source/NodeWindow/NodeWindowPlugin.cpp | 8 +- .../Source/NodeWindow/SubMeshInfo.cpp | 2 +- .../Source/NodeWindow/SubMeshInfo.h | 4 +- .../Source/SceneManager/MirrorSetupWindow.cpp | 162 ++++++------------ .../Source/SceneManager/MirrorSetupWindow.h | 8 +- .../Code/Source/Editor/SkeletonModel.cpp | 14 +- 40 files changed, 311 insertions(+), 416 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp index 80efb54606..4f6e5a5c52 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp @@ -430,7 +430,7 @@ namespace ExporterLib MCore::LogInfo("============================================================"); // get all nodes that are affected by the skin - AZStd::vector bones; + AZStd::vector bones; if (actor) { actor->ExtractBoneList(0, &bones); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index e17fffbdb5..34ab2a8a69 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -653,7 +653,7 @@ namespace MCommon // render the advanced skeleton - 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) + 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) @@ -670,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 || AZStd::find(begin(boneList), end(boneList), jointIndex) == end(boneList)) + if (parentIndex == InvalidIndex || AZStd::find(begin(boneList), end(boneList), jointIndex) == end(boneList)) { continue; } @@ -715,7 +715,7 @@ namespace MCommon // render node orientations - void RenderUtil::RenderNodeOrientations(EMotionFX::ActorInstance* actorInstance, const AZStd::vector& 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()); @@ -726,18 +726,18 @@ 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 && AZStd::find(begin(boneList), end(boneList), jointIndex) != end(boneList)) + 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h index 8fb8f524c4..d62816fa65 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h @@ -191,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 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)); + 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. @@ -202,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 AZStd::vector& 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index d8377f2d0e..77ce4435bc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -79,7 +79,7 @@ namespace EMotionFX mRetargetRootNode = InvalidIndex; mThreadIndex = 0; mCustomData = nullptr; - mID = MCore::GetIDGenerator().GenerateID(); + mID = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); mUnitType = GetEMotionFX().GetUnitType(); mFileUnitType = mUnitType; m_staticAabb = AZ::Aabb::CreateNull(); @@ -149,21 +149,13 @@ namespace EMotionFX // clone the materials result->mMaterials.resize(mMaterials.size()); - for (uint32 i = 0; i < mMaterials.size(); ++i) + for (size_t i = 0; i < mMaterials.size(); ++i) { // get the number of materials in the current LOD - const uint32 numMaterials = mMaterials[i].size(); - result->mMaterials[i].reserve(numMaterials); - for (uint32 m = 0; m < numMaterials; ++m) + result->mMaterials[i].reserve(mMaterials[i].size()); + for (const Material* material : mMaterials[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()); } } @@ -195,7 +187,7 @@ namespace EMotionFX // clone the morph setups result->mMorphSetups.resize(mMorphSetups.size()); - for (uint32 i = 0; i < mMorphSetups.size(); ++i) + for (size_t i = 0; i < mMorphSetups.size(); ++i) { if (mMorphSetups[i]) { @@ -326,13 +318,13 @@ 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.emplace(lodLevels.begin()+insertAt); LODLevel& newLOD = lodLevels[insertAt]; - const uint32 lodIndex = insertAt; + const size_t lodIndex = insertAt; const size_t numNodes = mSkeleton->GetNumNodes(); newLOD.mNodeInfos.resize(numNodes); @@ -352,7 +344,7 @@ namespace EMotionFX } // 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; @@ -433,7 +425,7 @@ namespace EMotionFX } // 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); @@ -467,7 +459,7 @@ namespace EMotionFX } - 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; @@ -504,7 +496,7 @@ 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; @@ -548,7 +540,7 @@ 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; @@ -592,9 +584,9 @@ namespace EMotionFX } - uint32 Actor::CalcMaxNumInfluences(uint32 lodLevel) const + size_t Actor::CalcMaxNumInfluences(size_t lodLevel) const { - uint32 maxInfluences = 0; + size_t maxInfluences = 0; const size_t numNodes = mSkeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) @@ -605,7 +597,7 @@ namespace EMotionFX continue; } - maxInfluences = MCore::Max(maxInfluences, mesh->CalcMaxNumInfluences()); + maxInfluences = AZStd::max(maxInfluences, mesh->CalcMaxNumInfluences()); } return maxInfluences; @@ -613,10 +605,8 @@ namespace EMotionFX // verify if the skinning will look correctly in the given geometry LOD for a given skeletal LOD level - void Actor::VerifySkinning(AZStd::vector& 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 size_t numNodes = mSkeleton->GetNumNodes(); @@ -630,7 +620,7 @@ namespace EMotionFX 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); @@ -672,19 +662,15 @@ 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; + size_t maxInfluences = 0; + AZStd::vector meshVertexCounts; const size_t numNodes = GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { @@ -694,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) { @@ -724,7 +710,7 @@ namespace EMotionFX } - bool Actor::CheckIfHasSkinnedMeshes(AZ::u32 lodLevel) const + bool Actor::CheckIfHasSkinnedMeshes(size_t lodLevel) const { const size_t numNodes = mSkeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) @@ -763,14 +749,14 @@ namespace EMotionFX const size_t numLODs = GetNumLODLevels(); // for all LODs, get rid of all the morph setups for each geometry LOD - for (uint32 i = 0; i < mMorphSetups.size(); ++i) + for (MorphSetup* mMorphSetup : mMorphSetups) { - if (mMorphSetups[i]) + if (mMorphSetup) { - mMorphSetups[i]->Destroy(); + mMorphSetup->Destroy(); } - mMorphSetups[i] = nullptr; + mMorphSetup = nullptr; } // remove all modifiers from the stacks for each lod in all nodes @@ -781,7 +767,7 @@ namespace EMotionFX 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); @@ -805,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) @@ -829,7 +815,7 @@ 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 size_t numNodes = mSkeleton->GetNumNodes(); @@ -848,7 +834,7 @@ 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.size()); @@ -865,7 +851,7 @@ 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 size_t numRootNodes = mSkeleton->GetNumRootNodes(); @@ -898,7 +884,7 @@ namespace EMotionFX // extract a bone list - void Actor::ExtractBoneList(uint32 lodLevel, AZStd::vector* outBoneList) const + void Actor::ExtractBoneList(size_t lodLevel, AZStd::vector* outBoneList) const { // clear the existing items outBoneList->clear(); @@ -927,8 +913,8 @@ 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 uint16 nodeNr = skinningLayer->GetInfluence(v, i)->GetNodeNr(); @@ -1122,7 +1108,7 @@ namespace EMotionFX // find the first active parent node in a given skeletal LOD - size_t Actor::FindFirstActiveParentBone(uint32 skeletalLOD, size_t startNodeIndex) const + size_t Actor::FindFirstActiveParentBone(size_t skeletalLOD, size_t startNodeIndex) const { size_t curNodeIndex = startNodeIndex; @@ -1290,7 +1276,7 @@ namespace EMotionFX Node* node = mSkeleton->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); @@ -1493,10 +1479,10 @@ namespace EMotionFX { outPoints.clear(); - const uint32 geomLODLevel = 0; + const size_t geomLODLevel = 0; const size_t numNodes = mSkeleton->GetNumNodes(); - for (int 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); @@ -1744,7 +1730,7 @@ 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 @@ -1793,8 +1779,8 @@ namespace EMotionFX Pose& bindPose = *mSkeleton->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); } @@ -1889,13 +1875,13 @@ namespace EMotionFX } } - void Actor::ReserveMaterials(uint32 lodLevel, uint32 numMaterials) + void Actor::ReserveMaterials(size_t lodLevel, size_t numMaterials) { mMaterials[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.size()); MCORE_ASSERT(nr < mMaterials[lodLevel].size()); @@ -1904,41 +1890,29 @@ namespace EMotionFX // 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.size()); - // search through all materials - const uint32 numMaterials = mMaterials[lodLevel].size(); - for (uint32 i = 0; i < numMaterials; ++i) + const auto foundMaterial = AZStd::find_if(mMaterials[lodLevel].begin(), mMaterials[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 != mMaterials[lodLevel].end() ? AZStd::distance(mMaterials[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.size()); - MCORE_ASSERT(nr < mMaterials[lodLevel].size()); mMaterials[lodLevel][nr] = mat; } - void Actor::AddMaterial(uint32 lodLevel, Material* mat) + void Actor::AddMaterial(size_t lodLevel, Material* mat) { - MCORE_ASSERT(lodLevel < mMaterials.size()); mMaterials[lodLevel].emplace_back(mat); } - size_t Actor::GetNumMaterials(uint32 lodLevel) const + size_t Actor::GetNumMaterials(size_t lodLevel) const { - MCORE_ASSERT(lodLevel < mMaterials.size()); return mMaterials[lodLevel].size(); } @@ -1990,7 +1964,7 @@ namespace EMotionFX } - void Actor::SetMorphSetup(uint32 lodLevel, MorphSetup* setup) + void Actor::SetMorphSetup(size_t lodLevel, MorphSetup* setup) { mMorphSetups[lodLevel] = setup; } @@ -2157,14 +2131,14 @@ namespace EMotionFX return lodLevels[lodLevel].mNodeInfos[nodeIndex].mMesh; } - MeshDeformerStack* Actor::GetMeshDeformerStack(uint32 lodLevel, size_t 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; } // set the mesh for a given node in a given LOD - void Actor::SetMesh(uint32 lodLevel, size_t 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; @@ -2172,14 +2146,14 @@ namespace EMotionFX // set the mesh deformer stack for a given node in a given LOD - void Actor::SetMeshDeformerStack(uint32 lodLevel, size_t 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; } // check if the mesh has a skinning deformer (either linear or dual quat) - bool Actor::CheckIfHasSkinningDeformer(uint32 lodLevel, size_t nodeIndex) const + bool Actor::CheckIfHasSkinningDeformer(size_t lodLevel, size_t nodeIndex) const { // check if there is a mesh Mesh* mesh = GetMesh(lodLevel, nodeIndex); @@ -2199,7 +2173,7 @@ namespace EMotionFX } // remove the mesh for a given node in a given LOD - void Actor::RemoveNodeMeshForLOD(uint32 lodLevel, size_t nodeIndex, bool destroyMesh) + void Actor::RemoveNodeMeshForLOD(size_t lodLevel, size_t nodeIndex, bool destroyMesh) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; @@ -2289,7 +2263,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) @@ -2819,8 +2793,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)); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h index 21b97c0bd6..efcfa52413 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -234,7 +234,7 @@ namespace EMotionFX * @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. @@ -245,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, AZStd::vector* outBoneList) const; + void ExtractBoneList(size_t lodLevel, AZStd::vector* outBoneList) const; //------------------------------------------------ void SetPhysicsSetup(const AZStd::shared_ptr& physicsSetup); @@ -261,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. @@ -269,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. @@ -279,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. @@ -287,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 @@ -306,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. */ - size_t GetNumMaterials(uint32 lodLevel) const; + size_t GetNumMaterials(size_t lodLevel) const; /** * Removes all materials from this actor. @@ -329,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; //------------------------------------------------ @@ -348,20 +348,20 @@ 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. @@ -385,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. @@ -394,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. @@ -404,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. @@ -412,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. @@ -424,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. @@ -438,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(AZStd::vector& 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. @@ -446,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; //------------------ @@ -546,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 mMorphSetups[geomLODLevel]; } /** * Remove all morph setups. Morph setups contain all morph targtets. @@ -561,7 +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); + void SetMorphSetup(size_t lodLevel, MorphSetup* setup); /** * Get the number of node groups inside this actor object. @@ -735,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. */ - size_t FindFirstActiveParentBone(uint32 skeletalLOD, size_t startNodeIndex) const; + size_t FindFirstActiveParentBone(size_t skeletalLOD, size_t startNodeIndex) const; /** * Make the geometry LOD levels compatible with the skinning LOD levels. @@ -777,7 +777,7 @@ namespace EMotionFX uint32 GetThreadIndex() const { return mThreadIndex; } Mesh* GetMesh(size_t lodLevel, size_t nodeIndex) const; - MeshDeformerStack* GetMeshDeformerStack(uint32 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. @@ -790,13 +790,13 @@ namespace EMotionFX MCORE_INLINE Skeleton* GetSkeleton() const { return mSkeleton; } MCORE_INLINE size_t GetNumNodes() const { return mSkeleton->GetNumNodes(); } - void SetMesh(uint32 lodLevel, size_t nodeIndex, Mesh* mesh); - void SetMeshDeformerStack(uint32 lodLevel, size_t 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, size_t nodeIndex) const; - bool CheckIfHasSkinningDeformer(uint32 lodLevel, size_t nodeIndex) const; + bool CheckIfHasMorphDeformer(size_t lodLevel, size_t nodeIndex) const; + bool CheckIfHasSkinningDeformer(size_t lodLevel, size_t nodeIndex) const; - void RemoveNodeMeshForLOD(uint32 lodLevel, size_t nodeIndex, bool destroyMesh = true); + void RemoveNodeMeshForLOD(size_t lodLevel, size_t nodeIndex, bool destroyMesh = true); void SetNumNodes(size_t numNodes); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h index 4b605afc3b..c6bd84c0c8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h @@ -801,7 +801,7 @@ namespace EMotionFX * @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 mEnabledNodes[index]; } /** * Enable all nodes inside the actor instance. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp index 2daaac6a85..34e336bf2f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp @@ -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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h index fc1c986b68..d3bec012f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h @@ -68,7 +68,7 @@ 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index 1203e3762a..c86cc66b61 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -740,7 +740,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); @@ -760,37 +760,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); @@ -800,7 +796,7 @@ namespace EMotionFX maxInfluences = AZStd::max(maxInfluences, numInfluences); } - return aznumeric_cast(maxInfluences); + return maxInfluences; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index 4a86a9875d..420bac0f33 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -462,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. @@ -472,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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp index a7d628b8c3..b269fdecdd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp @@ -45,7 +45,7 @@ namespace EMotionFX // 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..78bdc842e9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h @@ -49,7 +49,7 @@ 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp index c4fae4d3bb..82245a505f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp @@ -114,13 +114,13 @@ namespace EMotionFX // 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.size(); + const size_t numDeformers = mDeformers.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); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h index 020e2b2b75..0b1ce6fbcb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h @@ -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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp index 41b1475927..b40ff27ce0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp @@ -194,7 +194,7 @@ 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(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h index ae56ecc96d..303c379248 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h @@ -103,7 +103,7 @@ 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp index 386f73ae23..0b27ee634e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp @@ -196,7 +196,7 @@ namespace EMotionFX } - void MorphSetup::ReserveMorphTargets(uint32 numMorphTargets) + void MorphSetup::ReserveMorphTargets(size_t numMorphTargets) { mMorphTargets.reserve(numMorphTargets); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h index c7c04ae636..45c55d301c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h @@ -34,7 +34,7 @@ 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. @@ -47,7 +47,7 @@ namespace EMotionFX * @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 mMorphTargets[nr]; } /** * Add a morph target to this morph setup. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h index 829d6f5be6..3e32229691 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. @@ -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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp index d1c23ba04d..4ee07c38f2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp @@ -170,7 +170,7 @@ namespace EMotionFX // 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 @@ -202,7 +202,7 @@ 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) @@ -338,7 +338,7 @@ namespace EMotionFX //--------------------------------------------------- // constructor - MorphTargetStandard::DeformData::DeformData(uint32 nodeIndex, uint32 numVerts) + MorphTargetStandard::DeformData::DeformData(size_t nodeIndex, uint32 numVerts) { mNodeIndex = nodeIndex; mNumVerts = numVerts; @@ -356,7 +356,7 @@ namespace EMotionFX // 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); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h index cda878efbb..d519e98f57 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h @@ -66,7 +66,7 @@ namespace EMotionFX uint32 mVertexNr; /**< 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(); @@ -74,7 +74,7 @@ namespace EMotionFX 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. */ + size_t 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. */ @@ -83,7 +83,7 @@ namespace EMotionFX * @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. @@ -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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp index 5474087574..8f14fcc2b1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp @@ -400,22 +400,22 @@ namespace EMotionFX - void Node::SetSkeletalLODLevelBits(uint32 bitValues) + void Node::SetSkeletalLODLevelBits(size_t bitValues) { mSkeletalLODs = 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); + mSkeletalLODs |= (1ull << lodLevel); } else { - mSkeletalLODs &= ~(1 << lodLevel); + mSkeletalLODs &= ~(1ull << lodLevel); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h index fe22a12c8d..9aa01201d2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h @@ -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(size_t lodLevel) const { return (mSkeletalLODs & (1 << lodLevel)) != 0; } + MCORE_INLINE bool GetSkeletalLODStatus(size_t lodLevel) const { return (mSkeletalLODs & (1ull << lodLevel)) != 0; } //-------------------------------------------- @@ -417,7 +417,7 @@ namespace EMotionFX private: size_t mNodeIndex; /**< The node index, which is the index into the array of nodes inside the Skeleton class. */ size_t 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. */ + size_t mSkeletalLODs; /**< The skeletal LOD status values. Each bit represents if this node is enabled or disabled in the given LOD. */ size_t mNameID; /**< The ID, which is generated from the name. You can use this for fast compares between nodes. */ size_t 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. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp index edc1ea37cd..e708d255d3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp @@ -39,35 +39,35 @@ namespace EMotionFX // preallocate space - void NodeMap::Reserve(uint32 numEntries) + void NodeMap::Reserve(size_t numEntries) { mEntries.reserve(numEntries); } // resize the entries array - void NodeMap::Resize(uint32 numEntries) + void NodeMap::Resize(size_t numEntries) { mEntries.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); } // 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); } // 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); @@ -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) @@ -107,7 +107,7 @@ namespace EMotionFX // remove a given entry by its index - void NodeMap::RemoveEntryByIndex(uint32 entryIndex) + void NodeMap::RemoveEntryByIndex(size_t entryIndex) { mEntries.erase(AZStd::next(begin(mEntries), entryIndex)); } @@ -116,8 +116,8 @@ namespace EMotionFX // 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; } @@ -127,10 +127,10 @@ namespace EMotionFX // remove a given entry by its name ID - void NodeMap::RemoveEntryByNameID(uint32 firstNameID) + void NodeMap::RemoveEntryByNameID(size_t firstNameID) { - const uint32 entryIndex = FindEntryIndexByNameID(firstNameID); - if (entryIndex == MCORE_INVALIDINDEX32) + const size_t entryIndex = FindEntryIndexByNameID(firstNameID); + if (entryIndex == InvalidIndex) { return; } @@ -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.size(); - for (uint32 i = 0; i < numEntries; ++i) + const size_t numEntries = mEntries.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); } @@ -265,7 +265,7 @@ namespace EMotionFX // the main info FileFormat::NodeMapChunk nodeMapChunk{}; - nodeMapChunk.mNumEntries = mEntries.size(); + nodeMapChunk.mNumEntries = aznumeric_caster(mEntries.size()); MCore::Endian::ConvertUnsignedInt32To(&nodeMapChunk.mNumEntries, targetEndianType); if (f.Write(&nodeMapChunk, sizeof(FileFormat::NodeMapChunk)) == 0) { @@ -282,7 +282,7 @@ namespace EMotionFX } // for all entries - const uint32 numEntries = mEntries.size(); + const uint32 numEntries = aznumeric_caster(mEntries.size()); for (uint32 i = 0; i < numEntries; ++i) { if (WriteFileString(&f, GetFirstNameString(i), targetEndianType) == false) @@ -327,28 +327,28 @@ namespace EMotionFX // 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(); } // 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(); } // 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); } // 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); } @@ -357,48 +357,37 @@ namespace EMotionFX // 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.size(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [firstName](const MapEntry& entry) { - const AZStd::string& firstNameEntry = GetFirstName(i); - if (firstNameEntry == firstName) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return MCore::GetStringIdPool().GetName(entry.mFirstNameID) == firstName; + }); + return foundEntry != end(mEntries) ? AZStd::distance(begin(mEntries), foundEntry) : InvalidIndex; } // find an entry index by its name ID - uint32 NodeMap::FindEntryIndexByNameID(uint32 firstNameID) const + size_t NodeMap::FindEntryIndexByNameID(size_t firstNameID) const { - const uint32 numEntries = mEntries.size(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [firstNameID](const MapEntry& entry) { - if (mEntries[i].mFirstNameID == firstNameID) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return entry.mFirstNameID == firstNameID; + }); + return foundEntry != end(mEntries) ? AZStd::distance(begin(mEntries), 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 6db38efc32..ae66a243bb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h @@ -39,41 +39,37 @@ 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) {} + size_t mFirstNameID = InvalidIndex; /**< The first name ID, which is the primary key in the map. */ + size_t mSecondNameID = InvalidIndex; /**< 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 size_t 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; + 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(size_t 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); + void RemoveEntryByNameID(size_t firstNameID); // filename void SetFileName(const char* fileName); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp index 08581e919e..326e0e0448 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp @@ -1334,7 +1334,7 @@ namespace EMotionFX } - void Pose::ResizeNumMorphs(uint32 numMorphTargets) + void Pose::ResizeNumMorphs(size_t numMorphTargets) { mMorphWeights.Resize(numMorphTargets); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h index ef9653e728..be5f24f8e4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h @@ -100,24 +100,24 @@ namespace EMotionFX 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 size_t 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 Transform& GetLocalSpaceTransformDirect(size_t nodeIndex) { return mLocalSpaceTransforms[nodeIndex]; } + MCORE_INLINE Transform& GetModelSpaceTransformDirect(size_t nodeIndex) { return mModelSpaceTransforms[nodeIndex]; } + MCORE_INLINE const Transform& GetLocalSpaceTransformDirect(size_t nodeIndex) const { return mLocalSpaceTransforms[nodeIndex]; } + MCORE_INLINE const Transform& GetModelSpaceTransformDirect(size_t nodeIndex) const { return mModelSpaceTransforms[nodeIndex]; } + MCORE_INLINE void SetLocalSpaceTransformDirect(size_t nodeIndex, const Transform& transform){ mLocalSpaceTransforms[nodeIndex] = transform; mFlags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; } + MCORE_INLINE void SetModelSpaceTransformDirect(size_t nodeIndex, const Transform& transform){ mModelSpaceTransforms[nodeIndex] = transform; mFlags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; } + MCORE_INLINE void InvalidateLocalSpaceTransform(size_t nodeIndex) { mFlags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; } + MCORE_INLINE void InvalidateModelSpaceTransform(size_t 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 void SetMorphWeight(size_t index, float weight) { mMorphWeights[index] = weight; } + MCORE_INLINE float GetMorphWeight(size_t index) const { return mMorphWeights[index]; } + MCORE_INLINE size_t GetNumMorphWeights() const { return mMorphWeights.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 mFlags[nodeIndex]; } + MCORE_INLINE void SetFlags(size_t nodeIndex, uint8 flags) { mFlags[nodeIndex] = flags; } bool HasPoseData(const AZ::TypeId& typeId) const; PoseData* GetPoseDataByType(const AZ::TypeId& typeId) const; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp index c1a8bbd65c..a8fd925123 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp @@ -202,7 +202,7 @@ 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h index 33596e6809..ab2d805ff1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h @@ -71,7 +71,7 @@ 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. 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 4aaebc3e3e..4dabd18e5c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp @@ -210,7 +210,7 @@ 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); @@ -240,11 +240,11 @@ namespace EMStudio mHierarchy->addTopLevelItem(rootItem); // get the number of root nodes and iterate through them - const uint32 numRootNodes = actor->GetSkeleton()->GetNumRootNodes(); + const size_t numRootNodes = actor->GetSkeleton()->GetNumRootNodes(); for (uint32 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 @@ -260,7 +260,7 @@ 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); @@ -288,10 +288,10 @@ 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 = (AZStd::find(begin(mBoneList), end(mBoneList), nodeIndex) != end(mBoneList)); @@ -352,7 +352,7 @@ namespace EMStudio for (uint32 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 @@ -365,7 +365,7 @@ namespace EMStudio for (uint32 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 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 b55062f57b..e4dd215819 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h @@ -133,7 +133,7 @@ namespace EMStudio QIcon* mNodeIcon; QIcon* mMeshIcon; QIcon* mCharacterIcon; - AZStd::vector mBoneList; + AZStd::vector mBoneList; AZStd::vector mActorInstanceIDs; AZStd::string mItemName; AZStd::string mActorInstanceIDString; 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 27e5504e72..f55604b38c 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 @@ -53,7 +53,7 @@ namespace EMStudio MCORE_MEMORYOBJECTCATEGORY(RenderPlugin::EMStudioRenderActor, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); EMotionFX::Actor* mActor; - AZStd::vector mBoneList; + AZStd::vector mBoneList; RenderGL::GLActor* mRenderActor; AZStd::vector mActorInstances; float mNormalsScaleMultiplier; 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..49b1d1b8f3 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 @@ -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..28215e59c9 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 @@ -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/NodeWindowPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.cpp index 3d7e44dac3..7b47b8cb43 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 @@ -286,18 +286,18 @@ namespace EMStudio // 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 - AZStd::vector 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,7 +305,7 @@ 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 = (AZStd::find(begin(boneList), end(boneList), nodeIndex) != end(boneList)); 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/MirrorSetupWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.cpp index 271f277ed1..fc01f68efe 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 @@ -329,7 +329,7 @@ namespace EMStudio MCORE_ASSERT(node); // remove the mapping for this node - PerformMapping(node->GetNodeIndex(), MCORE_INVALIDINDEX32); + PerformMapping(node->GetNodeIndex(), InvalidIndex); } @@ -443,10 +443,7 @@ namespace EMStudio { const size_t numNodes = aznumeric_caster(currentActor->GetNumNodes()); mMap.resize(numNodes); - for (uint32 i = 0; i < numNodes; ++i) - { - mMap[i] = MCORE_INVALIDINDEX32; - } + AZStd::fill(mMap.begin(), mMap.end(), InvalidIndex); } } @@ -490,11 +487,11 @@ namespace EMStudio // 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()) @@ -505,15 +502,15 @@ namespace EMStudio mCurrentList->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 = (mMap[node->GetNodeIndex()] != InvalidIndex); QTableWidgetItem* mappedItem = new QTableWidgetItem(); mappedItem->setIcon(mapped ? *mMappedIcon : QIcon()); mCurrentList->setItem(rowIndex, 0, mappedItem); @@ -524,8 +521,7 @@ namespace EMStudio { typeItem->setIcon(*mMeshIcon); } - else - if (AZStd::find(begin(mCurrentBoneList), end(mCurrentBoneList), node->GetNodeIndex()) != end(mCurrentBoneList)) + else if (AZStd::find(begin(mCurrentBoneList), end(mCurrentBoneList), node->GetNodeIndex()) != end(mCurrentBoneList)) { typeItem->setIcon(*mBoneIcon); } @@ -559,11 +555,11 @@ namespace EMStudio // 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()) @@ -574,8 +570,8 @@ namespace EMStudio mSourceList->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(); @@ -593,8 +589,7 @@ namespace EMStudio { typeItem->setIcon(*mMeshIcon); } - else - if (AZStd::find(mSourceBoneList.begin(), mSourceBoneList.end(), node->GetNodeIndex()) != mSourceBoneList.end()) + else if (AZStd::find(mSourceBoneList.begin(), mSourceBoneList.end(), node->GetNodeIndex()) != mSourceBoneList.end()) { typeItem->setIcon(*mBoneIcon); } @@ -629,9 +624,9 @@ namespace EMStudio // fill the table QString currentName; QString sourceName; - const uint32 numNodes = currentActor->GetNumNodes(); + const int numNodes = aznumeric_caster(currentActor->GetNumNodes()); mMappingTable->setRowCount(numNodes); - for (uint32 i = 0; i < numNodes; ++i) + for (int i = 0; i < numNodes; ++i) { currentName = currentActor->GetSkeleton()->GetNode(i)->GetName(); @@ -639,7 +634,7 @@ namespace EMStudio mMappingTable->setItem(i, 0, currentTableItem); mMappingTable->setRowHeight(i, 21); - if (mMap[i] != MCORE_INVALIDINDEX32) + if (mMap[i] != InvalidIndex) { sourceName = sourceActor->GetSkeleton()->GetNode(mMap[i])->GetName(); currentTableItem = new QTableWidgetItem(sourceName); @@ -650,8 +645,6 @@ namespace EMStudio mMappingTable->setItem(i, 1, new QTableWidgetItem()); } } - //mMappingTable->resizeColumnsToContents(); - //mMappingTable->setColumnWidth(0, mMappingTable->columnWidth(0) + 25); } @@ -694,12 +687,12 @@ 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]; + const size_t oldSourceIndex = mMap[currentNodeIndex]; mMap[currentNodeIndex] = sourceNodeIndex; // update the current table @@ -707,9 +700,7 @@ namespace EMStudio const QList currentListItems = mCurrentList->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); if (!mappedItem) @@ -718,7 +709,7 @@ namespace EMStudio mCurrentList->setItem(rowIndex, 0, mappedItem); } - if (sourceNodeIndex == MCORE_INVALIDINDEX32) + if (sourceNodeIndex == InvalidIndex) { mappedItem->setIcon(QIcon()); } @@ -729,16 +720,14 @@ namespace EMStudio } // update source table - if (sourceNodeIndex != MCORE_INVALIDINDEX32) + if (sourceNodeIndex != InvalidIndex) { const bool stillUsed = AZStd::find(mMap.begin(), mMap.end(), sourceNodeIndex) != mMap.end(); const QString sourceName = currentActor->GetSkeleton()->GetNode(sourceNodeIndex)->GetName(); const QList sourceListItems = mSourceList->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); if (!mappedItem) @@ -759,16 +748,14 @@ namespace EMStudio } 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 QString sourceName = currentActor->GetSkeleton()->GetNode(oldSourceIndex)->GetName(); const QList sourceListItems = mSourceList->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); if (!mappedItem) @@ -790,14 +777,14 @@ namespace EMStudio } // update the mapping table - QTableWidgetItem* item = mMappingTable->item(currentNodeIndex, 1); - if (!item && sourceNodeIndex != MCORE_INVALIDINDEX32) + QTableWidgetItem* item = mMappingTable->item(aznumeric_caster(currentNodeIndex), 1); + if (!item && sourceNodeIndex != InvalidIndex) { item = new QTableWidgetItem(); - mMappingTable->setItem(currentNodeIndex, 1, item); + mMappingTable->setItem(aznumeric_caster(currentNodeIndex), 1, item); } - if (sourceNodeIndex == MCORE_INVALIDINDEX32) + if (sourceNodeIndex == InvalidIndex) { if (item) { @@ -893,15 +880,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(mMap.begin(), AZStd::next(mMap.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)); @@ -963,12 +947,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 (mMap[i] == InvalidIndex) { continue; } @@ -1033,16 +1017,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(mMap.begin(), AZStd::next(mMap.begin(), numNodes), [](const size_t nodeIndex) { - if (mMap[i] != MCORE_INVALIDINDEX32) - { - return false; - } - } - - return true; + return nodeIndex != InvalidIndex; + }); } @@ -1081,20 +1060,13 @@ namespace EMStudio 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 (mMap[i] != InvalidIndex) { continue; } @@ -1110,28 +1082,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 +1098,7 @@ namespace EMStudio { return; } - /* - const uint32 numNodes = currentActor->GetNumNodes(); - for (uint32 i=0; i( mMap[i] ); - } - */ // apply the current map as command ApplyCurrentMapAsCommand(); } @@ -1172,8 +1112,8 @@ 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()) { @@ -1184,12 +1124,12 @@ namespace EMStudio } else { - mMap[i] = MCORE_INVALIDINDEX32; + mMap[i] = InvalidIndex; } } else { - mMap[i] = MCORE_INVALIDINDEX32; + mMap[i] = InvalidIndex; } } } @@ -1207,10 +1147,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 = mMap[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 13bb98334c..660359ba4a 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 @@ -79,14 +79,14 @@ namespace EMStudio QIcon* mNodeIcon; QIcon* mMeshIcon; QIcon* mMappedIcon; - AZStd::vector mCurrentBoneList; - AZStd::vector mSourceBoneList; - AZStd::vector mMap; + AZStd::vector mCurrentBoneList; + AZStd::vector mSourceBoneList; + AZStd::vector mMap; 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/Source/Editor/SkeletonModel.cpp b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp index 8530521458..95e08eab77 100644 --- a/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp @@ -615,31 +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 = AZStd::any_of(begin(boneListPerLodLevel), end(boneListPerLodLevel), [nodeIndex](const AZStd::vector& lodLevel) + nodeInfo.m_isBone = AZStd::any_of(begin(boneListPerLodLevel), end(boneListPerLodLevel), [nodeIndex](const AZStd::vector& lodLevel) { 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)) { From 7a8f96873816fcd9cf7c42b22ea38bb12150f254 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:13 -0700 Subject: [PATCH 182/251] Convert Pose uint32 -> size_t Signed-off-by: Chris Burel --- .../EMotionFX/Source/MorphSetupInstance.cpp | 22 +- .../EMotionFX/Source/MorphSetupInstance.h | 8 +- Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp | 317 ++++++++---------- Gems/EMotionFX/Code/EMotionFX/Source/Pose.h | 2 +- 4 files changed, 156 insertions(+), 193 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp index 456056d00f..df4aaa0e7c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp @@ -61,7 +61,7 @@ namespace EMotionFX } // allocate the number of morph targets - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); mMorphTargets.resize(numMorphTargets); // update the ID values @@ -73,27 +73,21 @@ namespace EMotionFX // 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.size(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundElement = AZStd::find_if(mMorphTargets.begin(), mMorphTargets.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 != mMorphTargets.end() ? AZStd::distance(mMorphTargets.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]; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h index e597cb7a63..e93ed7cf6d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h @@ -130,16 +130,16 @@ namespace EMotionFX * @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 &mMorphTargets[nr]; } - MCORE_INLINE const MorphTarget* GetMorphTarget(uint32 nr) const { return &mMorphTargets[nr]; } + MCORE_INLINE const MorphTarget* GetMorphTarget(size_t nr) const { return &mMorphTargets[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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp index 326e0e0448..096b32b041 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp @@ -60,7 +60,7 @@ namespace EMotionFX mSkeleton = mActor->GetSkeleton(); // resize the buffers - const uint32 numTransforms = mActor->GetSkeleton()->GetNumNodes(); + const size_t numTransforms = mActor->GetSkeleton()->GetNumNodes(); mLocalSpaceTransforms.ResizeFast(numTransforms); mModelSpaceTransforms.ResizeFast(numTransforms); mFlags.ResizeFast(numTransforms); @@ -84,15 +84,15 @@ namespace EMotionFX mSkeleton = actor->GetSkeleton(); // resize the buffers - const uint32 numTransforms = mActor->GetSkeleton()->GetNumNodes(); + const size_t numTransforms = mActor->GetSkeleton()->GetNumNodes(); mLocalSpaceTransforms.ResizeFast(numTransforms); mModelSpaceTransforms.ResizeFast(numTransforms); - const uint32 oldSize = mFlags.GetLength(); + const size_t oldSize = mFlags.GetLength(); mFlags.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; } @@ -189,35 +189,15 @@ 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) + 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(); @@ -238,11 +218,11 @@ namespace EMotionFX { // 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) + 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]); } @@ -261,8 +241,8 @@ namespace EMotionFX { Skeleton* skeleton = mActor->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 && !(mFlags[parentIndex] & FLAG_MODELTRANSFORMREADY)) { UpdateModelSpaceTransform(parentIndex); } @@ -271,7 +251,7 @@ namespace EMotionFX if ((mFlags[nodeIndex] & FLAG_MODELTRANSFORMREADY) == false) { const Transform& localTransform = GetLocalSpaceTransform(nodeIndex); - if (parentIndex != MCORE_INVALIDINDEX32) + if (parentIndex != InvalidIndex) { mModelSpaceTransforms[parentIndex].PreMultiply(localTransform, &mModelSpaceTransforms[nodeIndex]); } @@ -288,19 +268,17 @@ namespace EMotionFX // update the local transform void Pose::UpdateLocalSpaceTransform(size_t nodeIndex) const { - const uint32 flags = mFlags[nodeIndex]; + const uint8 flags = mFlags[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) + const size_t parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); + if (parentIndex != InvalidIndex) { GetModelSpaceTransform(parentIndex, &mLocalSpaceTransforms[nodeIndex]); mLocalSpaceTransforms[nodeIndex].Inverse(); @@ -441,8 +419,8 @@ 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 = mFlags.GetLength(); + for (size_t i = 0; i < numFlags; ++i) { mFlags[i] &= ~FLAG_LOCALTRANSFORMREADY; } @@ -451,8 +429,8 @@ namespace EMotionFX void Pose::InvalidateAllModelSpaceTransforms() { - const uint32 numFlags = mFlags.GetLength(); - for (uint32 i = 0; i < numFlags; ++i) + const size_t numFlags = mFlags.GetLength(); + for (size_t i = 0; i < numFlags; ++i) { mFlags[i] &= ~FLAG_MODELTRANSFORMREADY; } @@ -461,8 +439,8 @@ namespace EMotionFX void Pose::InvalidateAllLocalAndModelSpaceTransforms() { - const uint32 numFlags = mFlags.GetLength(); - for (uint32 i = 0; i < numFlags; ++i) + const size_t numFlags = mFlags.GetLength(); + for (size_t i = 0; i < numFlags; ++i) { mFlags[i] &= ~(FLAG_LOCALTRANSFORMREADY | FLAG_MODELTRANSFORMREADY); } @@ -472,8 +450,8 @@ namespace EMotionFX Transform Pose::CalcTrajectoryTransform() const { MCORE_ASSERT(mActor); - const uint32 motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); - if (motionExtractionNodeIndex == MCORE_INVALIDINDEX32) + const size_t motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); + if (motionExtractionNodeIndex == InvalidIndex) { return Transform::CreateIdentity(); } @@ -485,8 +463,8 @@ namespace EMotionFX void Pose::UpdateAllLocalSpaceTranforms() { Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { UpdateLocalSpaceTransform(i); } @@ -496,8 +474,8 @@ namespace EMotionFX void Pose::UpdateAllModelSpaceTranforms() { Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { UpdateModelSpaceTransform(i); } @@ -532,11 +510,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,10 +530,10 @@ namespace EMotionFX } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.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); } @@ -565,12 +542,11 @@ namespace EMotionFX { 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,10 +554,10 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.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; } @@ -614,11 +590,10 @@ namespace EMotionFX // 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,10 +610,10 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.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); } @@ -646,11 +621,10 @@ namespace EMotionFX 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,10 +640,10 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.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; } @@ -767,32 +741,31 @@ namespace EMotionFX { if (mActorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = mActorInstance->GetEnabledNode(i); mLocalSpaceTransforms[nodeNr].Zero(); } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { mMorphWeights[i] = 0.0f; } } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { mLocalSpaceTransforms[i].Zero(); } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { mMorphWeights[i] = 0.0f; } @@ -807,19 +780,18 @@ namespace EMotionFX { if (mActorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = mActorInstance->GetEnabledNode(i); UpdateLocalSpaceTransform(nodeNr); mLocalSpaceTransforms[nodeNr].mRotation.Normalize(); } } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { UpdateLocalSpaceTransform(i); mLocalSpaceTransforms[i].mRotation.Normalize(); @@ -833,11 +805,10 @@ namespace EMotionFX { if (mActorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); const Transform& otherTransform = other->GetLocalSpaceTransform(nodeNr); @@ -845,18 +816,18 @@ namespace EMotionFX } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActorInstance->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; } } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& otherTransform = other->GetLocalSpaceTransform(i); @@ -864,10 +835,10 @@ namespace EMotionFX } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActor->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; } @@ -882,20 +853,19 @@ namespace EMotionFX { if (mActorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& curTransform = const_cast(GetLocalSpaceTransform(nodeNr)); curTransform.Blend(destPose->GetLocalSpaceTransform(nodeNr), weight); } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActorInstance->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); } @@ -908,18 +878,18 @@ namespace EMotionFX } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->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(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActor->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); } @@ -940,27 +910,27 @@ namespace EMotionFX AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); if (mActorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = mActorInstance->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 = mLocalSpaceTransforms.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 = mMorphWeights.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]; } @@ -993,8 +963,8 @@ namespace EMotionFX AZ_Assert(mLocalSpaceTransforms.GetLength() == additivePose.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); if (mActorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); @@ -1010,8 +980,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mLocalSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& additiveTransform = additivePose.GetLocalSpaceTransform(i); @@ -1025,9 +995,9 @@ namespace EMotionFX } } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.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; } @@ -1043,8 +1013,8 @@ namespace EMotionFX AZ_Assert(mLocalSpaceTransforms.GetLength() == additivePose.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); if (mActorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); @@ -1060,8 +1030,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mLocalSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& additiveTransform = additivePose.GetLocalSpaceTransform(i); @@ -1075,9 +1045,9 @@ namespace EMotionFX } } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.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]; } @@ -1092,8 +1062,8 @@ namespace EMotionFX AZ_Assert(mLocalSpaceTransforms.GetLength() == refPose.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); if (mActorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); @@ -1108,8 +1078,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mLocalSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& refTransform = refPose.GetLocalSpaceTransform(i); @@ -1122,9 +1092,9 @@ namespace EMotionFX } } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = mMorphWeights.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]; } @@ -1143,20 +1113,19 @@ namespace EMotionFX Pose* bindPose = transformData->GetBindPose(); Transform result; - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = mActorInstance->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(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActorInstance->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; } @@ -1167,18 +1136,18 @@ namespace EMotionFX Pose* bindPose = transformData->GetBindPose(); Transform result; - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->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(); + const size_t numMorphs = mMorphWeights.GetLength(); MCORE_ASSERT(mActor->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; } @@ -1284,8 +1253,8 @@ 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 = mActor->GetMotionExtractionNodeIndex(); + if (motionExtractionNodeIndex != InvalidIndex) { Transform motionExtractionNodeTransform = GetLocalSpaceTransformDirect(motionExtractionNodeIndex); mActorInstance->MotionExtractionCompensate(motionExtractionNodeTransform, motionExtractionFlags); @@ -1297,8 +1266,8 @@ 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 = mActor->GetMotionExtractionNodeIndex(); + if (motionExtractionNodeIndex != InvalidIndex) { Transform motionExtractionNodeTransform = GetLocalSpaceTransform(motionExtractionNodeIndex); mActorInstance->MotionExtractionCompensate(motionExtractionNodeTransform, motionExtractionFlags); @@ -1311,8 +1280,8 @@ namespace EMotionFX void Pose::ApplyMorphWeightsToActorInstance() { MorphSetupInstance* morphSetupInstance = mActorInstance->GetMorphSetupInstance(); - const uint32 numMorphs = morphSetupInstance->GetNumMorphTargets(); - for (uint32 m = 0; m < numMorphs; ++m) + const size_t numMorphs = morphSetupInstance->GetNumMorphTargets(); + for (size_t m = 0; m < numMorphs; ++m) { MorphSetupInstance::MorphTarget* morphTarget = morphSetupInstance->GetMorphTarget(m); if (morphTarget->GetIsInManualMode() == false) @@ -1326,8 +1295,8 @@ 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 = mMorphWeights.GetLength(); + for (size_t m = 0; m < numMorphs; ++m) { mMorphWeights[m] = 0.0f; } @@ -1345,10 +1314,10 @@ namespace EMotionFX AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); if (mActorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); Transform otherTransform = other.GetLocalSpaceTransform(nodeNr); transform = otherTransform * transform; @@ -1356,8 +1325,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mLocalSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); Transform otherTransform = other.GetLocalSpaceTransform(i); @@ -1375,8 +1344,8 @@ namespace EMotionFX AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); if (mActorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); @@ -1385,8 +1354,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mLocalSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); transform.Multiply(other.GetLocalSpaceTransform(i)); @@ -1403,8 +1372,8 @@ namespace EMotionFX AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); if (mActorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { uint16 nodeNr = mActorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); @@ -1415,8 +1384,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mLocalSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); Transform otherTransform = other.GetLocalSpaceTransform(i); @@ -1430,7 +1399,7 @@ namespace EMotionFX } - Transform Pose::GetMeshNodeWorldSpaceTransform(AZ::u32 lodLevel, AZ::u32 nodeIndex) const + Transform Pose::GetMeshNodeWorldSpaceTransform(size_t lodLevel, size_t nodeIndex) const { if (!mActorInstance) { @@ -1461,12 +1430,12 @@ namespace EMotionFX Pose& unmirroredPose = tempPose->GetPose(); unmirroredPose = *this; - const AZ::u32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActorInstance->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 = mActorInstance->GetEnabledNode(i); + const size_t jointDataIndex = jointLinks[nodeNumber]; + if (jointDataIndex == InvalidIndex) { continue; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h index be5f24f8e4..58dcb59ee4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h @@ -90,7 +90,7 @@ namespace EMotionFX * @param The LOD level, which must be in range of 0..mActor->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(); From 8314f8caf3d58999c866c5b4afc58954474a61fb Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:14 -0700 Subject: [PATCH 183/251] Update ActorInstance uint32->size_t Signed-off-by: Chris Burel --- .../Code/EMotionFX/Source/ActorInstance.cpp | 191 +++++++----------- .../Code/EMotionFX/Source/ActorInstance.h | 42 ++-- .../Code/EMotionFX/Source/SubMesh.cpp | 41 +--- .../EMotionFX/Code/EMotionFX/Source/SubMesh.h | 14 +- 4 files changed, 115 insertions(+), 173 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index eaa09f92c0..65eb038dbf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -94,8 +94,8 @@ namespace EMotionFX } // disable nodes that are disabled in LOD 0 Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { if (skeleton->GetNode(n)->GetSkeletalLODStatus(0) == false) { @@ -170,8 +170,8 @@ namespace EMotionFX // delete all attachments // actor instances that are attached will be detached, and not deleted from memory - const uint32 numAttachments = mAttachments.size(); - for (uint32 i = 0; i < numAttachments; ++i) + const size_t numAttachments = mAttachments.size(); + for (size_t i = 0; i < numAttachments; ++i) { ActorInstance* attachmentActorInstance = mAttachments[i]->GetAttachmentActorInstance(); if (attachmentActorInstance) @@ -375,10 +375,10 @@ namespace EMotionFX AZ::Matrix3x4* skinningMatrices = mTransformData->GetSkinningMatrices(); const Pose* pose = mTransformData->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); + const size_t nodeNumber = GetEnabledNode(i); Transform skinningTransform = mActor->GetInverseBindPoseTransform(nodeNumber); skinningTransform.Multiply(pose->GetModelSpaceTransform(nodeNumber)); skinningMatrices[nodeNumber] = AZ::Matrix3x4::CreateFromTransform(skinningTransform.ToAZTransform()); @@ -392,10 +392,8 @@ namespace EMotionFX // Update the mesh deformers. const Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = mEnabledNodes.size(); - for (uint32 i = 0; i < numNodes; ++i) + for (uint16 nodeNr : mEnabledNodes) { - const uint16 nodeNr = mEnabledNodes[i]; Node* node = skeleton->GetNode(nodeNr); MeshDeformerStack* stack = mActor->GetMeshDeformerStack(mLODLevel, nodeNr); if (stack) @@ -412,10 +410,8 @@ namespace EMotionFX // Update the mesh morph deformers. const Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = mEnabledNodes.size(); - for (uint32 i = 0; i < numNodes; ++i) + for (uint16 nodeNr : mEnabledNodes) { - const uint16 nodeNr = mEnabledNodes[i]; Node* node = skeleton->GetNode(nodeNr); MeshDeformerStack* stack = mActor->GetMeshDeformerStack(mLODLevel, nodeNr); if (stack) @@ -461,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.size(); - for (uint32 i = 0; i < numAttachments; ++i) + const auto foundAttachment = AZStd::find_if(mAttachments.begin(), mAttachments.end(), [actorInstance](const Attachment* attachment) { - if (mAttachments[i]->GetAttachmentActorInstance() == actorInstance) - { - return i; - } - } + return attachment->GetAttachmentActorInstance() == actorInstance; + }); - return MCORE_INVALIDINDEX32; + return foundAttachment == mAttachments.end() ? AZStd::distance(mAttachments.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; } @@ -492,7 +484,7 @@ namespace EMotionFX } // remove an attachment - void ActorInstance::RemoveAttachment(uint32 nr, bool delFromMem) + void ActorInstance::RemoveAttachment(size_t nr, bool delFromMem) { MCORE_ASSERT(nr < mAttachments.size()); @@ -559,8 +551,8 @@ namespace EMotionFX mDependencies.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 = mActor->GetNumDependencies(); + for (size_t i = 0; i < numDependencies; ++i) { mDependencies.emplace_back(*mActor->GetDependency(i)); } @@ -569,11 +561,9 @@ namespace EMotionFX // set the attachment matrices void ActorInstance::UpdateAttachments() { - // update all attachments - const uint32 numAttachments = mAttachments.size(); - for (uint32 i = 0; i < numAttachments; ++i) + for (Attachment* mAttachment : mAttachments) { - mAttachments[i]->Update(); + mAttachment->Update(); } } @@ -604,7 +594,7 @@ 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) @@ -650,11 +640,10 @@ namespace EMotionFX 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) + 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->AddPoint(pose->GetWorldSpaceTransform(nodeNr).mPosition); @@ -663,7 +652,7 @@ namespace EMotionFX } // calculate the AABB that contains all world space vertices of all meshes - void ActorInstance::CalcMeshBasedAabb(uint32 geomLODLevel, AZ::Aabb* outResult, uint32 vertexFrequency) + void ActorInstance::CalcMeshBasedAabb(size_t geomLODLevel, AZ::Aabb* outResult, uint32 vertexFrequency) { *outResult = AZ::Aabb::CreateNull(); @@ -671,8 +660,8 @@ namespace EMotionFX const Skeleton* skeleton = mActor->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); @@ -728,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); @@ -749,32 +738,19 @@ 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(); // 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); @@ -802,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; @@ -817,11 +793,10 @@ namespace EMotionFX const Pose* pose = mTransformData->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); if (mesh == nullptr) @@ -917,17 +892,16 @@ 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(); // 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 @@ -968,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; @@ -983,11 +957,10 @@ namespace EMotionFX const Skeleton* skeleton = mActor->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); if (mesh == nullptr) @@ -1094,12 +1067,12 @@ namespace EMotionFX // 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 auto parentArrayIter = AZStd::find(begin(mEnabledNodes), end(mEnabledNodes), static_cast(parentIndex)); if (parentArrayIter != end(mEnabledNodes)) @@ -1141,12 +1114,8 @@ namespace EMotionFX // 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); - } + mEnabledNodes.resize(mActor->GetNumNodes()); + std::iota(mEnabledNodes.begin(), mEnabledNodes.end(), 0); } // disable all nodes @@ -1156,10 +1125,10 @@ namespace EMotionFX } // 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) @@ -1170,8 +1139,8 @@ namespace EMotionFX Skeleton* skeleton = mActor->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); @@ -1194,7 +1163,7 @@ namespace EMotionFX } } - void ActorInstance::SetLODLevel(uint32 level) + void ActorInstance::SetLODLevel(size_t level) { m_requestedLODLevel = level; } @@ -1208,14 +1177,7 @@ namespace EMotionFX 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 );*/ + mLODLevel = MCore::Clamp(m_requestedLODLevel, 0, mActor->GetNumLODLevels() - 1); } } @@ -1224,8 +1186,8 @@ namespace EMotionFX { // 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) + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Node* node = skeleton->GetNode(i); @@ -1242,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 = mActor->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); @@ -1266,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); @@ -1471,7 +1433,7 @@ namespace EMotionFX return mActor; } - void ActorInstance::SetID(uint32 id) + void ActorInstance::SetID(size_t id) { mID = id; } @@ -1481,7 +1443,7 @@ namespace EMotionFX return mMotionSystem; } - uint32 ActorInstance::GetLODLevel() const + size_t ActorInstance::GetLODLevel() const { return mLODLevel; } @@ -1592,7 +1554,7 @@ namespace EMotionFX return mAttachments.size(); } - Attachment* ActorInstance::GetAttachment(uint32 nr) const + Attachment* ActorInstance::GetAttachment(size_t nr) const { return mAttachments[nr]; } @@ -1617,7 +1579,7 @@ namespace EMotionFX return mDependencies.size(); } - Actor::Dependency* ActorInstance::GetDependency(uint32 nr) + Actor::Dependency* ActorInstance::GetDependency(size_t nr) { return &mDependencies[nr]; } @@ -1779,10 +1741,9 @@ namespace EMotionFX SetIsVisible(isVisible); // recurse to all child attachments - const uint32 numAttachments = mAttachments.size(); - for (uint32 i = 0; i < numAttachments; ++i) + for (Attachment* mAttachment : mAttachments) { - mAttachments[i]->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); + mAttachment->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); } } @@ -1846,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 c6bd84c0c8..620ecc29c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h @@ -75,13 +75,13 @@ 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 size_t GetID() const { return mID; } /** * Set the unique identification number for the actor instance. * @param[in] id The unique identification number. */ - void SetID(uint32 id); + void SetID(size_t id); /** * Get the motion system of this actor instance. @@ -181,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 @@ -189,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. @@ -199,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); //-------------------------------- @@ -423,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. @@ -465,7 +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, AZ::Aabb* outResult, uint32 vertexFrequency = 1); + void CalcMeshBasedAabb(size_t geomLODLevel, AZ::Aabb* outResult, uint32 vertexFrequency = 1); /** * Get the axis aligned bounding box. @@ -568,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. @@ -593,7 +593,7 @@ 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. @@ -606,7 +606,7 @@ namespace EMotionFX * @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. @@ -671,7 +671,7 @@ namespace EMotionFX * @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. @@ -692,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. @@ -711,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. @@ -721,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. @@ -741,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; @@ -856,7 +856,7 @@ namespace EMotionFX float GetMotionSamplingTimer() const; float GetMotionSamplingRate() const; - MCORE_INLINE uint32 GetNumNodes() const { return mActor->GetSkeleton()->GetNumNodes(); } + MCORE_INLINE size_t GetNumNodes() const { return mActor->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; @@ -892,10 +892,10 @@ namespace EMotionFX 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. */ + size_t mLODLevel; /**< 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 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. */ + size_t 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 collision mesh based). */ float m_boundsExpandBy = 0.25f; /**< Expand bounding box by normalized percentage. (Default: 25% greater than the calculated bounding box) */ @@ -1002,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/SubMesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp index fa60ed4033..d18006527f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp @@ -19,7 +19,7 @@ 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; @@ -41,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); } @@ -57,20 +57,9 @@ namespace EMotionFX // 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.size(); - - // 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(mBones.begin(), mBones.end(), oldNodeNr, newNodeNr); } @@ -97,7 +86,7 @@ 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 (AZStd::find(begin(mBones), end(mBones), nodeNr) == end(mBones)) @@ -228,29 +217,21 @@ namespace EMotionFX } - uint32 SubMesh::FindBoneIndex(uint32 nodeNr) const + size_t SubMesh::FindBoneIndex(size_t nodeNr) const { - const uint32 numBones = mBones.size(); - for (uint32 i = 0; i < numBones; ++i) - { - if (mBones[i] == nodeNr) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + const auto foundBone = AZStd::find(mBones.begin(), mBones.end(), nodeNr); + return foundBone != mBones.end() ? AZStd::distance(mBones.begin(), foundBone) : InvalidIndex; } // remove the given bone - void SubMesh::RemoveBone(uint16 index) + void SubMesh::RemoveBone(size_t index) { mBones.erase(AZStd::next(begin(mBones), index)); } - void SubMesh::SetNumBones(uint32 numBones) + void SubMesh::SetNumBones(size_t numBones) { if (numBones == 0) { @@ -263,7 +244,7 @@ namespace EMotionFX } - void SubMesh::SetBone(uint32 index, uint32 nodeIndex) + void SubMesh::SetBone(size_t index, size_t nodeIndex) { mBones[index] = nodeIndex; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h index 9455b6b7df..d234a9e4c1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h @@ -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,14 +178,14 @@ 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. @@ -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. @@ -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. From 4034195bdcce34f041298402a3477f28b5125114 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:16 -0700 Subject: [PATCH 184/251] Convert EMotionFX runtime uint32 -> size_t This allows the EMotionFX runtime to compile with `/we4267` enabled, which emits a warning when converting from `size_t` to a smaller type. All tests for the runtime have been updated accordingly, and they pass. In instances where a range-for loop could be used, or a std algorithm, that was used instead of using `size_t numItems = vec.size()` and a for loop. Casts to `uint32` were removed where possible. Some places remain, like in the file formats. Signed-off-by: Chris Burel --- .../CommandSystem/Source/ActorCommands.cpp | 93 +++-- .../CommandSystem/Source/ActorCommands.h | 8 +- .../Source/ActorInstanceCommands.cpp | 22 +- .../Source/ActorInstanceCommands.h | 4 +- .../Source/AnimGraphCommands.cpp | 30 +- .../Source/AnimGraphConnectionCommands.cpp | 44 +-- .../Source/AnimGraphConnectionCommands.h | 16 +- .../Source/AnimGraphNodeCommands.cpp | 71 ++-- .../Source/AnimGraphNodeGroupCommands.cpp | 26 +- .../Source/AnimGraphParameterCommands.cpp | 22 +- .../Source/AnimGraphParameterCommands.h | 4 +- .../Source/AttachmentCommands.cpp | 10 +- .../CommandSystem/Source/MetaData.cpp | 19 +- .../CommandSystem/Source/MotionCommands.cpp | 47 ++- .../CommandSystem/Source/MotionCommands.h | 6 +- .../Source/MotionEventCommands.cpp | 38 +- .../Source/MotionEventCommands.h | 18 +- .../Source/MotionSetCommands.cpp | 55 ++- .../Source/SelectionCommands.cpp | 38 +- .../CommandSystem/Source/SelectionList.cpp | 63 ++- .../CommandSystem/Source/SelectionList.h | 38 +- .../Source/SimulatedObjectCommands.cpp | 20 +- .../Source/SimulatedObjectCommands.h | 23 +- .../Exporters/ExporterLib/Exporter/Exporter.h | 4 +- .../Exporter/MorphTargetExport.cpp | 47 ++- .../ExporterLib/Exporter/NodeExport.cpp | 89 ++--- .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 9 +- .../Code/EMotionFX/Source/ActorInstance.cpp | 6 +- .../Code/EMotionFX/Source/ActorInstance.h | 6 +- .../Code/EMotionFX/Source/ActorManager.cpp | 67 +--- .../Code/EMotionFX/Source/ActorManager.h | 18 +- .../EMotionFX/Source/ActorUpdateScheduler.h | 18 +- .../Code/EMotionFX/Source/AnimGraph.cpp | 83 ++-- .../Code/EMotionFX/Source/AnimGraph.h | 40 +- .../Source/AnimGraphAttributeTypes.cpp | 2 +- .../Source/AnimGraphAttributeTypes.h | 2 +- .../EMotionFX/Source/AnimGraphEventBuffer.cpp | 12 +- .../EMotionFX/Source/AnimGraphEventBuffer.h | 10 +- .../EMotionFX/Source/AnimGraphInstance.cpp | 131 +++---- .../Code/EMotionFX/Source/AnimGraphInstance.h | 66 ++-- .../EMotionFX/Source/AnimGraphManager.cpp | 24 +- .../Code/EMotionFX/Source/AnimGraphManager.h | 8 +- .../Source/AnimGraphMotionCondition.cpp | 4 +- .../Code/EMotionFX/Source/AnimGraphNode.cpp | 302 ++++++-------- .../Code/EMotionFX/Source/AnimGraphNode.h | 170 ++++---- .../EMotionFX/Source/AnimGraphNodeData.cpp | 4 +- .../Code/EMotionFX/Source/AnimGraphNodeData.h | 6 +- .../EMotionFX/Source/AnimGraphNodeGroup.cpp | 14 +- .../EMotionFX/Source/AnimGraphNodeGroup.h | 12 +- .../Code/EMotionFX/Source/AnimGraphObject.cpp | 6 +- .../Code/EMotionFX/Source/AnimGraphObject.h | 12 +- .../Code/EMotionFX/Source/AnimGraphPose.h | 2 +- .../EMotionFX/Source/AnimGraphPosePool.cpp | 29 +- .../Code/EMotionFX/Source/AnimGraphPosePool.h | 8 +- .../Source/AnimGraphRefCountedDataPool.cpp | 25 +- .../Source/AnimGraphRefCountedDataPool.h | 8 +- .../Source/AnimGraphReferenceNode.cpp | 6 +- .../EMotionFX/Source/AnimGraphSnapshot.cpp | 18 +- .../Source/AnimGraphStateMachine.cpp | 14 +- .../EMotionFX/Source/AnimGraphStateMachine.h | 2 +- .../Source/AnimGraphStateTransition.cpp | 4 +- .../EMotionFX/Source/AnimGraphSyncTrack.cpp | 32 +- .../Code/EMotionFX/Source/AttachmentNode.cpp | 6 +- .../Code/EMotionFX/Source/AttachmentNode.h | 8 +- .../Code/EMotionFX/Source/AttachmentSkin.cpp | 14 +- .../Code/EMotionFX/Source/AttachmentSkin.h | 12 +- .../Code/EMotionFX/Source/BlendTree.cpp | 4 +- .../Source/BlendTreeAccumTransformNode.cpp | 2 +- .../Source/BlendTreeAccumTransformNode.h | 2 +- .../Source/BlendTreeBlend2AdditiveNode.cpp | 2 +- .../Source/BlendTreeBlend2LegacyNode.cpp | 4 +- .../EMotionFX/Source/BlendTreeBlend2Node.cpp | 2 +- .../Source/BlendTreeBlend2NodeBase.cpp | 2 +- .../Source/BlendTreeBlend2NodeBase.h | 2 +- .../EMotionFX/Source/BlendTreeFootIKNode.cpp | 20 +- .../Source/BlendTreeGetTransformNode.cpp | 6 +- .../Source/BlendTreeGetTransformNode.h | 2 +- .../EMotionFX/Source/BlendTreeLookAtNode.cpp | 8 +- .../EMotionFX/Source/BlendTreeLookAtNode.h | 2 +- .../Source/BlendTreeMaskLegacyNode.cpp | 24 +- .../Source/BlendTreeMaskLegacyNode.h | 2 +- .../EMotionFX/Source/BlendTreeMaskNode.cpp | 26 +- .../Code/EMotionFX/Source/BlendTreeMaskNode.h | 6 +- .../Source/BlendTreeMirrorPoseNode.cpp | 6 +- .../Source/BlendTreeMorphTargetNode.cpp | 10 +- .../Source/BlendTreeMorphTargetNode.h | 4 +- .../EMotionFX/Source/BlendTreeRagdollNode.cpp | 4 +- .../BlendTreeRagdollStrengthModifierNode.h | 2 +- .../Source/BlendTreeSetTransformNode.cpp | 6 +- .../Source/BlendTreeSetTransformNode.h | 2 +- .../Source/BlendTreeTransformNode.cpp | 2 +- .../EMotionFX/Source/BlendTreeTransformNode.h | 2 +- .../Source/BlendTreeTwoLinkIKNode.cpp | 38 +- .../EMotionFX/Source/BlendTreeTwoLinkIKNode.h | 12 +- .../Code/EMotionFX/Source/DebugDraw.cpp | 10 +- .../EMotionFX/Source/DualQuatSkinDeformer.cpp | 8 +- .../EMotionFX/Source/DualQuatSkinDeformer.h | 10 +- .../Source/Importer/ChunkProcessors.cpp | 9 +- .../EMotionFX/Source/Importer/Importer.cpp | 49 +-- .../Code/EMotionFX/Source/KeyFrameFinder.h | 4 +- .../Code/EMotionFX/Source/KeyFrameFinder.inl | 14 +- .../EMotionFX/Source/KeyTrackLinearDynamic.h | 28 +- .../Source/KeyTrackLinearDynamic.inl | 97 ++--- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 370 +++++------------- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h | 46 +-- .../Code/EMotionFX/Source/MeshDeformer.h | 2 +- .../EMotionFX/Source/MeshDeformerStack.cpp | 118 ++---- .../Code/EMotionFX/Source/MeshDeformerStack.h | 10 +- .../EMotionFX/Source/MorphMeshDeformer.cpp | 40 +- .../Code/EMotionFX/Source/MorphMeshDeformer.h | 8 +- .../Code/EMotionFX/Source/MorphSetup.cpp | 105 ++--- .../Code/EMotionFX/Source/MorphSetup.h | 10 +- .../Code/EMotionFX/Source/MorphTarget.cpp | 2 +- .../Code/EMotionFX/Source/MorphTarget.h | 4 +- .../EMotionFX/Source/MorphTargetStandard.cpp | 79 ++-- .../EMotionFX/Source/MorphTargetStandard.h | 16 +- .../Code/EMotionFX/Source/Motion.cpp | 2 +- .../Source/MotionData/MotionData.cpp | 26 +- .../EMotionFX/Source/MotionData/MotionData.h | 16 +- .../MotionData/NonUniformMotionData.cpp | 24 +- .../Source/MotionData/NonUniformMotionData.h | 2 +- .../Source/MotionData/UniformMotionData.cpp | 26 +- .../Source/MotionData/UniformMotionData.h | 2 +- .../Code/EMotionFX/Source/MotionInstance.cpp | 10 +- .../Code/EMotionFX/Source/MotionInstance.h | 6 +- .../EMotionFX/Source/MotionInstancePool.cpp | 33 +- .../EMotionFX/Source/MotionInstancePool.h | 12 +- .../EMotionFX/Source/MotionLayerSystem.cpp | 77 ++-- .../Code/EMotionFX/Source/MotionLayerSystem.h | 14 +- .../Code/EMotionFX/Source/MotionManager.cpp | 314 ++++----------- .../Code/EMotionFX/Source/MotionManager.h | 26 +- .../Code/EMotionFX/Source/MotionQueue.cpp | 6 +- .../Code/EMotionFX/Source/MotionQueue.h | 4 +- .../Code/EMotionFX/Source/MotionSet.cpp | 66 +--- .../Code/EMotionFX/Source/MotionSet.h | 8 +- .../Code/EMotionFX/Source/MotionSystem.cpp | 77 +--- .../Code/EMotionFX/Source/MotionSystem.h | 2 +- .../EMotionFX/Source/MultiThreadScheduler.cpp | 64 ++- .../EMotionFX/Source/MultiThreadScheduler.h | 10 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp | 14 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.h | 12 +- .../Code/EMotionFX/Source/NodeGroup.cpp | 2 +- .../Code/EMotionFX/Source/NodeGroup.h | 2 +- .../Code/EMotionFX/Source/NodeMap.cpp | 4 +- .../EMotionFX/Code/EMotionFX/Source/NodeMap.h | 8 +- .../Code/EMotionFX/Source/PhysicsSetup.cpp | 6 +- Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp | 2 +- .../Code/EMotionFX/Source/PoseDataRagdoll.cpp | 2 +- .../Code/EMotionFX/Source/RagdollInstance.cpp | 22 +- .../Code/EMotionFX/Source/RagdollInstance.h | 8 +- .../Code/EMotionFX/Source/Recorder.cpp | 245 +++++------- .../Code/EMotionFX/Source/Recorder.h | 63 ++- .../Source/RepositioningLayerPass.cpp | 6 +- .../EMotionFX/Source/RepositioningLayerPass.h | 4 +- .../EMotionFX/Source/SimulatedObjectSetup.cpp | 60 +-- .../EMotionFX/Source/SimulatedObjectSetup.h | 22 +- .../Source/SingleThreadScheduler.cpp | 19 +- .../EMotionFX/Source/SingleThreadScheduler.h | 6 +- .../SkinningInfoVertexAttributeLayer.cpp | 10 +- .../Source/SkinningInfoVertexAttributeLayer.h | 2 +- .../EMotionFX/Source/SoftSkinDeformer.cpp | 10 +- .../Code/EMotionFX/Source/SoftSkinDeformer.h | 20 +- .../EMotionFX/Source/StandardMaterial.cpp | 30 +- .../Code/EMotionFX/Source/StandardMaterial.h | 10 +- .../Code/EMotionFX/Source/TransformData.cpp | 14 +- .../Code/EMotionFX/Source/TransformData.h | 14 +- .../EMStudioSDK/Source/PluginManager.cpp | 117 ++---- .../EMStudioSDK/Source/PluginManager.h | 14 +- .../Source/TimeView/TimeTrack.cpp | 44 +-- .../Source/TimeView/TimeTrack.h | 10 +- .../Integration/AnimGraphComponentBus.h | 44 +-- .../Code/MCore/Source/MultiThreadManager.h | 16 + .../Code/MCore/Source/StringIdPool.cpp | 4 +- .../Integration/Components/ActorComponent.cpp | 14 +- .../Components/AnimGraphComponent.cpp | 122 +++--- .../Components/AnimGraphComponent.h | 32 +- .../Integration/System/SystemComponent.cpp | 8 +- .../Code/Tests/AnimGraphComponentBusTests.cpp | 82 ++-- .../Code/Tests/AnimGraphEventTests.cpp | 4 +- .../Tests/AnimGraphNodeEventFilterTests.cpp | 2 +- .../Tests/AnimGraphNodeProcessingTests.cpp | 2 +- .../Tests/AnimGraphParameterActionTests.cpp | 13 +- ...nimGraphParameterConditionCommandTests.cpp | 2 +- .../Code/Tests/AnimGraphRefCountTests.cpp | 4 +- .../Code/Tests/AnimGraphSyncTrackTests.cpp | 8 +- .../Code/Tests/AnimGraphTagConditionTests.cpp | 5 +- .../Tests/AnimGraphVector2ConditionTests.cpp | 13 +- .../Code/Tests/BlendTreeFootIKNodeTests.cpp | 18 +- .../Code/Tests/BlendTreeMaskNodeTests.cpp | 10 +- .../Code/Tests/BlendTreeRagdollNodeTests.cpp | 2 +- .../CanAddSimpleMotionComponent.cpp | 2 +- .../Tests/Integration/PoseComparisonTests.cpp | 18 +- .../Code/Tests/KeyTrackLinearTests.cpp | 16 +- Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h | 2 +- .../Code/Tests/Mocks/AnimGraphInstance.h | 28 +- .../Code/Tests/Mocks/AnimGraphNode.h | 4 +- Gems/EMotionFX/Code/Tests/Mocks/Node.h | 44 +-- .../Code/Tests/Mocks/SimulatedJoint.h | 4 +- .../Code/Tests/Mocks/SimulatedObject.h | 12 +- Gems/EMotionFX/Code/Tests/Mocks/Skeleton.h | 4 +- .../Code/Tests/MorphTargetRuntimeTests.cpp | 2 +- .../Code/Tests/MotionEventTrackTests.cpp | 2 +- .../Code/Tests/NonUniformMotionDataTests.cpp | 22 +- Gems/EMotionFX/Code/Tests/PoseTests.cpp | 102 ++--- .../Code/Tests/Prefabs/LeftArmSkeleton.h | 2 +- .../Code/Tests/QuaternionParameterTests.cpp | 4 +- .../Tests/SimulatedObjectCommandTests.cpp | 20 +- .../Tests/SimulatedObjectSerializeTests.cpp | 2 +- .../EMotionFX/Code/Tests/SkeletalLODTests.cpp | 14 +- .../Code/Tests/UniformMotionDataTests.cpp | 22 +- .../Code/Tests/Vector3ParameterTests.cpp | 6 +- 211 files changed, 2440 insertions(+), 3244 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp index 52a4ec6a0b..85d9c699e1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp @@ -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(); } @@ -100,7 +100,7 @@ namespace CommandSystem } else { - EMotionFX::Node* node = skeleton->FindNodeByName(retargetRootNodeName.c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(retargetRootNodeName); actor->SetRetargetRootNode(node); } } @@ -120,8 +120,8 @@ namespace CommandSystem { // Store old attachment nodes for undo. mOldAttachmentNodes = ""; - 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 = skeleton->GetNode(i); if (!node) @@ -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; @@ -199,8 +199,8 @@ namespace CommandSystem { // Store old nodes for undo. mOldExcludedFromBoundsNodes = ""; - 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 = skeleton->GetNode(i); if (!node) @@ -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; @@ -294,19 +294,18 @@ 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()); @@ -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,12 +475,12 @@ 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) + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Mesh* mesh = actor->GetMesh(lod, i); if (mesh && mesh->GetIsCollisionMesh()) @@ -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); @@ -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); @@ -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); @@ -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) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h index eec9f7a5c5..94c6e0ff42 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h @@ -19,9 +19,9 @@ namespace CommandSystem { // Adjust the given actor. MCORE_DEFINECOMMAND_START(CommandAdjustActor, "Adjust actor", true) - uint32 mOldMotionExtractionNodeIndex; - uint32 mOldRetargetRootNodeIndex; - uint32 mOldTrajectoryNodeIndex; + size_t mOldMotionExtractionNodeIndex; + size_t mOldRetargetRootNodeIndex; + size_t mOldTrajectoryNodeIndex; AZStd::string mOldAttachmentNodes; AZStd::string mOldExcludedFromBoundsNodes; AZStd::string mOldName; @@ -71,6 +71,6 @@ public: // 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..60f03f170e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp @@ -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) { @@ -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..69509822fe 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h @@ -31,7 +31,7 @@ public: AZ::Vector3 mOldPosition; AZ::Quaternion mOldRotation; AZ::Vector3 mOldScale; - uint32 mOldLODLevel; + size_t mOldLODLevel; bool mOldIsVisible; bool mOldDoRender; bool mOldWorkspaceDirtyFlag; @@ -44,7 +44,7 @@ public: AZ::Vector3 mOldPosition; AZ::Quaternion mOldRotation; AZ::Vector3 mOldScale; - uint32 mOldLODLevel; + size_t mOldLODLevel; bool mOldIsVisible; bool mOldDoRender; bool mOldWorkspaceDirtyFlag; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp index fdc4e4d0e5..1458107bcf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp @@ -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 && @@ -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()) @@ -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()) { @@ -521,8 +515,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); @@ -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); @@ -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/AnimGraphConnectionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp index 25e3924e0d..7707d8fa8b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp @@ -124,10 +124,10 @@ namespace CommandSystem // in case the source port got specified by name, overwrite the source port number if (!mSourcePortName.empty()) { - mSourcePort = sourceNode->FindOutputPortIndex(mSourcePortName.c_str()); + mSourcePort = sourceNode->FindOutputPortIndex(mSourcePortName); // 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() && mSourcePort == InvalidIndex) { m_connectionId.SetInvalid(); return true; @@ -157,13 +157,13 @@ namespace CommandSystem } // verify port ranges - if (mSourcePort >= static_cast(sourceNode->GetOutputPorts().size()) || mSourcePort < 0) + if (mSourcePort >= 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 (mTargetPort >= 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; @@ -345,7 +345,7 @@ 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, @@ -356,7 +356,7 @@ namespace CommandSystem // 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()); } @@ -414,8 +414,8 @@ namespace CommandSystem CommandAnimGraphRemoveConnection::CommandAnimGraphRemoveConnection(MCore::Command* orgCommand) : MCore::Command("AnimGraphRemoveConnection", orgCommand) { - mSourcePort = MCORE_INVALIDINDEX32; - mTargetPort = MCORE_INVALIDINDEX32; + mSourcePort = InvalidIndex; + mTargetPort = InvalidIndex; mTransitionType = AZ::TypeId::CreateNull(); mStartOffsetX = 0; mStartOffsetY = 0; @@ -603,7 +603,7 @@ namespace CommandSystem 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(), @@ -623,7 +623,7 @@ namespace CommandSystem if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult)) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -634,8 +634,8 @@ namespace CommandSystem mTargetNodeId.SetInvalid(); mSourceNodeId.SetInvalid(); m_connectionId.SetInvalid(); - mSourcePort = MCORE_INVALIDINDEX32; - mTargetPort = MCORE_INVALIDINDEX32; + mSourcePort = InvalidIndex; + mTargetPort = InvalidIndex; mStartOffsetX = 0; mStartOffsetY = 0; mEndOffsetX = 0; @@ -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..d0ef5549e0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h @@ -35,8 +35,8 @@ namespace CommandSystem int32 mStartOffsetY; int32 mEndOffsetX; int32 mEndOffsetY; - int32 mSourcePort; - int32 mTargetPort; + size_t mSourcePort; + size_t mTargetPort; AZStd::string mSourcePortName; AZStd::string mTargetPortName; bool mOldDirtyFlag; @@ -47,8 +47,8 @@ namespace CommandSystem 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; } + size_t GetSourcePort() const { return mSourcePort; } + size_t GetTargetPort() const { return mTargetPort; } int32 GetStartOffsetX() const { return mStartOffsetX; } int32 GetStartOffsetY() const { return mStartOffsetY; } int32 GetEndOffsetX() const { return mEndOffsetX; } @@ -69,8 +69,8 @@ namespace CommandSystem int32 mStartOffsetY; int32 mEndOffsetX; int32 mEndOffsetY; - int32 mSourcePort; - int32 mTargetPort; + size_t mSourcePort; + size_t mTargetPort; bool mOldDirtyFlag; AZStd::string mOldContents; @@ -78,8 +78,8 @@ namespace CommandSystem 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; } + size_t GetSourcePort() const { return mSourcePort; } + size_t GetTargetPort() const { return mTargetPort; } int32 GetStartOffsetX() const { return mStartOffsetX; } int32 GetStartOffsetY() const { return mStartOffsetY; } int32 GetEndOffsetX() const { return mEndOffsetX; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp index ed871fc03f..6142fe151e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp @@ -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) @@ -416,7 +416,7 @@ namespace CommandSystem 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()); } @@ -743,8 +743,8 @@ namespace CommandSystem //-------------------------- // 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) @@ -848,7 +848,7 @@ namespace CommandSystem if (!GetCommandManager()->ExecuteCommandGroupInsideCommand(group, outResult)) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -870,7 +870,7 @@ namespace CommandSystem ); if (GetCommandManager()->ExecuteCommandInsideCommand(command, outResult) == false) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -1207,16 +1207,15 @@ namespace CommandSystem AZStd::vector outNodes; const AZ::TypeId nodeType = azrtti_typeid(node); parentNode->CollectChildNodesOfType(nodeType, &outNodes); - const uint32 numTypeNodes = outNodes.size(); + 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/AnimGraphNodeGroupCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp index f5f913f0ca..a11af1399d 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()); } @@ -404,10 +404,10 @@ 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; } @@ -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/AnimGraphParameterCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp index 38a545465b..b0c03e4df2 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; @@ -316,7 +316,7 @@ 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. @@ -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()) { - animGraphInstance->ReInitParameterValue(static_cast(valueParameterIndex.GetValue())); + animGraphInstance->ReInitParameterValue(valueParameterIndex.GetValue()); } else { @@ -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(); @@ -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 != 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 8b55130677..f93a93d0f9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h @@ -59,8 +59,6 @@ namespace CommandSystem struct COMMANDSYSTEM_API ParameterConnectionItem { - uint32 mTargetNodePort; - 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); } @@ -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 = 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/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/MetaData.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp index 506f47fcac..aade6e8358 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) @@ -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/MotionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.cpp index 5655f2f293..677b4ec5ff 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.cpp @@ -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); @@ -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); @@ -618,7 +618,7 @@ namespace CommandSystem //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 +645,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 +665,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); @@ -720,8 +720,8 @@ namespace CommandSystem //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 +741,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); @@ -974,8 +974,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); @@ -1185,13 +1185,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 +1233,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 +1282,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 +1291,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..2e68d7b2cc 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. @@ -83,7 +83,7 @@ namespace CommandSystem public: uint32 mOldMotionID; AZStd::string mOldFileName; - uint32 mOldIndex; + size_t mOldIndex; bool mOldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp index e4b8d38147..b1d896ccd4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp @@ -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 AZStd::vector& 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.size(); - 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 AZStd::vector& 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 269a0322c0..629e1e72c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h @@ -55,7 +55,7 @@ namespace CommandSystem private: AZStd::string m_eventTrackName; - AZStd::optional m_eventTrackIndex; + AZStd::optional m_eventTrackIndex; AZStd::optional m_isEnabled; }; @@ -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 AZStd::vector& 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..051a0e0797 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp @@ -159,8 +159,8 @@ namespace CommandSystem 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); @@ -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); @@ -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); @@ -790,8 +787,8 @@ namespace CommandSystem } // 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); @@ -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/SelectionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp index f6d03d2983..72c7338512 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp @@ -36,11 +36,11 @@ namespace CommandSystem void SelectActorInstancesUsingCommands(const AZStd::vector& selectedActorInstances) { SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedActorInstances = selectedActorInstances.size(); + 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,7 +49,7 @@ 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 (AZStd::find(begin(selectedActorInstances), end(selectedActorInstances), actorInstance) == end(selectedActorInstances)) @@ -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); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp index a6ff4de440..5910ae84f7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp @@ -25,14 +25,14 @@ namespace CommandSystem EMotionFX::ActorNotificationBus::Handler::BusDisconnect(); } - uint32 SelectionList::GetNumTotalItems() const + size_t SelectionList::GetNumTotalItems() const { - return static_cast(mSelectedNodes.size() + + return mSelectedNodes.size() + mSelectedActors.size() + mSelectedActorInstances.size() + mSelectedMotions.size() + mSelectedMotionInstances.size() + - mSelectedAnimGraphs.size()); + mSelectedAnimGraphs.size(); } bool SelectionList::GetIsEmpty() const @@ -113,48 +113,46 @@ namespace CommandSystem // 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()); } @@ -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..6dd1d2d4e2 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 mSelectedNodes.size(); } /** * Get the number of selected actors */ - MCORE_INLINE uint32 GetNumSelectedActors() const { return static_cast(mSelectedActors.size()); } + MCORE_INLINE size_t GetNumSelectedActors() const { return mSelectedActors.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 mSelectedActorInstances.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 mSelectedMotionInstances.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 mSelectedMotions.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 mSelectedAnimGraphs.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 mSelectedNodes[index]; } /** * Get the first node from the selection list. @@ -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 mSelectedActors[index]; } /** * Get the first actor from the selection list. @@ -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 mSelectedActorInstances[index]; } /** * Get the first actor instance from the selection list. @@ -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 mSelectedAnimGraphs[index]; } /** * Get the first anim graph from the selection list. @@ -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 mSelectedMotions[index]; } /** * Get the first motion from the selection list. @@ -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 mSelectedMotionInstances[index]; } /** * Get the first motion instance from the selection list. @@ -276,37 +276,37 @@ namespace CommandSystem * 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) { mSelectedNodes.erase(mSelectedNodes.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) { mSelectedActors.erase(mSelectedActors.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) { mSelectedActorInstances.erase(mSelectedActorInstances.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) { mSelectedMotions.erase(mSelectedMotions.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) { mSelectedMotionInstances.erase(mSelectedMotionInstances.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) { mSelectedAnimGraphs.erase(mSelectedAnimGraphs.begin() + index); } /** * Remove the given node from the selection list. 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/Exporter.h b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h index 290f9d4470..9cd3efc6ba 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h @@ -107,8 +107,8 @@ namespace ExporterLib 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 diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp index eefa92f21d..723669d3f1 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,12 +28,12 @@ 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.mLOD = aznumeric_caster(lodLevel); + morphTargetChunk.mNumTransformations = aznumeric_caster(numTransformations); morphTargetChunk.mRangeMin = morphTarget->GetRangeMin(); morphTargetChunk.mRangeMax = morphTarget->GetRangeMax(); morphTargetChunk.mPhonemeSets = morphTarget->GetPhonemeSets(); @@ -60,7 +60,7 @@ 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); @@ -73,7 +73,7 @@ namespace ExporterLib // create and fill the transformation EMotionFX::FileFormat::Actor_MorphTargetTransform transformChunk; - transformChunk.mNodeIndex = transform.mNodeIndex; + transformChunk.mNodeIndex = aznumeric_caster(transform.mNodeIndex); CopyVector(transformChunk.mPosition, AZ::PackedVector3f(transform.mPosition)); CopyVector(transformChunk.mScale, AZ::PackedVector3f(transform.mScale)); CopyQuaternion(transformChunk.mRotation, transform.mRotation); @@ -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); @@ -177,7 +176,7 @@ namespace ExporterLib // fill in the chunk header EMotionFX::FileFormat::FileChunk chunkHeader; chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS; - chunkHeader.mSizeInBytes = GetMorphSetupChunkSize(morphSetup); + chunkHeader.mSizeInBytes = aznumeric_caster(GetMorphSetupChunkSize(morphSetup)); chunkHeader.mVersion = 2; // endian convert the chunk and write it to the file @@ -186,8 +185,8 @@ namespace ExporterLib // fill in the chunk header EMotionFX::FileFormat::Actor_MorphTargets morphTargetsChunk; - morphTargetsChunk.mNumMorphTargets = numSavedMorphTargets; - morphTargetsChunk.mLOD = lodLevel; + morphTargetsChunk.mNumMorphTargets = aznumeric_caster(numSavedMorphTargets); + morphTargetsChunk.mLOD = aznumeric_caster(lodLevel); MCore::LogDetailedInfo("============================================================"); MCore::LogInfo("Morph Targets (%i, LOD=%d)", morphTargetsChunk.mNumMorphTargets, morphTargetsChunk.mLOD); @@ -199,7 +198,7 @@ namespace ExporterLib 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/NodeExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp index 4f6e5a5c52..e7f0fa011e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp @@ -24,12 +24,10 @@ namespace ExporterLib 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(); @@ -48,12 +46,12 @@ namespace ExporterLib CopyQuaternion(nodeChunk.mLocalQuat, rotation); CopyVector(nodeChunk.mLocalScale, scale); - nodeChunk.mNumChilds = numChilds; - nodeChunk.mParentIndex = parentIndex; + nodeChunk.mNumChilds = aznumeric_caster(numChilds); + nodeChunk.mParentIndex = 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)) { @@ -84,7 +82,7 @@ namespace ExporterLib // 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)."); } @@ -105,7 +103,7 @@ namespace ExporterLib // 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); @@ -129,10 +127,8 @@ namespace ExporterLib 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()); @@ -144,8 +140,8 @@ namespace ExporterLib chunkHeader.mVersion = 2; // get the nodes chunk size - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Nodes2) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node2); - for (i = 0; i < numNodes; i++) + chunkHeader.mSizeInBytes = 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()); } @@ -156,8 +152,8 @@ namespace ExporterLib // nodes chunk EMotionFX::FileFormat::Actor_Nodes2 nodesChunk; - nodesChunk.mNumNodes = numNodes; - nodesChunk.mNumRootNodes = actor->GetSkeleton()->GetNumRootNodes(); + nodesChunk.mNumNodes = aznumeric_caster(numNodes); + nodesChunk.mNumRootNodes = aznumeric_caster(actor->GetSkeleton()->GetNumRootNodes()); // endian conversion and write it ConvertUnsignedInt(&nodesChunk.mNumNodes, targetEndianType); @@ -166,21 +162,20 @@ namespace ExporterLib 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; @@ -194,7 +189,7 @@ namespace ExporterLib MCore::LogDetailedInfo("- Group: name='%s'", nodeGroup->GetName()); MCore::LogDetailedInfo(" + DisabledOnDefault: %i", groupChunk.mDisabledOnDefault); 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) @@ -214,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) @@ -229,11 +224,10 @@ namespace ExporterLib 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.size(); + const size_t numGroups = nodeGroups.size(); if (numGroups == 0) { @@ -251,11 +245,11 @@ namespace ExporterLib // calculate the chunk size chunkHeader.mSizeInBytes = sizeof(uint16); - for (i = 0; i < numGroups; ++i) + 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.mSizeInBytes += GetStringChunkSize(nodeGroup->GetNameString()); + chunkHeader.mSizeInBytes += sizeof(uint16) * nodeGroup->GetNumNodes(); } // endian conversion @@ -270,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); } } @@ -311,12 +305,12 @@ namespace ExporterLib MCORE_ASSERT(nodeMirrorInfos); - const uint32 numNodes = nodeMirrorInfos->size(); + 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.mSizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_NodeMotionSources2) + (numNodes * sizeof(uint16)) + (numNodes * sizeof(uint8) * 2)); chunkHeader.mVersion = 1; // endian conversion and write it @@ -326,7 +320,7 @@ namespace ExporterLib // the node motion sources chunk data EMotionFX::FileFormat::Actor_NodeMotionSources2 nodeMotionSourcesChunk; - nodeMotionSourcesChunk.mNumNodes = numNodes; + nodeMotionSourcesChunk.mNumNodes = aznumeric_caster(numNodes); // convert endian and save to the file ConvertUnsignedInt(&nodeMotionSourcesChunk.mNumNodes, targetEndianType); @@ -339,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->at(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.mSourceNode; // convert endian and save to the file ConvertUnsignedShort(&nodeMotionSource, targetEndianType); @@ -353,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->at(i).mAxis); + uint8 axis = static_cast(nodeMirrorInfo.mAxis); 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->at(i).mFlags); + uint8 flags = static_cast(nodeMirrorInfo.mFlags); file->Write(&flags, sizeof(uint8)); } } @@ -371,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); @@ -403,12 +394,12 @@ 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.mSizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_AttachmentNodes) + numAttachmentNodes * sizeof(uint16)); chunkHeader.mVersion = 1; // endian conversion and write it @@ -418,7 +409,7 @@ namespace ExporterLib // the attachment nodes chunk data EMotionFX::FileFormat::Actor_AttachmentNodes attachmentNodesChunk; - attachmentNodesChunk.mNumNodes = numAttachmentNodes; + attachmentNodesChunk.mNumNodes = aznumeric_caster(numAttachmentNodes); // convert endian and save to the file ConvertUnsignedInt(&attachmentNodesChunk.mNumNodes, targetEndianType); @@ -437,11 +428,9 @@ namespace ExporterLib } // 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index 77ce4435bc..5d3f5e6ec8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -1446,8 +1446,8 @@ 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) + mMorphSetups.resize(numLODLevels); + for (size_t i = 0; i < numLODLevels; ++i) { mMorphSetups[i] = nullptr; } @@ -2657,8 +2657,7 @@ namespace EMotionFX EMotionFX::SkinningInfoVertexAttributeLayer* skinLayer = static_cast(vertexAttributeLayer); const AZ::u32 numOrgVerts = skinLayer->GetNumAttributes(); - AZStd::set localJointIndices = skinLayer->CalcLocalJointIndices(numOrgVerts); - const size_t numLocalJoints = 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. @@ -2721,7 +2720,7 @@ namespace EMotionFX 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index 65eb038dbf..126d376ae4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -57,7 +57,7 @@ namespace EMotionFX mAttachedTo = nullptr; mSelfAttachment = nullptr; mCustomData = nullptr; - mID = MCore::GetIDGenerator().GenerateID(); + mID = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); mVisualizeScale = 1.0f; mMotionSamplingRate = 0.0f; mMotionSamplingTimer = 0.0f; @@ -465,7 +465,7 @@ namespace EMotionFX return attachment->GetAttachmentActorInstance() == actorInstance; }); - return foundAttachment == mAttachments.end() ? AZStd::distance(mAttachments.begin(), foundAttachment) : InvalidIndex; + return foundAttachment != mAttachments.end() ? AZStd::distance(mAttachments.begin(), foundAttachment) : InvalidIndex; } // remove an attachment by actor instance pointer @@ -1433,7 +1433,7 @@ namespace EMotionFX return mActor; } - void ActorInstance::SetID(size_t id) + void ActorInstance::SetID(uint32 id) { mID = id; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h index 620ecc29c5..05a8136326 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h @@ -75,13 +75,13 @@ namespace EMotionFX * Get the unique identification number for the actor instance. * @return The unique identification number. */ - MCORE_INLINE size_t GetID() const { return mID; } + MCORE_INLINE uint32 GetID() const { return mID; } /** * Set the unique identification number for the actor instance. * @param[in] id The unique identification number. */ - void SetID(size_t id); + void SetID(uint32 id); /** * Get the motion system of this actor instance. @@ -895,7 +895,7 @@ namespace EMotionFX size_t mLODLevel; /**< 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 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. */ - size_t mID; /**< The unique identification number for the actor instance. */ + 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 collision mesh based). */ float m_boundsExpandBy = 0.25f; /**< Expand bounding box by normalized percentage. (Default: 25% greater than the calculated bounding box) */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp index a8584163ed..b96a4b4962 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp @@ -100,8 +100,8 @@ namespace EMotionFX mScheduler = scheduler; // adjust all visibility flags to false for all actor instances - const uint32 numActorInstances = mActorInstances.size(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = mActorInstances.size(); + for (size_t i = 0; i < numActorInstances; ++i) { mActorInstances[i]->SetIsVisible(false); } @@ -116,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(); @@ -168,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; } @@ -209,55 +209,28 @@ namespace EMotionFX LockActorInstances(); // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.size(); - 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(mActorInstances), end(mActorInstances), actorInstance) != end(mActorInstances); 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.size(); - 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(mActorInstances), end(mActorInstances), actorInstance); + return foundActorInstance != end(mActorInstances) ? AZStd::distance(begin(mActorInstances), 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.size(); - for (uint32 i = 0; i < numActorInstances; ++i) + const auto foundActorInstance = AZStd::find_if(begin(mActorInstances), end(mActorInstances), [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(mActorInstances) ? *foundActorInstance : nullptr; } @@ -284,7 +257,7 @@ namespace EMotionFX // unregister a given actor instance - void ActorManager::UnregisterActorInstance(uint32 nr) + void ActorManager::UnregisterActorInstance(size_t nr) { UnregisterActorInstance(mActorInstances[nr]); } @@ -415,7 +388,7 @@ namespace EMotionFX } - Actor* ActorManager::GetActor(uint32 nr) const + Actor* ActorManager::GetActor(size_t nr) const { return m_actors[nr].get(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h index 34b290cfff..a7f12111ce 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h @@ -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); @@ -131,7 +131,7 @@ namespace EMotionFX * @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 mActorInstances[nr]; } /** * Get the array of actor instances. @@ -144,7 +144,7 @@ namespace EMotionFX * @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. @@ -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 mRootActorInstances[nr]; } /** * Get the currently used actor update scheduler. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h index 2ad6beeacf..18fd7ff233 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 mNumUpdated.GetValue(); } + size_t GetNumVisibleActorInstances() const { return mNumVisible.GetValue(); } + size_t GetNumSampledActorInstances() const { return mNumSampled.GetValue(); } protected: - MCore::AtomicUInt32 mNumUpdated; - MCore::AtomicUInt32 mNumVisible; - MCore::AtomicUInt32 mNumSampled; + MCore::AtomicSizeT mNumUpdated; + MCore::AtomicSizeT mNumVisible; + MCore::AtomicSizeT mNumSampled; /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp index f049c498f6..38fb6380e9 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 @@ -36,7 +37,7 @@ namespace EMotionFX AnimGraph::AnimGraph() : mGameControllerSettings(aznew AnimGraphGameControllerSettings()) { - mID = MCore::GetIDGenerator().GenerateID(); + mID = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); mDirtyFlag = false; mAutoUnregister = true; mRetarget = false; @@ -344,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()) @@ -362,7 +363,7 @@ namespace EMotionFX } - uint32 AnimGraph::RecursiveCalcNumNodes() const + size_t AnimGraph::RecursiveCalcNumNodes() const { return mRootStateMachine->RecursiveCalcNumNodes(); } @@ -385,9 +386,9 @@ namespace EMotionFX } - 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()) @@ -395,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); @@ -409,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); } @@ -422,7 +423,7 @@ namespace EMotionFX // recursively calculate the number of node connections - uint32 AnimGraph::RecursiveCalcNumNodeConnections() const + size_t AnimGraph::RecursiveCalcNumNodeConnections() const { return mRootStateMachine->RecursiveCalcNumNodeConnections(); } @@ -491,7 +492,7 @@ 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]; } @@ -514,19 +515,13 @@ 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(mNodeGroups), end(mNodeGroups), [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(mNodeGroups) ? AZStd::distance(begin(mNodeGroups), foundNodeGroup) : InvalidIndex; } @@ -538,7 +533,7 @@ namespace EMotionFX // 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) @@ -569,9 +564,9 @@ namespace EMotionFX // get the number of node groups - uint32 AnimGraph::GetNumNodeGroups() const + size_t AnimGraph::GetNumNodeGroups() const { - return static_cast(mNodeGroups.size()); + return mNodeGroups.size(); } @@ -716,7 +711,7 @@ namespace EMotionFX MCore::LockGuard lock(mLock); // assign the index and add it to the objects array - object->SetObjectIndex(static_cast(mObjects.size())); + object->SetObjectIndex(mObjects.size()); mObjects.push_back(object); // if it's a node, add it to the nodes array as well @@ -761,10 +756,10 @@ namespace EMotionFX if (azrtti_istypeof(object)) { AnimGraphNode* node = static_cast(object); - const uint32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); - const uint32 numNodes = mNodes.size(); - for (uint32 i = nodeIndex + 1; i < numNodes; ++i) + const size_t numNodes = mNodes.size(); + for (size_t i = nodeIndex + 1; i < numNodes; ++i) { AnimGraphNode* curNode = mNodes[i]; MCORE_ASSERT(i == curNode->GetNodeIndex()); @@ -778,32 +773,26 @@ namespace EMotionFX // reserve space for a given amount of objects - void AnimGraph::ReserveNumObjects(uint32 numObjects) + void AnimGraph::ReserveNumObjects(size_t numObjects) { mObjects.reserve(numObjects); } // reserve space for a given amount of nodes - void AnimGraph::ReserveNumNodes(uint32 numNodes) + void AnimGraph::ReserveNumNodes(size_t numNodes) { mNodes.reserve(numNodes); } // Calculate number of motion nodes in the graph - uint32 AnimGraph::CalcNumMotionNodes() const + size_t AnimGraph::CalcNumMotionNodes() const { - const uint32 numNodes = mNodes.size(); - uint32 numMotionNodes = 0; - for (uint32 i = 0; i < numNodes; ++i) + return AZStd::accumulate(begin(mNodes), end(mNodes), size_t{0}, [](size_t total, const AnimGraphNode* node) { - if (azrtti_istypeof(mNodes[i])) - { - numMotionNodes++; - } - } - return numMotionNodes; + return total + azrtti_istypeof(node); + }); } @@ -831,7 +820,7 @@ namespace EMotionFX // 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) { @@ -1027,11 +1016,9 @@ namespace EMotionFX void AnimGraph::RemoveInvalidConnections(bool logWarnings) { // Iterate over all nodes - const AZ::u32 numNodes = mNodes.size(); - for (AZ::u32 i = 0; i < numNodes; ++i) + for (AnimGraphNode* node : mNodes) { - 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 ab1cfd926f..a356b031aa 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h @@ -72,24 +72,24 @@ namespace EMotionFX 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 mObjects.size(); } + AnimGraphObject* GetObject(size_t index) const { return mObjects[index]; } + void ReserveNumObjects(size_t numObjects); size_t GetNumNodes() const { return mNodes.size(); } - AnimGraphNode* GetNode(uint32 index) const { return mNodes[index]; } - void ReserveNumNodes(uint32 numNodes); - uint32 CalcNumMotionNodes() const; + AnimGraphNode* GetNode(size_t index) const { return mNodes[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(); 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 d63d67be43..e0f6712145 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h @@ -132,7 +132,7 @@ namespace EMotionFX 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/AnimGraphEventBuffer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.cpp index 7a241ec18e..0403e277b6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.cpp @@ -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/AnimGraphInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp index 1082bc112b..c31f584498 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp @@ -143,12 +143,11 @@ namespace EMotionFX { if (delFromMem) { - const uint32 numParams = mParamValues.size(); - for (uint32 i = 0; i < numParams; ++i) + for (MCore::Attribute* mParamValue : mParamValues) { - if (mParamValues[i]) + if (mParamValue) { - delete mParamValues[i]; + delete mParamValue; } } } @@ -172,12 +171,12 @@ namespace EMotionFX } - uint32 AnimGraphInstance::AddInternalAttribute(MCore::Attribute* attribute) + size_t AnimGraphInstance::AddInternalAttribute(MCore::Attribute* attribute) { MCore::LockGuard lock(mMutex); m_internalAttributes.emplace_back(attribute); - return static_cast(m_internalAttributes.size() - 1); + return m_internalAttributes.size() - 1; } @@ -266,11 +265,11 @@ namespace EMotionFX RemoveAllParameters(true); const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - mParamValues.resize(static_cast(valueParameters.size())); + mParamValues.resize(valueParameters.size()); // init the values - const uint32 numParams = mParamValues.size(); - for (uint32 i = 0; i < numParams; ++i) + const size_t numParams = mParamValues.size(); + for (size_t i = 0; i < numParams; ++i) { mParamValues[i] = valueParameters[i]->ConstructDefaultValueAsAttribute(); } @@ -282,28 +281,27 @@ namespace EMotionFX { // check how many parameters we need to add const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - const int32 numToAdd = static_cast(valueParameters.size()) - mParamValues.size(); + const ptrdiff_t numToAdd = aznumeric_cast(valueParameters.size()) - mParamValues.size(); if (numToAdd <= 0) { return; } // make sure we have the right space pre-allocated - mParamValues.reserve(static_cast(valueParameters.size())); + mParamValues.reserve(valueParameters.size()); // add the remaining parameters - const uint32 startIndex = mParamValues.size(); - for (int32 i = 0; i < numToAdd; ++i) + const size_t startIndex = mParamValues.size(); + for (ptrdiff_t i = 0; i < numToAdd; ++i) { - const uint32 index = startIndex + i; - mParamValues.emplace_back(); - mParamValues.back() = valueParameters[index]->ConstructDefaultValueAsAttribute(); + const size_t index = startIndex + i; + mParamValues.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) { @@ -318,7 +316,7 @@ namespace EMotionFX // reinitialize the parameter - void AnimGraphInstance::ReInitParameterValue(uint32 index) + void AnimGraphInstance::ReInitParameterValue(size_t index) { if (mParamValues[index]) { @@ -331,8 +329,8 @@ namespace EMotionFX void AnimGraphInstance::ReInitParameterValues() { - const AZ::u32 parameterValueCount = mParamValues.size(); - for (AZ::u32 i = 0; i < parameterValueCount; ++i) + const size_t parameterValueCount = mParamValues.size(); + for (size_t i = 0; i < parameterValueCount; ++i) { ReInitParameterValue(i); } @@ -440,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)); } @@ -470,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)); } @@ -494,7 +492,7 @@ namespace EMotionFX return nullptr; } - return mParamValues[static_cast(paramIndex.GetValue())]; + return mParamValues[paramIndex.GetValue()]; } @@ -507,7 +505,7 @@ namespace EMotionFX // add the parameter of the animgraph, at a given index - void AnimGraphInstance::InsertParameterValue(uint32 index) + void AnimGraphInstance::InsertParameterValue(size_t index) { mParamValues.emplace(AZStd::next(begin(mParamValues), index), nullptr); ReInitParameterValue(index); @@ -515,7 +513,7 @@ namespace EMotionFX // 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]; @@ -523,18 +521,18 @@ namespace EMotionFX // 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; + const size_t prevIndex = paramIndex - 1; mParamValues[paramIndex] = mParamValues[prevIndex]; } mParamValues[newIndex] = oldAttribute; } else { - for (uint32 paramIndex = oldIndex; paramIndex < newIndex; paramIndex++) + for (size_t paramIndex = oldIndex; paramIndex < newIndex; paramIndex++) { - const uint32 nexIndex = paramIndex + 1; + const size_t nexIndex = paramIndex + 1; mParamValues[paramIndex] = mParamValues[nexIndex]; } mParamValues[newIndex] = oldAttribute; @@ -609,7 +607,7 @@ 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; @@ -619,7 +617,7 @@ namespace EMotionFX } // repeat until we are at the root - uint32 depth = 1; + size_t depth = 1; while (curInstance) { // get the attachment object @@ -667,7 +665,7 @@ 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(); @@ -682,7 +680,7 @@ namespace EMotionFX { AnimGraphObjectData* data = m_uniqueDatas[index]; m_uniqueDatas.erase(m_uniqueDatas.begin() + index); - mObjectFlags.erase(AZStd::next(begin(mObjectFlags), static_cast(index))); + mObjectFlags.erase(AZStd::next(begin(mObjectFlags), index)); if (delFromMem && data) { data->Destroy(); @@ -809,10 +807,10 @@ namespace EMotionFX // init the hashmap void AnimGraphInstance::InitUniqueDatas() { - const uint32 numObjects = mAnimGraph->GetNumObjects(); + const size_t numObjects = mAnimGraph->GetNumObjects(); m_uniqueDatas.resize(numObjects); mObjectFlags.resize(numObjects); - for (uint32 i = 0; i < numObjects; ++i) + for (size_t i = 0; i < numObjects; ++i) { m_uniqueDatas[i] = nullptr; mObjectFlags[i] = 0; @@ -932,10 +930,9 @@ namespace EMotionFX // reset all node flags void AnimGraphInstance::ResetFlagsForAllObjects(uint32 flagsToDisable) { - const uint32 numObjects = mObjectFlags.size(); - for (uint32 i = 0; i < numObjects; ++i) + for (uint32& mObjectFlag : mObjectFlags) { - mObjectFlags[i] &= ~flagsToDisable; + mObjectFlag &= ~flagsToDisable; } } @@ -943,8 +940,8 @@ 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 = mAnimGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { mAnimGraph->GetNode(i)->ResetPoseRefCount(this); } @@ -954,8 +951,8 @@ 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 = mAnimGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { mAnimGraph->GetNode(i)->ResetRefDataRefCount(this); } @@ -977,8 +974,8 @@ 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 = mAnimGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { AnimGraphNode* node = mAnimGraph->GetNode(i); mObjectFlags[node->GetObjectIndex()] &= ~flagsToDisable; @@ -986,8 +983,8 @@ namespace EMotionFX 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); } @@ -1024,7 +1021,7 @@ namespace EMotionFX 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) { @@ -1062,8 +1059,8 @@ namespace EMotionFX // init all internal attributes void AnimGraphInstance::InitInternalAttributes() { - const uint32 numNodes = mAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mAnimGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { mAnimGraph->GetNode(i)->InitInternalAttributes(this); } @@ -1258,8 +1255,8 @@ namespace EMotionFX const uint32 threadIndex = mActorInstance->GetThreadIndex(); AnimGraphRefCountedDataPool& refDataPool = GetEMotionFX().GetThreadData(threadIndex)->GetRefCountedDataPool(); - const uint32 numNodes = mAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mAnimGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { const AnimGraphNode* node = mAnimGraph->GetNode(i); AnimGraphNodeData* nodeData = static_cast(m_uniqueDatas[node->GetObjectIndex()]); @@ -1292,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) @@ -1318,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)) @@ -1331,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)) @@ -1344,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) @@ -1357,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) @@ -1370,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) @@ -1383,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) @@ -1428,7 +1425,7 @@ namespace EMotionFX return false; } - return GetParameterValueAsFloat(static_cast(index.GetValue()), outValue); + return GetParameterValueAsFloat(index.GetValue(), outValue); } @@ -1440,7 +1437,7 @@ namespace EMotionFX return false; } - return GetParameterValueAsBool(static_cast(index.GetValue()), outValue); + return GetParameterValueAsBool(index.GetValue(), outValue); } @@ -1452,7 +1449,7 @@ namespace EMotionFX return false; } - return GetParameterValueAsInt(static_cast(index.GetValue()), outValue); + return GetParameterValueAsInt(index.GetValue(), outValue); } @@ -1464,7 +1461,7 @@ namespace EMotionFX return false; } - return GetVector2ParameterValue(static_cast(index.GetValue()), outValue); + return GetVector2ParameterValue(index.GetValue(), outValue); } @@ -1476,7 +1473,7 @@ namespace EMotionFX return false; } - return GetVector3ParameterValue(static_cast(index.GetValue()), outValue); + return GetVector3ParameterValue(index.GetValue(), outValue); } @@ -1488,7 +1485,7 @@ namespace EMotionFX return false; } - return GetVector4ParameterValue(static_cast(index.GetValue()), outValue); + return GetVector4ParameterValue(index.GetValue(), outValue); } @@ -1500,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 417883d16f..9366fcff86 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h @@ -95,28 +95,28 @@ 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]; if (baseAttrib->GetType() == T::TYPE_ID) @@ -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 mParamValues[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,11 +237,11 @@ 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 mObjectFlags[objectIndex]; } + MCORE_INLINE void SetObjectFlags(size_t objectIndex, uint32 flags) { mObjectFlags[objectIndex] = flags; } + MCORE_INLINE void EnableObjectFlags(size_t objectIndex, uint32 flagsToEnable) { mObjectFlags[objectIndex] |= flagsToEnable; } + MCORE_INLINE void DisableObjectFlags(size_t objectIndex, uint32 flagsToDisable) { mObjectFlags[objectIndex] &= ~flagsToDisable; } + MCORE_INLINE void SetObjectFlags(size_t objectIndex, uint32 flags, bool enabled) { if (enabled) { @@ -252,25 +252,25 @@ namespace EMotionFX mObjectFlags[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 (mObjectFlags[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 (mObjectFlags[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 (mObjectFlags[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 (mObjectFlags[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 (mObjectFlags[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 (mObjectFlags[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 (mObjectFlags[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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp index 8e25f6f0a8..fc74d747c6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp @@ -128,8 +128,8 @@ namespace EMotionFX MCore::LockGuardRecursive lock(mAnimGraphLock); // 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; } @@ -156,8 +156,8 @@ namespace EMotionFX 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()) @@ -182,8 +182,8 @@ namespace EMotionFX MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); // 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; } @@ -218,33 +218,33 @@ namespace EMotionFX } - uint32 AnimGraphManager::FindAnimGraphIndex(AnimGraph* animGraph) const + size_t AnimGraphManager::FindAnimGraphIndex(AnimGraph* animGraph) const { MCore::LockGuardRecursive lock(mAnimGraphLock); auto iterator = AZStd::find(mAnimGraphs.begin(), mAnimGraphs.end(), animGraph); if (iterator == mAnimGraphs.end()) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } const size_t index = iterator - mAnimGraphs.begin(); - return static_cast(index); + return index; } - uint32 AnimGraphManager::FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const + size_t AnimGraphManager::FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const { MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); auto iterator = AZStd::find(mAnimGraphInstances.begin(), mAnimGraphInstances.end(), animGraphInstance); if (iterator == mAnimGraphInstances.end()) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } const size_t index = iterator - mAnimGraphInstances.begin(); - return static_cast(index); + return index; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h index 4973437b8e..55ee6599fd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h @@ -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(mAnimGraphLock); return mAnimGraphs.size(); } + MCORE_INLINE AnimGraph* GetAnimGraph(size_t index) const { MCore::LockGuardRecursive lock(mAnimGraphLock); return mAnimGraphs[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; @@ -67,7 +67,7 @@ namespace EMotionFX size_t GetNumAnimGraphInstances() const { MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); return mAnimGraphInstances.size(); } AnimGraphInstance* GetAnimGraphInstance(size_t index) const { MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); return mAnimGraphInstances[index]; } - uint32 FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const; + size_t FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const; void SetAnimGraphVisualizationEnabled(bool enabled); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp index 425b48ce2e..9303ea96c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp @@ -156,10 +156,10 @@ 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(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp index f9896cf677..e73f8cf731 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp @@ -50,7 +50,7 @@ namespace EMotionFX AnimGraphNode::AnimGraphNode() : AnimGraphObject(nullptr) , m_id(AnimGraphNodeId::Create()) - , mNodeIndex(MCORE_INVALIDINDEX32) + , mNodeIndex(InvalidIndex) , mDisabled(false) , mParentNode(nullptr) , mCustomData(nullptr) @@ -256,7 +256,7 @@ namespace EMotionFX // 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]); @@ -287,7 +287,7 @@ namespace EMotionFX if (iterator != mChildNodes.end()) { - const uint32 index = static_cast(iterator - mChildNodes.begin()); + const size_t index = AZStd::distance(mChildNodes.begin(), iterator); RemoveChildNode(index, delFromMem); } } @@ -384,77 +384,50 @@ 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(mChildNodes), end(mChildNodes), [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(mChildNodes) ? AZStd::distance(begin(mChildNodes), 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(mChildNodes.begin(), mChildNodes.end(), node); + return foundChildNode != end(mChildNodes) ? AZStd::distance(begin(mChildNodes), foundChildNode) : InvalidIndex; } AnimGraphNode* AnimGraphNode::FindFirstChildNodeOfType(const AZ::TypeId& nodeType) const { - for (AnimGraphNode* childNode : mChildNodes) + const auto foundChild = AZStd::find_if(begin(mChildNodes), end(mChildNodes), [nodeType](const AnimGraphNode* childNode) { - if (azrtti_typeid(childNode) == nodeType) - { - return childNode; - } - } - - return nullptr; + return azrtti_typeid(childNode) == nodeType; + }); + return foundChild != end(mChildNodes) ? *foundChild : nullptr; } bool AnimGraphNode::HasChildNodeOfType(const AZ::TypeId& nodeType) const { - for (const AnimGraphNode* childNode : mChildNodes) + return AZStd::any_of(begin(mChildNodes), end(mChildNodes), [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(mConnections), end(mConnections), [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 @@ -537,55 +510,43 @@ namespace EMotionFX // initialize the input ports - void AnimGraphNode::InitInputPorts(uint32 numPorts) + void AnimGraphNode::InitInputPorts(size_t numPorts) { mInputPorts.resize(numPorts); } // initialize the output ports - void AnimGraphNode::InitOutputPorts(uint32 numPorts) + void AnimGraphNode::InitOutputPorts(size_t numPorts) { mOutputPorts.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(mOutputPorts), end(mOutputPorts), [&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(mOutputPorts) ? AZStd::distance(begin(mOutputPorts), 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(mInputPorts), end(mInputPorts), [&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(mInputPorts) ? AZStd::distance(begin(mInputPorts), 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(); @@ -594,7 +555,7 @@ namespace EMotionFX // add an input port, and return its index - uint32 AnimGraphNode::AddInputPort() + size_t AnimGraphNode::AddInputPort() { const size_t currentSize = mInputPorts.size(); mInputPorts.emplace_back(); @@ -603,7 +564,7 @@ namespace EMotionFX // 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); @@ -611,7 +572,7 @@ namespace EMotionFX // 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); @@ -619,9 +580,9 @@ namespace EMotionFX // get the total number of children - uint32 AnimGraphNode::RecursiveCalcNumNodes() const + size_t AnimGraphNode::RecursiveCalcNumNodes() const { - uint32 result = 0; + size_t result = 0; for (const AnimGraphNode* childNode : mChildNodes) { childNode->RecursiveCountChildNodes(result); @@ -632,7 +593,7 @@ 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++; @@ -645,16 +606,16 @@ 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(); @@ -667,11 +628,11 @@ 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()); } @@ -684,11 +645,11 @@ namespace EMotionFX // 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()); } @@ -701,11 +662,11 @@ namespace EMotionFX // 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()); } @@ -716,26 +677,26 @@ namespace EMotionFX mOutputPorts[outputPortNr].mPortID = 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()); } @@ -747,11 +708,11 @@ namespace EMotionFX } // 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()); } @@ -764,11 +725,11 @@ namespace EMotionFX mInputPorts[inputPortNr].mPortID = 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()); } @@ -782,11 +743,11 @@ namespace EMotionFX } // 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()); } @@ -834,7 +795,7 @@ namespace EMotionFX } // 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); @@ -961,8 +922,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 +947,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 +956,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,8 +993,8 @@ 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); } @@ -1086,7 +1047,7 @@ namespace EMotionFX startEventIndex = 0; } - if (startEventIndex == MCORE_INVALIDINDEX32) + if (startEventIndex == InvalidIndex) { startEventIndex = syncTrackB->GetNumEvents() - 1; } @@ -1118,8 +1079,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,7 +1155,7 @@ 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) @@ -1217,22 +1178,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(mChildNodes), end(mChildNodes), [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); + }); } @@ -1425,60 +1379,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(mInputPorts), end(mInputPorts), [&portName](const Port& port) { - if (port.GetNameString() == portName) - { - return &port; - } - } - return nullptr; + return port.GetNameString() == portName; + }); + return foundPort != end(mInputPorts) ? 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(mOutputPorts), end(mOutputPorts), [&portName](const Port& port) { - if (port.GetNameString() == portName) - { - return &port; - } - } - return nullptr; + return port.GetNameString() == portName; + }); + return foundPort != end(mOutputPorts) ? 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(mInputPorts), end(mInputPorts), [portID](const Port& port) { - if (mInputPorts[i].mPortID == portID) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return port.mPortID == portID; + }); + return foundPort != end(mInputPorts) ? AZStd::distance(begin(mInputPorts), 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(mOutputPorts), end(mOutputPorts), [portID](const Port& port) { - if (mOutputPorts[i].mPortID == portID) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return port.mPortID == portID; + }); + return foundPort != end(mOutputPorts) ? AZStd::distance(begin(mOutputPorts), foundPort) : InvalidIndex; } @@ -1521,7 +1459,7 @@ 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(); @@ -1553,8 +1491,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); @@ -1644,7 +1582,7 @@ namespace EMotionFX // iterate over all incoming connections bool syncTrackFound = false; - size_t connectionIndex = MCORE_INVALIDINDEX32; + size_t connectionIndex = InvalidIndex; const size_t numConnections = mConnections.size(); for (size_t i = 0; i < numConnections; ++i) { @@ -1662,7 +1600,7 @@ namespace EMotionFX } } - if (connectionIndex != MCORE_INVALIDINDEX32) + if (connectionIndex != InvalidIndex) { uniqueData->Init(animGraphInstance, mConnections[connectionIndex]->GetSourceNode()); } @@ -1752,7 +1690,7 @@ 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(); for (size_t i = 0; i < numConnections; ++i) @@ -1786,7 +1724,7 @@ namespace EMotionFX RequestRefDatas(animGraphInstance); AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); - if (poseFound && connectionIndex != MCORE_INVALIDINDEX32) + if (poseFound && connectionIndex != InvalidIndex) { const BlendTreeConnection* connection = mConnections[connectionIndex]; AnimGraphNode* sourceNode = connection->GetSourceNode(); @@ -1894,8 +1832,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 +1843,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 +1852,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)); } @@ -2075,7 +2013,7 @@ namespace EMotionFX { if (mOutputPorts[i].mCompatibleTypes[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); @@ -2103,7 +2041,7 @@ namespace EMotionFX { if (mOutputPorts[i].mCompatibleTypes[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); @@ -2352,8 +2290,8 @@ namespace EMotionFX // for all output ports for (Port& port : mOutputPorts) { - const uint32 internalAttributeIndex = port.mAttributeIndex; - if (internalAttributeIndex != MCORE_INVALIDINDEX32) + const size_t internalAttributeIndex = port.mAttributeIndex; + if (internalAttributeIndex != InvalidIndex) { const size_t numInstances = mAnimGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numInstances; ++i) @@ -2363,18 +2301,18 @@ namespace EMotionFX } mAnimGraph->DecreaseInternalAttributeIndices(internalAttributeIndex); - port.mAttributeIndex = MCORE_INVALIDINDEX32; + port.mAttributeIndex = InvalidIndex; } } } // decrease values higher than a given param value - void AnimGraphNode::DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan) + void AnimGraphNode::DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan) { for (Port& port : mOutputPorts) { - if (port.mAttributeIndex > decreaseEverythingHigherThan && port.mAttributeIndex != MCORE_INVALIDINDEX32) + if (port.mAttributeIndex > decreaseEverythingHigherThan && port.mAttributeIndex != InvalidIndex) { port.mAttributeIndex--; } @@ -2498,7 +2436,7 @@ namespace EMotionFX } - void AnimGraphNode::ReserveChildNodes(uint32 numChildNodes) + void AnimGraphNode::ReserveChildNodes(size_t numChildNodes) { mChildNodes.reserve(numChildNodes); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h index 7377f27d7c..89f4db2e5d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h @@ -60,7 +60,7 @@ namespace EMotionFX 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 + size_t mAttributeIndex; // 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); } @@ -97,22 +97,22 @@ namespace EMotionFX bool CheckIfIsCompatibleWith(const Port& otherPort) const { // check the data types - for (uint32 myCompatibleTypeindex = 0; myCompatibleTypeindex < 4; ++myCompatibleTypeindex) + for (uint32 mCompatibleType : mCompatibleTypes) { // 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 (mCompatibleType == 0) { return false; } - for (uint32 otherCompatibleTypeIndex = 0; otherCompatibleTypeIndex < 4; ++otherCompatibleTypeIndex) + for (uint32 otherCompatibleTypeIndex : otherPort.mCompatibleTypes) { - if (otherPort.mCompatibleTypes[otherCompatibleTypeIndex] == mCompatibleTypes[myCompatibleTypeindex]) + if (otherCompatibleTypeIndex == mCompatibleType) { 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; } @@ -141,7 +141,7 @@ namespace EMotionFX : mConnection(nullptr) , mPortID(MCORE_INVALIDINDEX32) , mNameID(MCORE_INVALIDINDEX32) - , mAttributeIndex(MCORE_INVALIDINDEX32) { ClearCompatibleTypes(); } + , mAttributeIndex(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); @@ -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,7 +446,7 @@ namespace EMotionFX return 0; } - MCORE_INLINE AnimGraphNode* GetInputNode(uint32 portNr) + MCORE_INLINE AnimGraphNode* GetInputNode(size_t portNr) { const BlendTreeConnection* con = mInputPorts[portNr].mConnection; if (con == nullptr) @@ -456,7 +456,7 @@ 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; if (con == 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,8 +648,8 @@ 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 mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance); } + MCORE_INLINE MCore::AttributeFloat* GetOutputNumber(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { @@ -658,7 +658,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeFloat::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -667,7 +667,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeFloat::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -676,7 +676,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeInt32::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -685,7 +685,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeString::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -694,7 +694,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeBool::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -703,7 +703,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeVector2::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -712,7 +712,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeVector3::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -721,7 +721,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeVector4::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -730,7 +730,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeQuaternion::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -739,7 +739,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeColor::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -748,7 +748,7 @@ namespace EMotionFX MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == AttributePose::TYPE_ID); return static_cast(mOutputPorts[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) { @@ -758,18 +758,18 @@ namespace EMotionFX return static_cast(mOutputPorts[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; @@ -801,24 +801,24 @@ namespace EMotionFX 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(); + 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(mOutputPorts[portIndex].mAttributeIndex); } + MCORE_INLINE Port& GetInputPort(size_t index) { return mInputPorts[index]; } + MCORE_INLINE Port& GetOutputPort(size_t index) { return mOutputPorts[index]; } + MCORE_INLINE const Port& GetInputPort(size_t index) const { return mInputPorts[index]; } + MCORE_INLINE const Port& GetOutputPort(size_t index) const { return mOutputPorts[index]; } void RelinkPortConnections(); - MCORE_INLINE uint32 GetNumConnections() const { return static_cast(mConnections.size()); } - MCORE_INLINE BlendTreeConnection* GetConnection(uint32 index) const { return mConnections[index]; } + MCORE_INLINE size_t GetNumConnections() const { return mConnections.size(); } + MCORE_INLINE BlendTreeConnection* GetConnection(size_t index) const { return mConnections[index]; } const AZStd::vector& GetConnections() const { return mConnections; } AZ_FORCE_INLINE AnimGraphNode* GetParentNode() const { return mParentNode; } @@ -829,7 +829,7 @@ namespace EMotionFX * @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]; } + MCORE_INLINE size_t GetNumChildNodes() const { return mChildNodes.size(); } + MCORE_INLINE AnimGraphNode* GetChildNode(size_t index) const { return mChildNodes[index]; } const AZStd::vector& GetChildNodes() const { return mChildNodes; } 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 @@ -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 mNodeIndex; } + MCORE_INLINE void SetNodeIndex(size_t index) { mNodeIndex = index; } void ResetPoseRefCount(AnimGraphInstance* animGraphInstance); MCORE_INLINE void IncreasePoseRefCount(AnimGraphInstance* animGraphInstance) { FindOrCreateUniqueNodeData(animGraphInstance)->IncreasePoseRefCount(); } @@ -944,7 +944,7 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); protected: - uint32 mNodeIndex; + size_t mNodeIndex; AZ::u64 m_id; AZStd::vector mConnections; AZStd::vector mInputPorts; @@ -967,7 +967,7 @@ namespace EMotionFX 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..a787dd25a2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp @@ -26,7 +26,7 @@ namespace EMotionFX , mPreSyncTime(0.0f) , mGlobalWeight(1.0f) , mLocalWeight(1.0f) - , mSyncIndex(MCORE_INVALIDINDEX32) + , mSyncIndex(InvalidIndex) , mPoseRefCount(0) , mRefDataRefCount(0) , mInheritFlags(0) @@ -55,7 +55,7 @@ namespace EMotionFX mLocalWeight = 1.0f; mInheritFlags = 0; m_isMirrorMotion = false; - mSyncIndex = MCORE_INVALIDINDEX32; + mSyncIndex = InvalidIndex; mSyncTrack = nullptr; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h index a3bfc34606..68d49ca511 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h @@ -54,8 +54,8 @@ namespace EMotionFX MCORE_INLINE AnimGraphNode* GetNode() const { return reinterpret_cast(mObject); } MCORE_INLINE void SetNode(AnimGraphNode* node) { mObject = 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) { mSyncIndex = syncIndex; } + MCORE_INLINE size_t GetSyncIndex() const { return mSyncIndex; } MCORE_INLINE void SetCurrentPlayTime(float absoluteTime) { mCurrentTime = absoluteTime; } MCORE_INLINE float GetCurrentPlayTime() const { return mCurrentTime; } @@ -108,7 +108,7 @@ namespace EMotionFX float mPreSyncTime; float mGlobalWeight; float mLocalWeight; - uint32 mSyncIndex; /**< The last used sync track index. */ + size_t mSyncIndex; /**< The last used sync track index. */ uint8 mPoseRefCount; uint8 mRefDataRefCount; uint8 mInheritFlags; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp index 3d93476c6a..a14401d3c8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp @@ -30,7 +30,7 @@ namespace EMotionFX } - AnimGraphNodeGroup::AnimGraphNodeGroup(const char* groupName, uint32 numNodes) + AnimGraphNodeGroup::AnimGraphNodeGroup(const char* groupName, size_t numNodes) { SetName(groupName); SetNumNodes(numNodes); @@ -100,28 +100,28 @@ namespace EMotionFX // set the number of nodes - void AnimGraphNodeGroup::SetNumNodes(uint32 numNodes) + void AnimGraphNodeGroup::SetNumNodes(size_t numNodes) { mNodeIds.resize(numNodes); } // get the number of nodes - uint32 AnimGraphNodeGroup::GetNumNodes() const + size_t AnimGraphNodeGroup::GetNumNodes() const { - return static_cast(mNodeIds.size()); + return mNodeIds.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; } // get the node number of a given index - AnimGraphNodeId AnimGraphNodeGroup::GetNode(uint32 index) const + AnimGraphNodeId AnimGraphNodeGroup::GetNode(size_t index) const { return mNodeIds[index]; } @@ -147,7 +147,7 @@ namespace EMotionFX // 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); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h index a3aa0ec9a6..611cfd6824 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp index c687dcadb1..7b4afbd38a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp @@ -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) @@ -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 diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h index 2f01b572e3..32905d66a7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h @@ -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,14 +144,14 @@ 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 mObjectIndex; } + MCORE_INLINE void SetObjectIndex(size_t index) { mObjectIndex = index; } MCORE_INLINE AnimGraph* GetAnimGraph() const { return mAnimGraph; } MCORE_INLINE void SetAnimGraph(AnimGraph* animGraph) { mAnimGraph = 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(AZStd::vector& outObjects) const; @@ -167,7 +167,7 @@ namespace EMotionFX protected: AnimGraph* mAnimGraph; - uint32 mObjectIndex; + size_t mObjectIndex; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h index 122749e714..a2b21aec6a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h @@ -39,7 +39,7 @@ namespace EMotionFX void LinkToActorInstance(const ActorInstance* actorInstance); void InitFromBindPose(const ActorInstance* actorInstance); - MCORE_INLINE uint32 GetNumNodes() const { return mPose.GetNumTransforms(); } + MCORE_INLINE size_t 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; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp index 5f139d9c49..3314ff0a17 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp @@ -27,10 +27,9 @@ namespace EMotionFX AnimGraphPosePool::~AnimGraphPosePool() { // delete all poses - const uint32 numPoses = mPoses.size(); - for (uint32 i = 0; i < numPoses; ++i) + for (AnimGraphPose* mPose : mPoses) { - delete mPoses[i]; + delete mPose; } mPoses.clear(); @@ -40,17 +39,16 @@ namespace EMotionFX // resize the number of poses in the pool - void AnimGraphPosePool::Resize(uint32 numPoses) + void AnimGraphPosePool::Resize(size_t numPoses) { - const uint32 numOldPoses = mPoses.size(); + const size_t numOldPoses = mPoses.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.back(); MCORE_ASSERT(AZStd::find(begin(mFreePoses), end(mFreePoses), pose) == end(mFreePoses)); // make sure the pose is not already in use @@ -60,7 +58,8 @@ namespace EMotionFX } 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.emplace_back(newPose); @@ -74,12 +73,12 @@ namespace EMotionFX AnimGraphPose* AnimGraphPosePool::RequestPose(const ActorInstance* actorInstance) { // if we have no free poses left, allocate a new one - if (mFreePoses.size() == 0) + if (mFreePoses.empty()) { AnimGraphPose* newPose = new AnimGraphPose(); newPose->LinkToActorInstance(actorInstance); mPoses.emplace_back(newPose); - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedPoses()); + mMaxUsed = AZStd::max(mMaxUsed, GetNumUsedPoses()); newPose->SetIsInUse(true); return newPose; } @@ -89,7 +88,7 @@ namespace EMotionFX //if (pose->GetActorInstance() != actorInstance) pose->LinkToActorInstance(actorInstance); mFreePoses.pop_back(); // remove it from the list of free poses - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedPoses()); + mMaxUsed = AZStd::max(mMaxUsed, GetNumUsedPoses()); pose->SetIsInUse(true); return pose; } @@ -107,10 +106,8 @@ namespace EMotionFX // free all poses void AnimGraphPosePool::FreeAllPoses() { - const uint32 numPoses = mPoses.size(); - for (uint32 i = 0; i < numPoses; ++i) + for (AnimGraphPose* curPose : mPoses) { - 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 8f7a38be97..8148d88926 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h @@ -34,7 +34,7 @@ namespace EMotionFX AnimGraphPosePool(); ~AnimGraphPosePool(); - void Resize(uint32 numPoses); + void Resize(size_t numPoses); AnimGraphPose* RequestPose(const ActorInstance* actorInstance); void FreePose(AnimGraphPose* pose); @@ -43,13 +43,13 @@ namespace EMotionFX MCORE_INLINE size_t GetNumFreePoses() const { return mFreePoses.size(); } MCORE_INLINE size_t GetNumPoses() const { return mPoses.size(); } - MCORE_INLINE size_t GetNumUsedPoses() const { return (mPoses.size() - mFreePoses.size()); } - MCORE_INLINE uint32 GetNumMaxUsedPoses() const { return mMaxUsed; } + MCORE_INLINE size_t GetNumUsedPoses() const { return mPoses.size() - mFreePoses.size(); } + MCORE_INLINE size_t GetNumMaxUsedPoses() const { return mMaxUsed; } MCORE_INLINE void ResetMaxUsedPoses() { mMaxUsed = 0; } private: AZStd::vector mPoses; AZStd::vector mFreePoses; - uint32 mMaxUsed; + size_t mMaxUsed; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp index 289a9c4982..f4e7402fdf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp @@ -28,10 +28,9 @@ namespace EMotionFX AnimGraphRefCountedDataPool::~AnimGraphRefCountedDataPool() { // delete all items - const uint32 numItems = mItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (AnimGraphRefCountedData*& mItem : mItems) { - delete mItems[i]; + delete mItem; } mItems.clear(); @@ -41,17 +40,16 @@ namespace EMotionFX // resize the number of items in the pool - void AnimGraphRefCountedDataPool::Resize(uint32 numItems) + void AnimGraphRefCountedDataPool::Resize(size_t numItems) { - const uint32 numOldItems = mItems.size(); + const size_t numOldItems = mItems.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.back(); MCORE_ASSERT(AZStd::find(begin(mFreeItems), end(mFreeItems), item) != end(mFreeItems)); // make sure the Item is not already in use @@ -61,7 +59,8 @@ namespace EMotionFX } 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.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.size() == 0) + if (mFreeItems.empty()) { AnimGraphRefCountedData* newItem = new AnimGraphRefCountedData(); mItems.emplace_back(newItem); - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedItems()); + mMaxUsed = AZStd::max(mMaxUsed, GetNumUsedItems()); return newItem; } // request the last free item AnimGraphRefCountedData* item = mFreeItems[mFreeItems.size() - 1]; mFreeItems.pop_back(); // remove it from the list of free Items - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedItems()); + mMaxUsed = AZStd::max(mMaxUsed, GetNumUsedItems()); return item; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h index 33590766ff..d05ea5b5a1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h @@ -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 size_t GetNumFreeItems() const { return mFreeItems.size(); } MCORE_INLINE size_t GetNumItems() const { return mItems.size(); } - MCORE_INLINE size_t GetNumUsedItems() const { return (mItems.size() - mFreeItems.size()); } - MCORE_INLINE uint32 GetNumMaxUsedItems() const { return mMaxUsed; } + MCORE_INLINE size_t GetNumUsedItems() const { return mItems.size() - mFreeItems.size(); } + MCORE_INLINE size_t GetNumMaxUsedItems() const { return mMaxUsed; } MCORE_INLINE void ResetMaxUsedItems() { mMaxUsed = 0; } private: AZStd::vector mItems; AZStd::vector mFreeItems; - uint32 mMaxUsed; + size_t mMaxUsed; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp index e6f6bb0985..a1f9af2935 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(); } @@ -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())); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp index 110a35781e..089f5a7df8 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(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp index a191ae9e13..3ad6ae8b8b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp @@ -36,7 +36,7 @@ namespace EMotionFX AnimGraphStateMachine::AnimGraphStateMachine() : AnimGraphNode() , mEntryState(nullptr) - , mEntryStateNodeNr(MCORE_INVALIDINDEX32) + , mEntryStateNodeNr(InvalidIndex) , m_entryStateId(AnimGraphNodeId::InvalidId) , m_alwaysStartInEntryState(true) { @@ -204,7 +204,6 @@ namespace EMotionFX bool requestInterruption = false; const bool isTransitioning = IsTransitioning(animGraphInstance); AnimGraphStateTransition* latestActiveTransition = GetLatestActiveTransition(uniqueData); - const AnimGraphNodeId sourceNodeId = sourceNode->GetId(); for (AnimGraphStateTransition* curTransition : mTransitions) { @@ -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. @@ -973,7 +971,7 @@ namespace EMotionFX // Legacy file format way. if (!mEntryState) { - if (mEntryStateNodeNr != MCORE_INVALIDINDEX32 && mEntryStateNodeNr < GetNumChildNodes()) + if (mEntryStateNodeNr != InvalidIndex && mEntryStateNodeNr < GetNumChildNodes()) { mEntryState = GetChildNode(mEntryStateNodeNr); } @@ -1095,11 +1093,11 @@ namespace EMotionFX 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 (mCurrentState && stateMachine->FindChildNodeIndex(mCurrentState) == InvalidIndex) { mCurrentState = nullptr; } - if (mPreviousState && stateMachine->FindChildNodeIndex(mPreviousState) == MCORE_INVALIDINDEX32) + if (mPreviousState && stateMachine->FindChildNodeIndex(mPreviousState) == InvalidIndex) { mPreviousState = nullptr; } @@ -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) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h index 8583a8a6e3..1f8d1eb591 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h @@ -267,7 +267,7 @@ namespace EMotionFX 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. */ + size_t mEntryStateNodeNr; /**< 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 de3fa990bf..747188ead2 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp index 6c0bd18548..c6ccf038dd 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) { 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/BlendTree.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.cpp index 1952ba9b2a..809a5d1c31 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.cpp @@ -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/BlendTreeAccumTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.cpp index 60e5f837b0..ffbf38c48a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.cpp @@ -49,7 +49,7 @@ namespace EMotionFX } else { - mNodeIndex = InvalidIndex32; + mNodeIndex = InvalidIndex; SetHasError(true); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h index 86ad69ec69..d8ca76aaa8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h @@ -84,7 +84,7 @@ namespace EMotionFX public: Transform mAdditiveTransform = Transform::CreateIdentity(); - uint32 mNodeIndex = InvalidIndex32; + size_t mNodeIndex = InvalidIndex; float mDeltaTime = 0.0f; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp index e6ce8c6119..f16d2f6943 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp @@ -214,7 +214,7 @@ namespace EMotionFX for (size_t n = 0; n < numNodes; ++n) { const float finalWeight = blendWeight;// * uniqueData->mWeights[n]; - const uint32 nodeIndex = uniqueData->mMask[n]; + const size_t nodeIndex = uniqueData->mMask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.ApplyAdditive(additivePose.GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp index 7e2fdd4736..78fbd91dd1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp @@ -237,7 +237,7 @@ namespace EMotionFX for (size_t n = 0; n < numNodes; ++n) { const float finalWeight = blendWeight /* * uniqueData->mWeights[n]*/; - const uint32 nodeIndex = uniqueData->mMask[n]; + const size_t nodeIndex = uniqueData->mMask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.Blend(localMaskPose.GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); @@ -250,7 +250,7 @@ namespace EMotionFX for (size_t n = 0; n < numNodes; ++n) { const float finalWeight = blendWeight /* * uniqueData->mWeights[n]*/; - const uint32 nodeIndex = uniqueData->mMask[n]; + const size_t nodeIndex = uniqueData->mMask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.BlendAdditive(localMaskPose.GetLocalSpaceTransform(nodeIndex), bindPose->GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp index f3b9ee2014..dfa7be26f8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp @@ -217,7 +217,7 @@ namespace EMotionFX for (size_t n = 0; n < numNodes; ++n) { const float finalWeight = blendWeight /* * uniqueData->mWeights[n]*/; - const uint32 nodeIndex = uniqueData->mMask[n]; + const size_t nodeIndex = uniqueData->mMask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.Blend(localMaskPose.GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp index 1a33ee1d85..2876605b0a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp @@ -116,7 +116,7 @@ namespace EMotionFX *outWeight = MCore::Clamp(*outWeight, 0.0f, 1.0f); UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - if (uniqueData->mMask.size() > 0) + if (!uniqueData->mMask.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..217e2a2e23 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h @@ -54,7 +54,7 @@ namespace EMotionFX void Update() override; public: - AZStd::vector mMask; + AZStd::vector mMask; AnimGraphNode* mSyncTrackNode; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp index 8e0e67e95a..97d7d4baa0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp @@ -270,8 +270,8 @@ 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 @@ -412,8 +412,8 @@ namespace EMotionFX 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; @@ -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]; @@ -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); @@ -924,8 +924,8 @@ 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp index 4947836da8..fd04a43251 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp @@ -36,7 +36,7 @@ namespace EMotionFX BlendTreeGetTransformNode* transformNode = azdynamic_cast(mObject); 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(); @@ -106,7 +106,7 @@ 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 @@ -117,7 +117,7 @@ namespace EMotionFX } Pose* pose = nullptr; - if (uniqueData->m_nodeIndex != MCORE_INVALIDINDEX32) + if (uniqueData->m_nodeIndex != InvalidIndex) { if (m_actorNode.second == 0) { 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..f904f35ba4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.cpp @@ -40,7 +40,7 @@ namespace EMotionFX const ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); const Actor* actor = actorInstance->GetActor(); - mNodeIndex = InvalidIndex32; + mNodeIndex = InvalidIndex; SetHasError(true); const AZStd::string& targetJointName = lookAtNode->GetTargetNodeName(); @@ -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->mNodeIndex; Pose& outTransformPose = outputPose->GetPose(); Transform globalTransform = outTransformPose.GetWorldSpaceTransform(nodeIndex); @@ -203,10 +203,10 @@ 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h index a7494b2514..4da3855dd1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h @@ -65,7 +65,7 @@ namespace EMotionFX public: AZ::Quaternion mRotationQuat = AZ::Quaternion::CreateIdentity(); float mTimeDelta = 0.0f; - uint32 mNodeIndex = InvalidIndex32; + size_t mNodeIndex = InvalidIndex; bool mFirstUpdate = true; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp index ac85704381..88da8346d0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp @@ -54,7 +54,7 @@ namespace EMotionFX , m_outputEvents3(true) { // setup the input ports - InitInputPorts(static_cast(m_numMasks)); + InitInputPorts(m_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,7 +104,7 @@ 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 < m_numMasks; ++i) { // if there is no connection plugged in if (mInputPorts[INPUTPORT_POSE_0 + i].mConnection == nullptr) @@ -121,7 +121,7 @@ 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 < m_numMasks; ++i) { // if there is no connection plugged in if (mInputPorts[INPUTPORT_POSE_0 + i].mConnection == nullptr) @@ -139,10 +139,9 @@ namespace EMotionFX 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->mMasks[i]) { - const uint32 nodeIndex = uniqueData->mMasks[i][n]; - outputLocalPose.SetLocalSpaceTransform(nodeIndex, localPose.GetLocalSpaceTransform(nodeIndex)); + outputLocalPose.SetLocalSpaceTransform(nodeIndex, localPose.GetLocalSpaceTransform(nodeIndex)); } } else @@ -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 < m_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 < m_numMasks; ++i) { // if the port has no input, skip it AnimGraphNode* inputNode = GetInputNode(INPUTPORT_POSE_0 + i); @@ -217,9 +216,8 @@ namespace EMotionFX 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->mMasks[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..0cddd9610a 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 > mMasks; }; BlendTreeMaskLegacyNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp index 8b65f76dbd..d43ac3b033 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp @@ -36,10 +36,10 @@ namespace EMotionFX const Actor* actor = mAnimGraphInstance->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 = mAnimGraphInstance->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. @@ -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)); } @@ -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..04199c18ca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp @@ -164,11 +164,11 @@ 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 diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp index 7420c005a9..ad88909e29 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp @@ -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); } } @@ -160,7 +162,7 @@ namespace EMotionFX } // Try to modify the morph target weight with the value we specified as input. - if (!mDisabled && uniqueData->m_morphTargetIndex != MCORE_INVALIDINDEX32) + if (!mDisabled && 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) 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/BlendTreeRagdollNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollNode.cpp index 4cf82cc77b..f62d569a16 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollNode.cpp @@ -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); 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/BlendTreeSetTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp index b922eb9b59..0817b95614 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp @@ -38,7 +38,7 @@ namespace EMotionFX ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); Actor* actor = actorInstance->GetActor(); - m_nodeIndex = InvalidIndex32; + m_nodeIndex = InvalidIndex; const AZStd::string& jointName = transformNode->GetJointName(); if (!jointName.empty()) @@ -106,7 +106,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode()) { - SetHasError(uniqueData, uniqueData->m_nodeIndex == MCORE_INVALIDINDEX32); + SetHasError(uniqueData, uniqueData->m_nodeIndex == InvalidIndex); } OutputAllIncomingNodes(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; 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/BlendTreeTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.cpp index e8005cee28..07f3256a35 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.cpp @@ -41,7 +41,7 @@ namespace EMotionFX const AZStd::string& targetJointName = transformNode->GetTargetJointName(); - mNodeIndex = InvalidIndex32; + mNodeIndex = InvalidIndex; SetHasError(true); if (!targetJointName.empty()) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.h index 7d685c2528..1d337fa6a1 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 mNodeIndex = InvalidIndex; }; BlendTreeTransformNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp index 1cfafb11d1..1054cef095 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp @@ -39,12 +39,12 @@ namespace EMotionFX const Skeleton* skeleton = actor->GetSkeleton(); // don't update the next time again - mNodeIndexA = InvalidIndex32; - mNodeIndexB = InvalidIndex32; - mNodeIndexC = InvalidIndex32; - mAlignNodeIndex = InvalidIndex32; - mBendDirNodeIndex = InvalidIndex32; - mEndEffectorNodeIndex = InvalidIndex32; + mNodeIndexA = InvalidIndex; + mNodeIndexB = InvalidIndex; + mNodeIndexC = InvalidIndex; + mAlignNodeIndex = InvalidIndex; + mBendDirNodeIndex = InvalidIndex; + mEndEffectorNodeIndex = InvalidIndex; SetHasError(true); // Find the end joint. @@ -62,14 +62,14 @@ namespace EMotionFX // Get the second joint. mNodeIndexB = jointC->GetParentIndex(); - if (mNodeIndexB == InvalidIndex32) + if (mNodeIndexB == InvalidIndex) { return; } // Get the third joint. mNodeIndexA = skeleton->GetNode(mNodeIndexB)->GetParentIndex(); - if (mNodeIndexA == InvalidIndex32) + if (mNodeIndexA == InvalidIndex) { return; } @@ -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->mNodeIndexA; + const size_t nodeIndexB = uniqueData->mNodeIndexB; + const size_t nodeIndexC = uniqueData->mNodeIndexC; + const size_t bendDirIndex = uniqueData->mBendDirNodeIndex; + size_t alignNodeIndex = uniqueData->mAlignNodeIndex; + size_t endEffectorNodeIndex = uniqueData->mEndEffectorNodeIndex; // 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); @@ -322,7 +322,7 @@ 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()) @@ -350,7 +350,7 @@ namespace EMotionFX AZ::Vector3 bendDir; if (m_extractBendDir) { - if (bendDirIndex != MCORE_INVALIDINDEX32) + if (bendDirIndex != InvalidIndex) { bendDir = outTransformPose.GetWorldSpaceTransform(bendDirIndex).mPosition - globalTransformA.mPosition; } @@ -386,7 +386,7 @@ 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) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h index 7a1a858804..807eb4044e 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 mNodeIndexA = InvalidIndex; + size_t mNodeIndexB = InvalidIndex; + size_t mNodeIndexC = InvalidIndex; + size_t mEndEffectorNodeIndex = InvalidIndex; + size_t mAlignNodeIndex = InvalidIndex; + size_t mBendDirNodeIndex = InvalidIndex; }; BlendTreeTwoLinkIKNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp index 72c52edc66..8f1346f543 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp @@ -110,12 +110,12 @@ 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp index 34e336bf2f..c107ae88f7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp @@ -33,7 +33,7 @@ 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) @@ -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); @@ -84,7 +84,7 @@ namespace EMotionFX // pre-calculate the skinning matrices for (BoneInfo& boneInfo : m_bones) { - const uint32 nodeIndex = boneInfo.mNodeNr; + const size_t nodeIndex = boneInfo.mNodeNr; const Transform skinTransform = actor->GetInverseBindPoseTransform(nodeIndex) * pose->GetModelSpaceTransform(nodeIndex); boneInfo.mDualQuat.FromRotationTranslation(skinTransform.mRotation, skinTransform.mPosition); } @@ -327,7 +327,7 @@ namespace EMotionFX AZ::Outcome boneIndexOutcome = FindLocalBoneIndex(influence->GetNodeNr()); if (boneIndexOutcome.IsSuccess()) { - influence->SetBoneNr(static_cast(boneIndexOutcome.GetValue())); + influence->SetBoneNr(aznumeric_caster(boneIndexOutcome.GetValue())); } else { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h index d3bec012f6..154885ea7d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h @@ -75,7 +75,7 @@ namespace EMotionFX * @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. @@ -104,7 +104,7 @@ namespace EMotionFX * @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].mNodeNr; } /** * Pre-allocate space for a given number of local bones. @@ -119,11 +119,11 @@ namespace EMotionFX */ struct EMFX_API BoneInfo { - uint32 mNodeNr; /**< The node number. */ + size_t mNodeNr; /**< The node number. */ MCore::DualQuaternion mDualQuat; /**< The dual quat of the pre-calculated matrix that contains the "globalMatrix * inverse(bindPoseMatrix)". */ MCORE_INLINE BoneInfo() - : mNodeNr(MCORE_INVALIDINDEX32) {} + : mNodeNr(InvalidIndex) {} }; AZStd::vector m_bones; /**< The array of bone information used for pre-calculation. */ @@ -155,6 +155,6 @@ namespace EMotionFX * @param nodeIndex The node number to search for. * @result The index inside the mBones 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/Importer/ChunkProcessors.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp index b6b0b091a2..604dfb8bb9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp @@ -1907,7 +1907,6 @@ namespace EMotionFX const MCore::Endian::EEndianType endianType = importParams.mEndianType; Actor* actor = importParams.mActor; - uint32 i; MCORE_ASSERT(actor); Skeleton* skeleton = actor->GetSkeleton(); @@ -1920,7 +1919,7 @@ namespace EMotionFX const uint32 numAttachmentNodes = attachmentNodesChunk.mNumNodes; // 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; @@ -1940,8 +1939,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); @@ -1949,7 +1948,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()); } } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp index 069182883c..e710192afd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp @@ -60,10 +60,9 @@ namespace EMotionFX Importer::~Importer() { // remove all chunk processors - const uint32 numProcessors = mChunkProcessors.size(); - for (uint32 i = 0; i < numProcessors; ++i) + for (ChunkProcessor* mChunkProcessor : mChunkProcessors) { - mChunkProcessors[i]->Destroy(); + mChunkProcessor->Destroy(); } } @@ -730,20 +729,11 @@ namespace EMotionFX SharedData* Importer::FindSharedData(AZStd::vector* sharedDataArray, uint32 type) { // for all shared data - const uint32 numSharedData = sharedDataArray->size(); - for (uint32 i = 0; i < numSharedData; ++i) + const auto foundSharedData = AZStd::find_if(begin(*sharedDataArray), end(*sharedDataArray), [type](const SharedData* sharedData) { - SharedData* sharedData = sharedDataArray->at(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; } @@ -764,11 +754,9 @@ namespace EMotionFX mLogDetails = detailLoggingActive; // set the processors logging flag - const int32 numProcessors = mChunkProcessors.size(); - for (int32 i = 0; i < numProcessors; i++) + for (ChunkProcessor* processor : mChunkProcessors) { - ChunkProcessor* processor = mChunkProcessors[i]; - processor->SetLogging((mLoggingActive && detailLoggingActive)); // only enable if logging is also enabled + processor->SetLogging(mLoggingActive && detailLoggingActive); // only enable if logging is also enabled } } @@ -789,10 +777,8 @@ namespace EMotionFX // reset shared objects so that the importer is ready for use again void Importer::ResetSharedData(AZStd::vector& sharedData) { - const int32 numSharedData = sharedData.size(); - for (int32 i = 0; i < numSharedData; i++) + for (SharedData* data : sharedData) { - SharedData* data = sharedData[i]; data->Reset(); data->Destroy(); } @@ -804,20 +790,11 @@ namespace EMotionFX ChunkProcessor* Importer::FindChunk(uint32 chunkID, uint32 version) const { // for all chunk processors - const uint32 numProcessors = mChunkProcessors.size(); - for (uint32 i = 0; i < numProcessors; ++i) + const auto foundProcessor = AZStd::find_if(begin(mChunkProcessors), end(mChunkProcessors), [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(mChunkProcessors) ? *foundProcessor : nullptr; } 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 8c5c56895a..5f8f7b49d0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h @@ -46,7 +46,7 @@ namespace EMotionFX /** * @param nrKeys The number of keyframes which the keytrack contains (preallocates this amount of keyframes). */ - KeyTrackLinearDynamic(uint32 nrKeys); + KeyTrackLinearDynamic(size_t nrKeys); static void Reflect(AZ::ReflectContext* context); @@ -54,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. @@ -81,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). @@ -107,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. @@ -133,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. @@ -159,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. @@ -190,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. @@ -205,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. @@ -228,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. @@ -236,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. @@ -245,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. @@ -254,7 +254,7 @@ 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. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl index 94abe4d707..806a45b69a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl @@ -8,7 +8,7 @@ // extended constructor template -KeyTrackLinearDynamic::KeyTrackLinearDynamic(uint32 nrKeys) +KeyTrackLinearDynamic::KeyTrackLinearDynamic(size_t nrKeys) { SetNumKeys(nrKeys); } @@ -53,17 +53,16 @@ void KeyTrackLinearDynamic::Init() // 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 : mKeys) { - 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]; @@ -73,20 +72,20 @@ MCORE_INLINE KeyFrame* KeyTrackLinearDynamic MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::GetFirstKey() { - return (mKeys.size() > 0) ? &mKeys[0] : nullptr; + return !mKeys.empty() ? &mKeys[0] : nullptr; } template MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::GetLastKey() { - return (mKeys.size() > 0) ? &mKeys.back() : nullptr; + return !mKeys.empty() ? &mKeys.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]; @@ -96,14 +95,14 @@ MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic::GetFirstKey() const { - return (mKeys.size() > 0) ? &mKeys[0] : nullptr; + return !mKeys.empty() ? &mKeys[0] : nullptr; } template MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic::GetLastKey() const { - return (mKeys.size() > 0) ? &mKeys.back() : nullptr; + return !mKeys.empty() ? &mKeys.back() : nullptr; } @@ -124,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 mKeys.size(); } @@ -134,7 +133,7 @@ template MCORE_INLINE void KeyTrackLinearDynamic::AddKey(float time, const ReturnType& value, bool smartPreAlloc) { #ifdef MCORE_DEBUG - if (mKeys.size() > 0) + if (!mKeys.empty()) { MCORE_ASSERT(time >= mKeys.back().GetTime()); } @@ -154,7 +153,7 @@ MCORE_INLINE void KeyTrackLinearDynamic::AddKey(float t // 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())); } @@ -165,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, &mKeys.front(), mKeys.size()); // if no key was found - return (keyNumber != MCORE_INVALIDINDEX32) ? &mKeys[keyNumber] : nullptr; + return (keyNumber != InvalidIndex) ? &mKeys[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(!mKeys.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, &mKeys.front(), mKeys.size()); if (cachedKey) { @@ -208,7 +207,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float { if (mKeys.size() > 2) { - localCachedKey = static_cast(mKeys.size()) - 3; + localCachedKey = mKeys.size() - 3; } else { @@ -243,7 +242,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float *outWasCacheHit = 0; } - keyNumber = KeyFrameFinder::FindKey(currentTime, &mKeys.front(), static_cast(mKeys.size())); + keyNumber = KeyFrameFinder::FindKey(currentTime, &mKeys.front(), mKeys.size()); if (cachedKey) { @@ -254,7 +253,7 @@ 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) @@ -287,7 +286,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float // 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]; @@ -303,7 +302,7 @@ 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]; @@ -318,7 +317,7 @@ 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]; @@ -341,7 +340,7 @@ void KeyTrackLinearDynamic::AddKeySorted(float time, co { if (mKeys.capacity() == mKeys.size()) { - const uint32 numToReserve = static_cast(mKeys.size() / 4); + const size_t numToReserve = mKeys.size() / 4; mKeys.reserve(mKeys.capacity() + numToReserve); } } @@ -371,13 +370,13 @@ void KeyTrackLinearDynamic::AddKeySorted(float time, co } // quickly find the location to insert, and insert it - const uint32 place = KeyFrameFinder::FindKey(keyTime, &mKeys.front(), static_cast(mKeys.size())); + const size_t place = KeyFrameFinder::FindKey(keyTime, &mKeys.front(), mKeys.size()); mKeys.insert(mKeys.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)); } @@ -404,7 +403,7 @@ 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 @@ -419,8 +418,8 @@ uint32 KeyTrackLinearDynamic::Optimize(float maxError) 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) @@ -459,7 +458,7 @@ uint32 KeyTrackLinearDynamic::Optimize(float maxError) // pre-alloc keys template -void KeyTrackLinearDynamic::SetNumKeys(uint32 numKeys) +void KeyTrackLinearDynamic::SetNumKeys(size_t numKeys) { // resize the array of keys mKeys.resize(numKeys); @@ -468,7 +467,7 @@ void KeyTrackLinearDynamic::SetNumKeys(uint32 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); @@ -478,7 +477,7 @@ MCORE_INLINE void KeyTrackLinearDynamic::SetKey(uint32 // 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); @@ -490,31 +489,17 @@ 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 !mKeys.empty() && AZStd::any_of(begin(mKeys), end(mKeys), [&initialPose, maxError](const auto& key) { - return false; - } - - // get the number of keyframes and iterate through them - const uint32 numKeyFrames = GetNumKeys(); - for (uint32 i = 0; i < numKeyFrames; ++i) - { - // 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); } @@ -522,7 +507,7 @@ MCORE_INLINE void KeyTrackLinearDynamic::Reserve(uint32 // calculate memory usage template -uint32 KeyTrackLinearDynamic::CalcMemoryUsage(bool includeMembers) const +size_t KeyTrackLinearDynamic::CalcMemoryUsage([[maybe_unused]] bool includeMembers) const { return 0; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index c86cc66b61..d946344622 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -256,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"); @@ -269,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; } @@ -278,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); } @@ -374,10 +374,9 @@ namespace EMotionFX // copy all original data over the output data void Mesh::ResetToOriginalData() { - const uint32 numLayers = mVertexAttributes.size(); - for (uint32 i = 0; i < numLayers; ++i) + for (VertexAttributeLayer* mVertexAttribute : mVertexAttributes) { - mVertexAttributes[i]->ResetToOriginalData(); + mVertexAttribute->ResetToOriginalData(); } } @@ -392,10 +391,9 @@ namespace EMotionFX RemoveAllVertexAttributeLayers(); // get rid of all sub meshes - const uint32 numSubMeshes = mSubMeshes.size(); - for (uint32 i = 0; i < numSubMeshes; ++i) + for (SubMesh* subMesh : mSubMeshes) { - mSubMeshes[i]->Destroy(); + subMesh->Destroy(); } mSubMeshes.clear(); @@ -495,15 +493,14 @@ 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)); @@ -548,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 < mNumVertices; ++i) { orgTangents[i] = AZ::Vector4::CreateZero(); tangents[i] = AZ::Vector4::CreateZero(); @@ -564,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]; @@ -572,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]; @@ -604,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 < mNumVertices; ++i) { // get the normal AZ::Vector3 normal(normals[i]); @@ -801,7 +798,7 @@ namespace EMotionFX // remove a given submesh - void Mesh::RemoveSubMesh(uint32 nr, bool delFromMem) + void Mesh::RemoveSubMesh(size_t nr, bool delFromMem) { SubMesh* subMesh = mSubMeshes[nr]; mSubMeshes.erase(AZStd::next(begin(mSubMeshes), nr)); @@ -813,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.emplace(AZStd::next(begin(mSubMeshes), 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.size(); - for (uint32 i = 0; i < numAttributes; ++i) + for (auto* vertexAttribute : mVertexAttributes) { - if (mVertexAttributes[i]->GetType() == type) + if (vertexAttribute->GetType() == type) { numLayers++; } @@ -839,7 +835,7 @@ namespace EMotionFX // get the number of UV layers - uint32 Mesh::CalcNumUVLayers() const + size_t Mesh::CalcNumUVLayers() const { return CalcNumAttributeLayers(Mesh::ATTRIB_UVCOORDS); } @@ -866,36 +862,21 @@ namespace EMotionFX } - 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.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [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(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), 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; } @@ -917,7 +898,7 @@ namespace EMotionFX // remove a layer by its index - void Mesh::RemoveSharedVertexAttributeLayer(uint32 layerNr) + void Mesh::RemoveSharedVertexAttributeLayer(size_t layerNr) { MCORE_ASSERT(layerNr < mSharedVertexAttributes.size()); mSharedVertexAttributes[layerNr]->Destroy(); @@ -931,7 +912,7 @@ namespace EMotionFX } - VertexAttributeLayer* Mesh::GetVertexAttributeLayer(uint32 layerNr) + VertexAttributeLayer* Mesh::GetVertexAttributeLayer(size_t layerNr) { MCORE_ASSERT(layerNr < mVertexAttributes.size()); return mVertexAttributes[layerNr]; @@ -946,58 +927,33 @@ namespace EMotionFX // 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.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [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(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), 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.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [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(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), 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; } @@ -1009,8 +965,8 @@ namespace EMotionFX // 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; } @@ -1029,7 +985,7 @@ namespace EMotionFX } - void Mesh::RemoveVertexAttributeLayer(uint32 layerNr) + void Mesh::RemoveVertexAttributeLayer(size_t layerNr) { MCORE_ASSERT(layerNr < mVertexAttributes.size()); mVertexAttributes[layerNr]->Destroy(); @@ -1049,26 +1005,25 @@ namespace EMotionFX MCore::MemCopy(clone->mPolyVertexCounts, mPolyVertexCounts, sizeof(uint8) * mNumPolygons); // copy the submesh data - uint32 i; - const uint32 numSubMeshes = mSubMeshes.size(); + const size_t numSubMeshes = mSubMeshes.size(); clone->mSubMeshes.resize(numSubMeshes); - for (i = 0; i < numSubMeshes; ++i) + for (size_t i = 0; i < numSubMeshes; ++i) { clone->mSubMeshes[i] = mSubMeshes[i]->Clone(clone); } // clone the shared vertex attributes - const uint32 numSharedAttributes = mSharedVertexAttributes.size(); + const size_t numSharedAttributes = mSharedVertexAttributes.size(); clone->mSharedVertexAttributes.resize(numSharedAttributes); - for (i = 0; i < numSharedAttributes; ++i) + for (size_t i = 0; i < numSharedAttributes; ++i) { clone->mSharedVertexAttributes[i] = mSharedVertexAttributes[i]->Clone(); } // clone the non-shared vertex attributes - const uint32 numAttributes = mVertexAttributes.size(); + const size_t numAttributes = mVertexAttributes.size(); clone->mVertexAttributes.resize(numAttributes); - for (i = 0; i < numAttributes; ++i) + for (size_t i = 0; i < numAttributes; ++i) { clone->mVertexAttributes[i] = mVertexAttributes[i]->Clone(); } @@ -1091,92 +1046,13 @@ namespace EMotionFX } // swap all vertex attribute layers - const uint32 numLayers = mVertexAttributes.size(); - for (uint32 i = 0; i < numLayers; ++i) + const size_t numLayers = mVertexAttributes.size(); + for (size_t i = 0; i < numLayers; ++i) { mVertexAttributes[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) { @@ -1201,8 +1077,8 @@ namespace EMotionFX mNumVertices -= 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); } @@ -1215,7 +1091,7 @@ namespace EMotionFX for (uint32 w = 0; w < numVertsToRemove; ++w) { // adjust all submesh start index offsets changed - for (uint32 s = 0; s < mSubMeshes.size();) + for (size_t s = 0; s < mSubMeshes.size();) { SubMesh* subMesh = mSubMeshes[s]; @@ -1264,12 +1140,12 @@ 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.size();) + for (size_t i = 0; i < mSubMeshes.size();) { SubMesh* subMesh = mSubMeshes[i]; @@ -1306,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) @@ -1333,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) @@ -1518,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 @@ -1556,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); @@ -1589,11 +1463,11 @@ 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); } } } @@ -1627,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); @@ -1636,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) { @@ -1959,18 +1833,14 @@ namespace EMotionFX // scale all positional data void Mesh::Scale(float scaleFactor) { - // all unique layers - const uint32 numLayers = GetNumVertexAttributeLayers(); - for (uint32 i = 0; i < numLayers; ++i) + for (VertexAttributeLayer* layer : mVertexAttributes) { - GetVertexAttributeLayer(i)->Scale(scaleFactor); + layer->Scale(scaleFactor); } - // scale all shared layers - const uint32 numSharedLayers = GetNumSharedVertexAttributeLayers(); - for (uint32 i = 0; i < numSharedLayers; ++i) + for (VertexAttributeLayer* layer : mSharedVertexAttributes) { - GetSharedVertexAttributeLayer(i)->Scale(scaleFactor); + layer->Scale(scaleFactor); } // scale the positional data @@ -1987,97 +1857,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.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), 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.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), foundLayer) : InvalidIndex; } // find by name ID - uint32 Mesh::FindVertexAttributeLayerIndexByNameID(uint32 nameID) const + size_t Mesh::FindVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const uint32 numLayers = mVertexAttributes.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [nameID](const VertexAttributeLayer* layer) { - if (mVertexAttributes[i]->GetNameID() == nameID) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameID() == nameID; + }); + return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), foundLayer) : InvalidIndex; } // find by name - uint32 Mesh::FindSharedVertexAttributeLayerIndexByName(const char* name) const + size_t Mesh::FindSharedVertexAttributeLayerIndexByName(const char* name) const { - const uint32 numLayers = mSharedVertexAttributes.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mSharedVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), 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.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mSharedVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), foundLayer) : InvalidIndex; } // find by name ID - uint32 Mesh::FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const + size_t Mesh::FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const uint32 numLayers = mSharedVertexAttributes.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [nameID](const VertexAttributeLayer* layer) { - if (mSharedVertexAttributes[i]->GetNameID() == nameID) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameID() == nameID; + }); + return foundLayer != end(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), foundLayer) : InvalidIndex; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index 420bac0f33..d9c09d66bb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -171,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. @@ -179,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(). @@ -249,7 +249,7 @@ namespace EMotionFX * @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) { mSubMeshes[nr] = subMesh; } /** * Set the number of submeshes. @@ -257,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) { mSubMeshes.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. @@ -306,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. @@ -318,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. @@ -331,7 +331,7 @@ 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. @@ -346,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. @@ -373,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; @@ -389,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. @@ -410,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); //--------------------------------------------------- @@ -517,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 @@ -538,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; @@ -561,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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h index 78bdc842e9..e1caeaf5a9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h @@ -56,7 +56,7 @@ namespace EMotionFX * @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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp index 82245a505f..ee204cf298 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp @@ -28,10 +28,9 @@ namespace EMotionFX // destructor MeshDeformerStack::~MeshDeformerStack() { - const uint32 numDeformers = mDeformers.size(); - for (uint32 i = 0; i < numDeformers; ++i) + for (MeshDeformer* deformer : mDeformers) { - mDeformers[i]->Destroy(); + deformer->Destroy(); } mDeformers.clear(); @@ -58,30 +57,25 @@ namespace EMotionFX // 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.size(); - 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 : mDeformers) + { + // 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 + mMesh->ResetToOriginalData(); } + + // update the mesh deformer + deformer->Update(actorInstance, node, timeDelta); } } } @@ -90,13 +84,10 @@ 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.size(); - // iterate through the deformers and update them - for (uint32 i = 0; i < numDeformers; ++i) + for (MeshDeformer* deformer : mDeformers) { // 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) @@ -107,7 +98,7 @@ namespace EMotionFX } // update the mesh deformer - mDeformers[i]->Update(actorInstance, node, timeDelta); + deformer->Update(actorInstance, node, timeDelta); } } } @@ -134,7 +125,7 @@ namespace EMotionFX } - void MeshDeformerStack::InsertDeformer(uint32 pos, MeshDeformer* meshDeformer) + void MeshDeformerStack::InsertDeformer(size_t pos, MeshDeformer* meshDeformer) { // add the object into the stack mDeformers.emplace(AZStd::next(begin(mDeformers), pos), meshDeformer); @@ -159,10 +150,9 @@ namespace EMotionFX MeshDeformerStack* newStack = aznew MeshDeformerStack(mesh); // clone all deformers - const uint32 numDeformers = mDeformers.size(); - for (uint32 i = 0; i < numDeformers; ++i) + for (const MeshDeformer* deformer : mDeformers) { - newStack->AddDeformer(mDeformers[i]->Clone(mesh)); + newStack->AddDeformer(deformer->Clone(mesh)); } // return a pointer to the clone @@ -176,7 +166,7 @@ namespace EMotionFX } - MeshDeformer* MeshDeformerStack::GetDeformer(uint32 nr) const + MeshDeformer* MeshDeformerStack::GetDeformer(size_t nr) const { MCORE_ASSERT(nr < mDeformers.size()); return mDeformers[nr]; @@ -184,10 +174,10 @@ namespace EMotionFX // 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.size(); ) + size_t numRemoved = 0; + for (size_t a = 0; a < mDeformers.size(); ) { MeshDeformer* deformer = mDeformers[a]; if (deformer->GetType() == deformerTypeID) @@ -209,12 +199,10 @@ namespace EMotionFX // remove all the deformers void MeshDeformerStack::RemoveAllDeformers() { - for (uint32 i = 0; i < mDeformers.size(); ++i) + for (MeshDeformer* deformer : mDeformers) { // retrieve the current deformer - MeshDeformer* deformer = mDeformers[i]; - - // remove the deformer + // remove the deformer RemoveDeformer(deformer); deformer->Destroy(); } @@ -222,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.size(); - for (uint32 a = 0; a < numDeformers; ++a) + size_t numChanged = 0; + for (MeshDeformer* deformer : mDeformers) { - MeshDeformer* deformer = mDeformers[a]; - if (deformer->GetType() == deformerTypeID) + if (deformer->GetType() == deformerTypeID) { deformer->SetIsEnabled(enabled); numChanged++; @@ -243,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.size(); - for (uint32 a = 0; a < numDeformers; ++a) + return AZStd::any_of(begin(mDeformers), end(mDeformers), [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.size(); - for (uint32 a = 0; a < numDeformers; ++a) + const auto foundDeformer = AZStd::find_if(begin(mDeformers), end(mDeformers), [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(mDeformers) ? *foundDeformer : nullptr; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h index 0b1ce6fbcb..ae63a1e495 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h @@ -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). @@ -141,7 +141,7 @@ namespace EMotionFX * @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,7 +156,7 @@ 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: AZStd::vector mDeformers; /**< The stack of deformers. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp index b40ff27ce0..561e94b35b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp @@ -57,14 +57,14 @@ 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.size()); - for (uint32 i = 0; i < mDeformPasses.size(); ++i) + for (size_t i = 0; i < mDeformPasses.size(); ++i) { DeformPass& pass = result->mDeformPasses[i]; pass.mDeformDataNr = mDeformPasses[i].mDeformDataNr; @@ -85,21 +85,20 @@ 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.size(); - for (uint32 i = 0; i < numPasses; ++i) + for (DeformPass& mDeformPasse : mDeformPasses) { // find the morph target - MorphTargetStandard* morphTarget = (MorphTargetStandard*)actor->GetMorphSetup(lodLevel)->FindMorphTargetByID(mDeformPasses[i].mMorphTarget->GetID()); + MorphTargetStandard* morphTarget = (MorphTargetStandard*)actor->GetMorphSetup(lodLevel)->FindMorphTargetByID(mDeformPasse.mMorphTarget->GetID()); if (morphTarget == nullptr) { continue; } // get the deform data and number of vertices to deform - MorphTargetStandard::DeformData* deformData = morphTarget->GetDeformData(mDeformPasses[i].mDeformDataNr); + MorphTargetStandard::DeformData* deformData = morphTarget->GetDeformData(mDeformPasse.mDeformDataNr); const uint32 numDeformVerts = deformData->mNumVerts; // this mesh deformer can't work on this mesh, because the deformdata number of vertices is bigger than the @@ -121,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 && mDeformPasse.mLastNearZero) { continue; } @@ -129,11 +128,11 @@ namespace EMotionFX // update the flag if (nearZero) { - mDeformPasses[i].mLastNearZero = true; + mDeformPasse.mLastNearZero = true; } else { - mDeformPasses[i].mLastNearZero = false; // we moved away from zero influence + mDeformPasse.mLastNearZero = false; // we moved away from zero influence } // output data @@ -150,10 +149,9 @@ namespace EMotionFX 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].mVertexNr; positions [vtxNr] = positions[vtxNr] + deltas[v].mPosition.ToVector3(minValue, maxValue) * weight; normals [vtxNr] = normals[vtxNr] + deltas[v].mNormal.ToVector3(-2.0f, 2.0f) * weight; @@ -165,10 +163,9 @@ namespace EMotionFX } 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].mVertexNr; positions[vtxNr] = positions[vtxNr] + deltas[v].mPosition.ToVector3(minValue, maxValue) * weight; normals [vtxNr] = normals[vtxNr] + deltas[v].mNormal.ToVector3(-2.0f, 2.0f) * weight; @@ -180,10 +177,9 @@ namespace EMotionFX 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].mVertexNr; positions[vtxNr] = positions[vtxNr] + deltas[v].mPosition.ToVector3(minValue, maxValue) * weight; normals[vtxNr] = normals[vtxNr] + deltas[v].mNormal.ToVector3(-2.0f, 2.0f) * weight; @@ -203,15 +199,15 @@ namespace EMotionFX 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); @@ -219,7 +215,7 @@ namespace EMotionFX { // add an empty deform pass and fill it afterwards mDeformPasses.emplace_back(); - const uint32 deformPassIndex = mDeformPasses.size() - 1; + const size_t deformPassIndex = mDeformPasses.size() - 1; mDeformPasses[deformPassIndex].mDeformDataNr = j; mDeformPasses[deformPassIndex].mMorphTarget = morphTarget; } @@ -240,7 +236,7 @@ namespace EMotionFX } - void MorphMeshDeformer::ReserveDeformPasses(uint32 numPasses) + void MorphMeshDeformer::ReserveDeformPasses(size_t numPasses) { mDeformPasses.reserve(numPasses); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h index 303c379248..882d4bdfeb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h @@ -55,7 +55,7 @@ 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. */ + size_t mDeformDataNr; /**< An index inside the deform datas of the standard morph target. */ bool mLastNearZero; /**< Was the last frame's weight near zero? */ /** @@ -64,7 +64,7 @@ namespace EMotionFX */ DeformPass() : mMorphTarget(nullptr) - , mDeformDataNr(MCORE_INVALIDINDEX32) + , mDeformDataNr(InvalidIndex) , mLastNearZero(false) {} }; @@ -110,7 +110,7 @@ namespace EMotionFX * @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. @@ -129,7 +129,7 @@ namespace EMotionFX * 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: AZStd::vector mDeformPasses; /**< The deform passes. Each pass basically represents a morph target. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp index 0b27ee634e..069e7c971a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp @@ -40,7 +40,7 @@ namespace EMotionFX // remove a morph target - void MorphSetup::RemoveMorphTarget(uint32 nr, bool delFromMem) + void MorphSetup::RemoveMorphTarget(size_t nr, bool delFromMem) { if (delFromMem) { @@ -70,10 +70,9 @@ namespace EMotionFX // remove all morph targets void MorphSetup::RemoveAllMorphTargets() { - const uint32 numTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numTargets; ++i) + for (MorphTarget*& mMorphTarget : mMorphTargets) { - mMorphTargets[i]->Destroy(); + mMorphTarget->Destroy(); } mMorphTargets.clear(); @@ -83,98 +82,64 @@ namespace EMotionFX // get a morph target by ID MorphTarget* MorphSetup::FindMorphTargetByID(uint32 id) const { - // linear search, and check IDs - const uint32 numTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [id](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetID() == id) - { - return mMorphTargets[i]; - } - } - - // nothing found - return nullptr; + return morphTarget->GetID() == id; + }); + return foundMorphTarget != end(mMorphTargets) ? *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.size(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [id](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetID() == id) - { - return i; - } - } - - // nothing found - return MCORE_INVALIDINDEX32; + return morphTarget->GetID() == id; + }); + return foundMorphTarget != end(mMorphTargets) ? AZStd::distance(begin(mMorphTargets), foundMorphTarget) : InvalidIndex; } - uint32 MorphSetup::FindMorphTargetIndexByName(const char* name) const + size_t MorphSetup::FindMorphTargetIndexByName(const char* name) const { - const uint32 numTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [name](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return morphTarget->GetNameString() == name; + }); + return foundMorphTarget != end(mMorphTargets) ? AZStd::distance(begin(mMorphTargets), foundMorphTarget) : InvalidIndex; } - uint32 MorphSetup::FindMorphTargetIndexByNameNoCase(const char* name) const + size_t MorphSetup::FindMorphTargetIndexByNameNoCase(const char* name) const { - const uint32 numTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [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(mMorphTargets) ? AZStd::distance(begin(mMorphTargets), foundMorphTarget) : InvalidIndex; } // find a morph target by name (case sensitive) MorphTarget* MorphSetup::FindMorphTargetByName(const char* name) const { - const uint32 numTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [name](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetNameString() == name) - { - return mMorphTargets[i]; - } - } - - return nullptr; + return morphTarget->GetNameString() == name; + }); + return foundMorphTarget != end(mMorphTargets) ? *foundMorphTarget : nullptr; } // find a morph target by name (not case sensitive) MorphTarget* MorphSetup::FindMorphTargetByNameNoCase(const char* name) const { - const uint32 numTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [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(mMorphTargets) ? *foundMorphTarget : nullptr; } @@ -185,10 +150,9 @@ namespace EMotionFX MorphSetup* clone = MorphSetup::Create(); // clone all morph targets - const uint32 numMorphTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numMorphTargets; ++i) + for (const MorphTarget* morphTarget : mMorphTargets) { - clone->AddMorphTarget(mMorphTargets[i]->Clone()); + clone->AddMorphTarget(morphTarget->Clone()); } // return the cloned morph setup @@ -212,10 +176,9 @@ namespace EMotionFX } // scale the morph targets - const uint32 numMorphTargets = mMorphTargets.size(); - for (uint32 i = 0; i < numMorphTargets; ++i) + for (MorphTarget* mMorphTarget : mMorphTargets) { - mMorphTargets[i]->Scale(scaleFactor); + mMorphTarget->Scale(scaleFactor); } } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h index 45c55d301c..23a5789e03 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h @@ -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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp index 3bb84881ff..9ccafbb5f3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp @@ -211,7 +211,7 @@ namespace EMotionFX // 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h index 3e32229691..35e2f620ae 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h @@ -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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp index 4ee07c38f2..7612fd73d7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp @@ -82,11 +82,11 @@ namespace EMotionFX // 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,8 +96,8 @@ namespace EMotionFX } // get the node indices of both nodes - const uint32 neutralNodeIndex = neutralNode->GetNodeIndex(); - const uint32 targetNodeIndex = targetSkeleton->GetNode(i)->GetNodeIndex(); + const size_t neutralNodeIndex = neutralNode->GetNodeIndex(); + const size_t targetNodeIndex = targetSkeleton->GetNode(i)->GetNodeIndex(); // skip bones in the bone list //if (mCaptureMeshDeforms) @@ -177,21 +177,20 @@ namespace EMotionFX 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.size(); - for (uint32 i = 0; i < numTransforms; ++i) + for (const Transformation& mTransform : mTransforms) { // if this is the node that gets modified by this transform - if (mTransforms[i].mNodeIndex != nodeIndex) + if (mTransform.mNodeIndex != nodeIndex) { continue; } - position += mTransforms[i].mPosition * newWeight; - scale += mTransforms[i].mScale * newWeight; + position += mTransform.mPosition * newWeight; + scale += mTransform.mScale * 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 rot = orgRot.NLerp(mTransform.mRotation, normalizedWeight); rotation = rotation * (orgRot.GetInverseFull() * rot); rotation.Normalize(); @@ -204,27 +203,16 @@ namespace EMotionFX // check if this morph target influences the specified node or not 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(mDeformDatas), end(mDeformDatas), [nodeIndex](const DeformData* deformData) { - return true; - } - } - - // check all transforms - const uint32 numTransforms = mTransforms.size(); - for (uint32 i = 0; i < numTransforms; ++i) - { - if (mTransforms[i].mNodeIndex == nodeIndex) + return deformData->mNodeIndex == nodeIndex; + }) + || + AZStd::any_of(begin(mTransforms), end(mTransforms), [nodeIndex](const Transformation& transform) { - return true; - } - } - - // this morph target doesn't influence the given node - return false; + return transform.mNodeIndex == nodeIndex; + }); } @@ -239,27 +227,26 @@ namespace EMotionFX Transform newTransform; // calculate the new transformations for all nodes of this morph target - const uint32 numTransforms = mTransforms.size(); - for (uint32 i = 0; i < numTransforms; ++i) + for (const Transformation& transform : mTransforms) { // try to find the node - const uint32 nodeIndex = mTransforms[i].mNodeIndex; + const size_t nodeIndex = transform.mNodeIndex; // init the transform data newTransform = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex); // calc new position and scale (delta based targetTransform) - newTransform.mPosition += mTransforms[i].mPosition * newWeight; + newTransform.mPosition += transform.mPosition * newWeight; EMFX_SCALECODE ( - newTransform.mScale += mTransforms[i].mScale * newWeight; + newTransform.mScale += transform.mScale * newWeight; // newTransform.mScaleRotation.Identity(); ) // rotate additively const AZ::Quaternion& orgRot = transformData->GetBindPose()->GetLocalSpaceTransform(nodeIndex).mRotation; - const AZ::Quaternion rot = orgRot.NLerp(mTransforms[i].mRotation, normalizedWeight); + const AZ::Quaternion rot = orgRot.NLerp(transform.mRotation, normalizedWeight); newTransform.mRotation = newTransform.mRotation * (orgRot.GetInverseFull() * rot); newTransform.mRotation.Normalize(); /* @@ -282,7 +269,7 @@ namespace EMotionFX return mDeformDatas.size(); } - MorphTargetStandard::DeformData* MorphTargetStandard::GetDeformData(uint32 nr) const + MorphTargetStandard::DeformData* MorphTargetStandard::GetDeformData(size_t nr) const { return mDeformDatas[nr]; } @@ -303,14 +290,14 @@ namespace EMotionFX return mTransforms.size(); } - MorphTargetStandard::Transformation& MorphTargetStandard::GetTransformation(uint32 nr) + MorphTargetStandard::Transformation& MorphTargetStandard::GetTransformation(size_t nr) { return mTransforms[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 @@ -397,18 +384,18 @@ namespace EMotionFX } // pre-alloc memory for the deform datas - void MorphTargetStandard::ReserveDeformDatas(uint32 numDeformDatas) + void MorphTargetStandard::ReserveDeformDatas(size_t numDeformDatas) { mDeformDatas.reserve(numDeformDatas); } // pre-allocate memory for the transformations - void MorphTargetStandard::ReserveTransformations(uint32 numTransforms) + void MorphTargetStandard::ReserveTransformations(size_t numTransforms) { mTransforms.reserve(numTransforms); } - void MorphTargetStandard::RemoveDeformData(uint32 index, bool delFromMem) + void MorphTargetStandard::RemoveDeformData(size_t index, bool delFromMem) { if (delFromMem) { @@ -418,7 +405,7 @@ namespace EMotionFX } - void MorphTargetStandard::RemoveTransformation(uint32 index) + void MorphTargetStandard::RemoveTransformation(size_t index) { mTransforms.erase(AZStd::next(begin(mTransforms), index)); } @@ -434,11 +421,9 @@ namespace EMotionFX } // scale the transformations - const uint32 numTransformations = mTransforms.size(); - for (uint32 i = 0; i < numTransformations; ++i) + for (Transformation& transform : mTransforms) { - Transformation& transform = mTransforms[i]; - transform.mPosition *= scaleFactor; + transform.mPosition *= scaleFactor; } // scale the deform datas (packed per vertex morph deltas) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h index d519e98f57..2ea1c43906 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h @@ -104,7 +104,7 @@ namespace EMotionFX 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. */ + size_t mNodeIndex; /**< The node number to apply this on. */ } MCORE_ALIGN_POST(16); @@ -182,7 +182,7 @@ namespace EMotionFX * @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. @@ -207,13 +207,13 @@ namespace EMotionFX * @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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp index c10740acb5..382a640e65 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp @@ -30,7 +30,7 @@ namespace EMotionFX Motion::Motion(const char* name) : BaseObject() { - mID = MCore::GetIDGenerator().GenerateID(); + mID = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); m_eventTable = AZStd::make_unique(); mUnitType = GetEMotionFX().GetUnitType(); mFileUnitType = mUnitType; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp index 5f394fb791..7421495c60 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; }); } @@ -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,13 +466,13 @@ 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(); if (AZ::GetAbs(subMotionHeight) >= AZ::Constants::FloatEpsilon) @@ -484,8 +484,8 @@ namespace EMotionFX } } - 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; 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..619a962d7e 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,7 +89,7 @@ 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; @@ -141,16 +141,16 @@ 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; @@ -161,7 +161,7 @@ namespace EMotionFX } 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); 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..44ed629756 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.cpp @@ -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,7 +152,7 @@ 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]; @@ -208,20 +208,20 @@ 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]; @@ -234,7 +234,7 @@ namespace EMotionFX } 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); 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/MotionInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp index 292aef9d54..3cefe9e513 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); @@ -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 AZStd::vector& 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.size() - 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 @@ -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(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h index d0f2d1d3fb..59bd08d248 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h @@ -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; //-------------------------------- @@ -821,7 +821,7 @@ namespace EMotionFX void CalcRelativeTransform(Node* rootNode, float curTime, float oldTime, Transform* outTransform) const; bool ExtractMotion(Transform& outTrajectoryDelta); - void CalcGlobalTransform(const AZStd::vector& 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."); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp index f2abc5f5de..d31d81fe7a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp @@ -65,10 +65,9 @@ namespace EMotionFX MCORE_ASSERT(mData == nullptr); // delete all subpools - const uint32 numSubPools = mSubPools.size(); - for (uint32 s = 0; s < numSubPools; ++s) + for (SubPool* mSubPool : mSubPools) { - delete mSubPools[s]; + delete mSubPool; } mSubPools.clear(); @@ -114,7 +113,7 @@ 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) { @@ -141,7 +140,7 @@ namespace EMotionFX { mPool->mData = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space mPool->mFreeList.resize_no_construct(numInitialInstances); - for (uint32 i = 0; i < numInitialInstances; ++i) + for (size_t i = 0; i < numInitialInstances; ++i) { void* memLocation = (void*)(mPool->mData + i * sizeof(MotionInstance)); mPool->mFreeList[i].mAddress = memLocation; @@ -158,7 +157,7 @@ namespace EMotionFX subPool->mNumInstances = numInitialInstances; mPool->mFreeList.resize_no_construct(numInitialInstances); - for (uint32 i = 0; i < numInitialInstances; ++i) + for (size_t i = 0; i < numInitialInstances; ++i) { mPool->mFreeList[i].mAddress = (void*)(subPool->mData + i * sizeof(MotionInstance)); mPool->mFreeList[i].mSubPool = subPool; @@ -203,14 +202,14 @@ namespace EMotionFX // we have no more free attributes left if (mPool->mPoolType == POOLTYPE_DYNAMIC) // we're dynamic, so we can just create new ones { - const uint32 numInstances = mPool->mSubPoolSize; + const size_t numInstances = mPool->mSubPoolSize; mPool->mNumInstances += numInstances; SubPool* subPool = new SubPool(); subPool->mData = (uint8*)MCore::Allocate(numInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space subPool->mNumInstances = numInstances; - const uint32 startIndex = mPool->mFreeList.size(); + const size_t startIndex = mPool->mFreeList.size(); //mPool->mFreeList.Reserve( numInstances * 2 ); if (mPool->mFreeList.capacity() < mPool->mNumInstances) { @@ -218,7 +217,7 @@ namespace EMotionFX } mPool->mFreeList.resize_no_construct(startIndex + numInstances); - for (uint32 i = 0; i < numInstances; ++i) + for (size_t i = 0; i < numInstances; ++i) { void* memAddress = (void*)(subPool->mData + i * sizeof(MotionInstance)); mPool->mFreeList[i + startIndex].mAddress = memAddress; @@ -290,12 +289,12 @@ namespace EMotionFX Lock(); MCore::LogInfo("EMotionFX::MotionInstancePool::LogMemoryStats() - Logging motion instance pool info"); - const uint32 numFree = mPool->mFreeList.size(); - uint32 numUsed = mPool->mNumUsedInstances; - uint32 memUsage = 0; - uint32 usedMemUsage = 0; - uint32 totalMemUsage = 0; - uint32 totalUsedInstancesMemUsage = 0; + const size_t numFree = mPool->mFreeList.size(); + size_t numUsed = mPool->mNumUsedInstances; + size_t memUsage = 0; + size_t usedMemUsage = 0; + size_t totalMemUsage = 0; + size_t totalUsedInstancesMemUsage = 0; if (mPool->mPoolType == POOLTYPE_STATIC) { @@ -375,13 +374,13 @@ namespace EMotionFX { Lock(); - for (uint32 i = 0; i < mPool->mSubPools.size(); ) + for (size_t i = 0; i < mPool->mSubPools.size(); ) { SubPool* subPool = mPool->mSubPools[i]; if (subPool->mNumInUse == 0) { // remove all free allocations - for (uint32 a = 0; a < mPool->mFreeList.size(); ) + for (size_t a = 0; a < mPool->mFreeList.size(); ) { if (mPool->mFreeList[a].mSubPool == subPool) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h index 8cb675bb08..e257640e33 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h @@ -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); @@ -69,8 +69,8 @@ namespace EMotionFX ~SubPool(); uint8* mData; - uint32 mNumInstances; - uint32 mNumInUse; + size_t mNumInstances; + size_t mNumInUse; }; struct EMFX_API MemLocation @@ -88,9 +88,9 @@ namespace EMotionFX ~Pool(); uint8* mData; - uint32 mNumInstances; - uint32 mNumUsedInstances; - uint32 mSubPoolSize; + size_t mNumInstances; + size_t mNumUsedInstances; + size_t mSubPoolSize; AZStd::vector mFreeList; AZStd::vector mSubPools; EPoolType mPoolType; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp index 9cda792890..4c3ba95e59 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 @@ -48,12 +49,11 @@ namespace EMotionFX void MotionLayerSystem::RemoveAllLayerPasses(bool delFromMem) { // delete all layer passes - const uint32 numLayerPasses = mLayerPasses.size(); - for (uint32 i = 0; i < numLayerPasses; ++i) + for (LayerPass* mLayerPasse : mLayerPasses) { if (delFromMem) { - mLayerPasses[i]->Destroy(); + mLayerPasse->Destroy(); } } @@ -65,12 +65,12 @@ namespace EMotionFX void MotionLayerSystem::StartMotion(MotionInstance* motion, PlayBackInfo* info) { // check if we have any motions playing already - const uint32 numMotionInstances = mMotionInstances.size(); + const size_t numMotionInstances = mMotionInstances.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.emplace(AZStd::next(begin(mMotionInstances), insertPos), motion); } @@ -97,18 +97,13 @@ namespace EMotionFX // 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.size(); - for (uint32 i = 0; i < numInstances; ++i) + const auto* foundInsertPosition = AZStd::lower_bound(begin(mMotionInstances), end(mMotionInstances), priorityLevel, [](const MotionInstance* motionInstance, size_t level) { - if (mMotionInstances[i]->GetPriorityLevel() <= priorityLevel) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motionInstance->GetPriorityLevel() < level; + }); + return foundInsertPosition != end(mMotionInstances) ? AZStd::distance(begin(mMotionInstances), foundInsertPosition) : InvalidIndex; } @@ -125,10 +120,9 @@ namespace EMotionFX mMotionQueue->Update(); // process all layer passes - const uint32 numPasses = mLayerPasses.size(); - for (uint32 i = 0; i < numPasses; ++i) + for (LayerPass* mLayerPasse : mLayerPasses) { - mLayerPasses[i]->Process(); + mLayerPasse->Process(); } // process the repositioning as last @@ -151,7 +145,7 @@ namespace EMotionFX // update the motion tree void MotionLayerSystem::UpdateMotionTree() { - for (uint32 i = 0; i < mMotionInstances.size(); ++i) + for (size_t i = 0; i < mMotionInstances.size(); ++i) { MotionInstance* source = mMotionInstances[i]; @@ -233,8 +227,8 @@ namespace EMotionFX if (source->GetCanOverwrite()) { // remove all motions that got overwritten by the current one - const uint32 numToRemove = mMotionInstances.size() - (i + 1); - for (uint32 a = 0; a < numToRemove; ++a) + const size_t numToRemove = mMotionInstances.size() - (i + 1); + for (size_t a = 0; a < numToRemove; ++a) { RemoveMotionInstance(mMotionInstances[i + 1]); } @@ -246,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.size() - 1; i != MCORE_INVALIDINDEX32;) + for (auto iter = rbegin(mMotionInstances); iter != rend(mMotionInstances); ++iter) { - MotionInstance* curInstance = mMotionInstances[i]; + MotionInstance* curInstance = *iter; // if we reached the current motion instance we are done if (curInstance == source) @@ -263,7 +257,6 @@ namespace EMotionFX numRemoved++; RemoveMotionInstance(curInstance); - i--; } return numRemoved; @@ -274,21 +267,11 @@ namespace EMotionFX MotionInstance* MotionLayerSystem::FindFirstNonMixingMotionInstance() const { // if there aren't any motion instances, return nullptr - const uint32 numInstances = mMotionInstances.size(); - if (numInstances == 0) + const auto foundMotionInstance = AZStd::find_if(begin(mMotionInstances), end(mMotionInstances), [](const MotionInstance* motionInstance) { - return nullptr; - } - - for (uint32 i = 0; i < numInstances; ++i) - { - if (mMotionInstances[i]->GetIsMixing() == false) - { - return mMotionInstances[i]; - } - } - - return nullptr; + return !motionInstance->GetIsMixing(); + }); + return foundMotionInstance != end(mMotionInstances) ? *foundMotionInstance : nullptr; } @@ -304,7 +287,7 @@ namespace EMotionFX Pose* tempActorPose = &tempAnimGraphPose->GetPose(); - const uint32 numMotionInstances = mMotionInstances.size(); + const size_t numMotionInstances = mMotionInstances.size(); if (numMotionInstances > 0) { if (numMotionInstances > 1) @@ -314,10 +297,10 @@ namespace EMotionFX finalPose->InitFromBindPose(mActorInstance); // blend the layers - for (uint32 i = numMotionInstances - 1; i != MCORE_INVALIDINDEX32; --i) + for (auto iter = rbegin(mMotionInstances); iter != rend(mMotionInstances); ++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; @@ -406,7 +389,7 @@ namespace EMotionFX // remove a given pass - void MotionLayerSystem::RemoveLayerPass(uint32 nr, bool delFromMem) + void MotionLayerSystem::RemoveLayerPass(size_t nr, bool delFromMem) { if (delFromMem) { @@ -433,7 +416,7 @@ 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.emplace(AZStd::next(begin(mLayerPasses), insertPos), pass); } @@ -465,7 +448,7 @@ namespace EMotionFX } - LayerPass* MotionLayerSystem::GetLayerPass(uint32 index) const + LayerPass* MotionLayerSystem::GetLayerPass(size_t index) const { return mLayerPasses[index]; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h index e207f48fd5..be14780341 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. @@ -147,7 +147,7 @@ namespace EMotionFX * @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,7 +175,7 @@ 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: diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp index b193c58175..1954d23dc3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp @@ -95,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.size(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [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(mMotions) ? *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.size(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [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(mMotions) ? *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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [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(mMotionSets) ? *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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [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(mMotionSets) ? *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.size(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [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(mMotions) ? AZStd::distance(begin(mMotions), 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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [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(mMotionSets) ? AZStd::distance(begin(mMotionSets), 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.size(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [id](const Motion* motion) { - if (mMotions[i]->GetID() == id) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motion->GetID() == id; + }); + return foundMotion != end(mMotions) ? AZStd::distance(begin(mMotions), 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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [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(mMotionSets) ? AZStd::distance(begin(mMotionSets), 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.size(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [id](const Motion* motion) { - if (mMotions[i]->GetID() == id) - { - return mMotions[i]; - } - } - - return nullptr; + return motion->GetID() == id; + }); + return foundMotion != end(mMotions) ? *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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [id](const MotionSet* motionSet) { - if (mMotionSets[i]->GetID() == id) - { - return mMotionSets[i]; - } - } - - return nullptr; + return motionSet->GetID() == id; + }); + return foundMotionSet != end(mMotionSets) ? *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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [motionSet](const MotionSet* ms) { - if (mMotionSets[i] == motionSet) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return ms == motionSet; + }); + return foundMotionSet != end(mMotionSets) ? AZStd::distance(begin(mMotionSets), 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.size(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [motion](const Motion* m) { - // compare the motions - if (motion == mMotions[i]) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return m == motion; + }); + return foundMotion != end(mMotions) ? AZStd::distance(begin(mMotions), foundMotion) : InvalidIndex; } @@ -380,25 +272,13 @@ namespace EMotionFX // 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.size(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [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(mMotions) ? AZStd::distance(begin(mMotions), foundMotion) : InvalidIndex; } @@ -419,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())); @@ -453,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]; // 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); @@ -491,11 +370,8 @@ namespace EMotionFX } // Reset all motion entries in the motion sets of the current motion. - const uint32 numMotionSets = mMotionSets.size(); - for (i = 0; i < numMotionSets; ++i) + for (const MotionSet* motionSet : mMotionSets) { - MotionSet* motionSet = mMotionSets[i]; - const EMotionFX::MotionSet::MotionEntries& motionEntries = motionSet->GetMotionEntries(); for (const auto& item : motionEntries) { @@ -509,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); @@ -542,9 +418,9 @@ namespace EMotionFX // 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; } @@ -598,16 +474,15 @@ namespace EMotionFX // 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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + for (const MotionSet* mMotionSet : mMotionSets) { // sum up the root motion sets - if (mMotionSets[i]->GetParentSet() == nullptr) + if (mMotionSet->GetParentSet() == nullptr) { result++; } @@ -618,32 +493,13 @@ 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.size(); - for (uint32 i = 0; i < numMotionSets; ++i) + auto foundRootMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [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(mMotionSets) ? *foundRootMotionSet : nullptr; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h index 98555da9f7..2aad2f72d9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h @@ -44,7 +44,7 @@ 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 mMotions[index]; } /** * Get the number of motions in 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,7 +154,7 @@ 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 mMotionSets[index]; } /** * Get the number of motion sets in the motion manager. @@ -167,14 +167,14 @@ namespace EMotionFX * 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); @@ -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 ea8826fe9a..10b52b1f8b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp @@ -46,7 +46,7 @@ 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) { @@ -61,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) @@ -199,7 +199,7 @@ namespace EMotionFX } - MotionQueue::QueueEntry& MotionQueue::GetEntry(uint32 nr) + MotionQueue::QueueEntry& MotionQueue::GetEntry(size_t nr) { return mEntries[nr]; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h index 9978a16bc6..aa30ccab46 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h @@ -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. 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 fcd243c95f..7619187d23 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp @@ -45,7 +45,7 @@ namespace EMotionFX GetEventManager().OnDeleteMotionSystem(this); // delete the motion infos - while (mMotionInstances.size()) + while (!mMotionInstances.empty()) { //delete mMotionInstances.GetLast(); GetMotionInstancePool().Free(mMotionInstances.back()); @@ -173,10 +173,9 @@ namespace EMotionFX // stop all the motions that are currently playing void MotionSystem::StopAllMotions() { - const uint32 numInstances = mMotionInstances.size(); - for (uint32 i = 0; i < numInstances; ++i) + for (MotionInstance* motionInstance : mMotionInstances) { - mMotionInstances[i]->Stop(); + motionInstance->Stop(); } } @@ -184,12 +183,11 @@ namespace EMotionFX // stop all motion instances of a given motion void MotionSystem::StopAllMotions(Motion* motion) { - const uint32 numInstances = mMotionInstances.size(); - for (uint32 i = 0; i < numInstances; ++i) + for (MotionInstance* motionInstance : mMotionInstances) { - if (mMotionInstances[i]->GetMotion()->GetID() == motion->GetID()) + if (motionInstance->GetMotion()->GetID() == motion->GetID()) { - mMotionInstances[i]->Stop(); + motionInstance->Stop(); } } } @@ -230,10 +228,9 @@ namespace EMotionFX void MotionSystem::UpdateMotionInstances(float timePassed) { // update all the motion infos - const uint32 numInstances = mMotionInstances.size(); - for (uint32 i = 0; i < numInstances; ++i) + for (MotionInstance* motionInstance : mMotionInstances) { - mMotionInstances[i]->Update(timePassed); + motionInstance->Update(timePassed); } } @@ -241,64 +238,26 @@ 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 false; - } - - // for all motion instances currently playing in this actor - const uint32 numInstances = mMotionInstances.size(); - for (uint32 i = 0; i < numInstances; ++i) + return instance && AZStd::any_of(begin(mMotionInstances), end(mMotionInstances), [instance](const MotionInstance* motionInstance) { - // 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(mMotionInstances), end(mMotionInstances), [motion, ignorePausedMotions](const MotionInstance* motionInstance) { - return false; - } - - // for all motion instances currently playing in this actor - const uint32 numInstances = mMotionInstances.size(); - 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.size()); return mMotionInstances[nr]; @@ -330,7 +289,7 @@ 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)); } @@ -362,6 +321,6 @@ namespace EMotionFX bool MotionSystem::GetIsPlaying() const { - return (mMotionInstances.size() > 0); + return !mMotionInstances.empty(); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h index dd7ba26170..109cf5d41f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h @@ -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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp index bd339ecb36..3cc4d027a8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp @@ -78,10 +78,10 @@ namespace EMotionFX void MultiThreadScheduler::Print() { // for all steps - const uint32 numSteps = mSteps.size(); - for (uint32 i = 0; i < numSteps; ++i) + const size_t numSteps = mSteps.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, mSteps[i].mActorInstances.size()); } AZ_Printf("EMotionFX", "---------"); @@ -91,14 +91,13 @@ namespace EMotionFX void MultiThreadScheduler::RemoveEmptySteps() { // process all steps - for (uint32 s = 0; s < mSteps.size(); ) + for (size_t s = 0; s < mSteps.size(); ) { - // if the step isn't empty - if (mSteps[s].mActorInstances.size() > 0) + if (!mSteps[s].mActorInstances.empty()) { s++; } - else // otherwise remove it + else { mSteps.erase(AZStd::next(begin(mSteps), s)); } @@ -111,7 +110,7 @@ namespace EMotionFX { MCore::LockGuardRecursive guard(mMutex); - uint32 numSteps = mSteps.size(); + size_t numSteps = mSteps.size(); if (numSteps == 0) { return; @@ -130,8 +129,8 @@ namespace EMotionFX // 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) @@ -147,22 +146,17 @@ namespace EMotionFX mNumVisible.SetValue(0); mNumSampled.SetValue(0); - for (uint32 s = 0; s < numSteps; ++s) + for (const ScheduleStep& currentStep : mSteps) { - const ScheduleStep& currentStep = mSteps[s]; - - // skip empty steps - const size_t numStepEntries = currentStep.mActorInstances.size(); - if (numStepEntries == 0) + if (currentStep.mActorInstances.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.mActorInstances) { - ActorInstance* actorInstance = currentStep.mActorInstances[c]; if (actorInstance->GetIsEnabled() == false) { continue; @@ -212,11 +206,11 @@ 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.size(); - for (uint32 s = startStep; s < numSteps; ++s) + const size_t numSteps = mSteps.size(); + for (size_t s = startStep; s < numSteps; ++s) { // if there is a conflicting dependency, skip this step if (CheckIfHasMatchingDependency(actorInstance, &mSteps[s])) @@ -235,8 +229,8 @@ namespace EMotionFX bool MultiThreadScheduler::HasActorInstanceInSteps(const ActorInstance* actorInstance) const { - const uint32 numSteps = mSteps.size(); - for (uint32 s = 0; s < numSteps; ++s) + const size_t numSteps = mSteps.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()) @@ -248,13 +242,13 @@ namespace EMotionFX return false; } - void MultiThreadScheduler::RecursiveInsertActorInstance(ActorInstance* instance, uint32 startStep) + void MultiThreadScheduler::RecursiveInsertActorInstance(ActorInstance* instance, size_t startStep) { MCore::LockGuardRecursive guard(mMutex); 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); @@ -279,8 +273,8 @@ namespace EMotionFX AddDependenciesToStep(instance, &mSteps[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) @@ -292,13 +286,13 @@ 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); // for all scheduler steps, starting from the specified start step number - const uint32 numSteps = mSteps.size(); - for (uint32 s = startStep; s < numSteps; ++s) + const size_t numSteps = mSteps.size(); + for (size_t s = startStep; s < numSteps; ++s) { ScheduleStep& step = mSteps[s]; @@ -330,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); // 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) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h index 4deebae866..6d5a7251e5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h @@ -99,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. @@ -114,12 +114,12 @@ 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]; } + const ScheduleStep& GetScheduleStep(size_t index) const { return mSteps[index]; } size_t GetNumScheduleSteps() const { return mSteps.size(); } protected: @@ -156,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 8f14fcc2b1..1144cc3f42 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp @@ -24,7 +24,7 @@ namespace EMotionFX mNodeIndex = InvalidIndex; // 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 = InvalidIndex; + mSemanticNameID = InvalidIndex32; mNodeFlags = FLAG_INCLUDEINBOUNDSCALC; if (name) @@ -33,12 +33,12 @@ namespace EMotionFX } else { - mNameID = InvalidIndex; + mNameID = InvalidIndex32; } } - Node::Node(size_t nameID, Skeleton* skeleton) + Node::Node(uint32 nameID, Skeleton* skeleton) : BaseObject() { mParentIndex = InvalidIndex; @@ -46,7 +46,7 @@ namespace EMotionFX 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 = InvalidIndex; + mSemanticNameID = InvalidIndex32; mNodeFlags = FLAG_INCLUDEINBOUNDSCALC; } @@ -69,7 +69,7 @@ namespace EMotionFX // create a node - Node* Node::Create(size_t nameID, Skeleton* skeleton) + Node* Node::Create(uint32 nameID, Skeleton* skeleton) { return aznew Node(nameID, skeleton); } @@ -235,7 +235,7 @@ namespace EMotionFX } else { - mNameID = InvalidIndex; + mNameID = InvalidIndex32; } } @@ -249,7 +249,7 @@ namespace EMotionFX } else { - mSemanticNameID = InvalidIndex; + mSemanticNameID = InvalidIndex32; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h index 9aa01201d2..19d9f53ff8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h @@ -70,7 +70,7 @@ namespace EMotionFX * @param nameID The name ID, generated using the MCore::GetStringIdPool(). * @param skeleton The skeleton where this node will belong to, you still need to manually add it to the skeleton though. */ - static Node* Create(size_t nameID, Skeleton* skeleton); + static Node* Create(uint32 nameID, Skeleton* skeleton); /** * Clone the node. @@ -155,14 +155,14 @@ namespace EMotionFX * same ID number. * @result The node ID number, which can be used for fast compares between nodes. */ - MCORE_INLINE size_t GetID() const { return mNameID; } + MCORE_INLINE uint32 GetID() const { return mNameID; } /** * Get the semantic name ID. * To get the name you can also use GetSemanticName() and GetSemanticNameString(). * @result The semantic name ID. */ - MCORE_INLINE size_t GetSemanticID() const { return mSemanticNameID; } + MCORE_INLINE uint32 GetSemanticID() const { return mSemanticNameID; } /** * Get the number of child nodes attached to this node. @@ -418,8 +418,8 @@ namespace EMotionFX size_t mNodeIndex; /**< The node index, which is the index into the array of nodes inside the Skeleton class. */ size_t mParentIndex; /**< The parent node index, or MCORE_INVALIDINDEX32 when there is no parent. */ size_t mSkeletalLODs; /**< The skeletal LOD status values. Each bit represents if this node is enabled or disabled in the given LOD. */ - size_t mNameID; /**< The ID, which is generated from the name. You can use this for fast compares between nodes. */ - size_t mSemanticNameID; /**< The semantic name ID, for example "LeftHand" or "RightFoot" or so, this can be used for retargeting. */ + 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. */ AZStd::vector mChildIndices; /**< The indices that point to the child nodes. */ AZStd::vector mAttributes; /**< The node attributes. */ @@ -437,7 +437,7 @@ namespace EMotionFX * @param nameID The name ID, generated using the MCore::GetStringIdPool(). * @param skeleton The skeleton where this node will belong to. */ - Node(size_t nameID, Skeleton* skeleton); + Node(uint32 nameID, Skeleton* skeleton); /** * The destructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp index e22ad5f064..cd2139ec9a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp @@ -68,7 +68,7 @@ namespace EMotionFX // get the node number of a given index - uint16 NodeGroup::GetNode(uint16 index) + uint16 NodeGroup::GetNode(uint16 index) const { return mNodes[index]; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h index dfe876c86a..b3e82e648b 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp index e708d255d3..fb2fbd9ed7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp @@ -127,7 +127,7 @@ namespace EMotionFX // remove a given entry by its name ID - void NodeMap::RemoveEntryByNameID(size_t firstNameID) + void NodeMap::RemoveEntryByNameID(uint32 firstNameID) { const size_t entryIndex = FindEntryIndexByNameID(firstNameID); if (entryIndex == InvalidIndex) @@ -373,7 +373,7 @@ namespace EMotionFX // find an entry index by its name ID - size_t NodeMap::FindEntryIndexByNameID(size_t firstNameID) const + size_t NodeMap::FindEntryIndexByNameID(uint32 firstNameID) const { const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [firstNameID](const MapEntry& entry) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h index ae66a243bb..3fe2c94386 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h @@ -39,8 +39,8 @@ namespace EMotionFX public: struct MapEntry { - size_t mFirstNameID = InvalidIndex; /**< The first name ID, which is the primary key in the map. */ - size_t mSecondNameID = InvalidIndex; /**< The second name ID. */ + uint32 mFirstNameID = InvalidIndex32; /**< The first name ID, which is the primary key in the map. */ + uint32 mSecondNameID = InvalidIndex32; /**< The second name ID. */ }; static NodeMap* Create(); @@ -57,7 +57,7 @@ namespace EMotionFX const AZStd::string& GetSecondNameString(size_t entryIndex) const; bool GetHasEntry(const char* firstName) const; size_t FindEntryIndexByName(const char* firstName) const; - size_t FindEntryIndexByNameID(size_t firstNameID) const; + size_t FindEntryIndexByNameID(uint32 firstNameID) const; const char* FindSecondName(const char* firstName) const; void FindSecondName(const char* firstName, AZStd::string* outString); @@ -69,7 +69,7 @@ namespace EMotionFX void SetEntry(const char* firstName, const char* secondName, bool addIfNotExists); void RemoveEntryByIndex(size_t entryIndex); void RemoveEntryByName(const char* firstName); - void RemoveEntryByNameID(size_t firstNameID); + void RemoveEntryByNameID(uint32 firstNameID); // filename void SetFileName(const char* fileName); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp index 0b799bcb1b..dbe57cdd34 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,9 +504,9 @@ 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp index 096b32b041..b9f223eded 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp @@ -1424,7 +1424,7 @@ namespace EMotionFX const Actor* actor = mActorInstance->GetActor(); const TransformData* transformData = mActorInstance->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); Pose& unmirroredPose = tempPose->GetPose(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp index 5ef490cd2c..e5c3aa7d8c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp @@ -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 93d4cd19d1..87221c0bd2 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); @@ -72,7 +72,7 @@ namespace EMotionFX } // 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) @@ -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,7 +330,7 @@ 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; @@ -357,7 +357,7 @@ namespace EMotionFX 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]; @@ -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); 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 923c74aa02..3eb32f24ce 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp @@ -231,9 +231,9 @@ namespace EMotionFX // Add all actor instances if we did not specify them explicitly. if (mRecordSettings.m_actorInstances.empty()) { - const uint32 numActorInstances = GetActorManager().GetNumActorInstances(); + const size_t numActorInstances = GetActorManager().GetNumActorInstances(); mRecordSettings.m_actorInstances.resize(numActorInstances); - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { ActorInstance* actorInstance = GetActorManager().GetActorInstance(i); mRecordSettings.m_actorInstances[i] = actorInstance; @@ -324,9 +324,9 @@ namespace EMotionFX if (mRecordSettings.mRecordTransforms) { // 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); @@ -344,9 +344,9 @@ namespace EMotionFX // if recording morph targets, resize the morphs array if (mRecordSettings.mRecordMorphs) { - const uint32 numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); + const size_t numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); actorInstanceData.mMorphTracks.resize(numMorphs); - for (uint32 m = 0; m < numMorphs; ++m) + for (size_t m = 0; m < numMorphs; ++m) { actorInstanceData.mMorphTracks[m].Reserve(256); } @@ -387,8 +387,8 @@ namespace EMotionFX 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(); @@ -470,14 +470,14 @@ 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; - 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()); @@ -513,8 +513,8 @@ namespace EMotionFX 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); @@ -548,9 +548,9 @@ namespace EMotionFX // add a new frame AZStd::vector& frames = animGraphInstanceData.mFrames; - if (frames.size() > 0) + if (!frames.empty()) { - const uint32 byteOffset = frames.back().mByteOffset + frames.back().mNumBytes; + const size_t byteOffset = frames.back().mByteOffset + frames.back().mNumBytes; frames.emplace_back(); frames.back().mByteOffset = byteOffset; frames.back().mNumBytes = 0; @@ -567,9 +567,9 @@ namespace EMotionFX currentFrame.mTimeValue = mRecordTime; // save the parameter values - const uint32 numParams = static_cast(animGraphInstance->GetAnimGraph()->GetNumValueParameters()); + const size_t numParams = animGraphInstance->GetAnimGraph()->GetNumValueParameters(); currentFrame.mParameterValues.resize(numParams); - for (uint32 p = 0; p < numParams; ++p) + for (size_t p = 0; p < numParams; ++p) { currentFrame.mParameterValues[p] = AZStd::unique_ptr(animGraphInstance->GetParameterValue(p)->Clone()); } @@ -595,7 +595,7 @@ namespace EMotionFX { // get the current frame's data pointer AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames.back(); - const uint32 frameOffset = currentFrame.mByteOffset; + const size_t frameOffset = currentFrame.mByteOffset; // prepare the objects array mObjects.clear(); @@ -605,14 +605,14 @@ namespace EMotionFX object->RecursiveCollectObjects(mObjects); // resize the object infos array - const uint32 numObjects = mObjects.size(); + const size_t numObjects = mObjects.size(); currentFrame.mObjectInfos.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 : mObjects) { - 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 @@ -623,7 +623,7 @@ namespace EMotionFX uint8* dataPointer = &animGraphInstanceData.mDataBuffer[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]; @@ -631,7 +631,7 @@ namespace EMotionFX currentFrame.mObjectInfos[i].mFrameByteOffset = currentFrame.mNumBytes; // 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; @@ -646,7 +646,7 @@ namespace EMotionFX // 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) @@ -655,7 +655,7 @@ namespace EMotionFX } // we need to reallocate to grow the buffer - const uint32 newNumBytes = animGraphInstanceData.mDataBufferSize + (numBytes - animGraphInstanceData.mDataBufferSize) * 100; // allocate 100 frames ahead + const size_t newNumBytes = animGraphInstanceData.mDataBufferSize + (numBytes - animGraphInstanceData.mDataBufferSize) * 100; // allocate 100 frames ahead void* newBuffer = MCore::Realloc(animGraphInstanceData.mDataBuffer, newNumBytes, EMFX_MEMCATEGORY_RECORDER); MCORE_ASSERT(newBuffer); if (newBuffer) @@ -770,15 +770,14 @@ namespace EMotionFX 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.size(); + const size_t numMorphs = actorInstanceData.mMorphTracks.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); } } } @@ -811,8 +810,8 @@ namespace EMotionFX // 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]; @@ -837,8 +836,8 @@ 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; } @@ -847,18 +846,18 @@ namespace EMotionFX AnimGraphInstance* animGraphInstance = animGraphInstanceData.mAnimGraphInstance; // get the real frame number (clamped) - const uint32 realFrameNumber = MCore::Min(frameNumber, animGraphInstanceData.mFrames.size() - 1); + const size_t realFrameNumber = AZStd::min(frameNumber, animGraphInstanceData.mFrames.size() - 1); const AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames[realFrameNumber]; // get the data and objects buffers - const uint32 byteOffset = currentFrame.mByteOffset; + const size_t byteOffset = currentFrame.mByteOffset; const uint8* frameDataBuffer = &animGraphInstanceData.mDataBuffer[byteOffset]; const AZStd::vector& frameObjects = currentFrame.mObjectInfos; // first lets update all parameter values MCORE_ASSERT(currentFrame.mParameterValues.size() == animGraphInstance->GetAnimGraph()->GetNumParameters()); - const uint32 numParameters = currentFrame.mParameterValues.size(); - for (uint32 p = 0; p < numParameters; ++p) + const size_t numParameters = currentFrame.mParameterValues.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()); @@ -866,12 +865,12 @@ namespace EMotionFX } // process all objects for this frame - uint32 totalBytesRead = 0; - const uint32 numObjects = frameObjects.size(); - 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.mObject->LoadUniqueData(animGraphInstance, &frameDataBuffer[objectInfo.mFrameByteOffset]); totalBytesRead += numBytesRead; } @@ -885,19 +884,13 @@ namespace EMotionFX != mRecordSettings.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->mActorInstance == actorInstance; + }); + return found != end(m_actorInstanceDatas) ? AZStd::distance(begin(m_actorInstanceDatas), found) : InvalidIndex; } void Recorder::UpdateNodeHistoryItems() @@ -919,29 +912,21 @@ namespace EMotionFX AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; // finalize items - const size_t numActiveNodes = mActiveNodes.size(); - const uint32 numHistoryItems = historyItems.size(); - for (uint32 h = 0; h < numHistoryItems; ++h) + for (NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[h]; if (curItem->mIsFinalized) { continue; } // check if we have an active node for the given item - size_t index = InvalidIndex; - for (size_t x = 0; x < numActiveNodes; ++x) + const bool haveActiveNode = AZStd::find_if(begin(mActiveNodes), end(mActiveNodes), [curItem](const AnimGraphNode* activeNode) { - if (mActiveNodes[x]->GetId() == curItem->mNodeId) - { - index = x; - break; - } - } + return activeNode->GetId() == curItem->mNodeId; + }) != end(mActiveNodes); // the node got deactivated, finalize the item - if (index == InvalidIndex) + if (haveActiveNode) { curItem->mGlobalWeights.Optimize(0.0001f); curItem->mLocalWeights.Optimize(0.0001f); @@ -953,9 +938,8 @@ namespace EMotionFX } // iterate over all active nodes - for (size_t i = 0; i < numActiveNodes; ++i) + for (const AnimGraphNode* activeNode : mActiveNodes) { - AnimGraphNode* activeNode = mActiveNodes[i]; if (activeNode == animGraphInstance->GetRootNode()) // skip the root node { continue; @@ -1013,7 +997,7 @@ namespace EMotionFX // 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) { @@ -1050,13 +1034,11 @@ namespace EMotionFX // 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 AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[i]; if (curItem->mNodeId == node->GetId() && curItem->mStartTime <= recordTime && curItem->mIsFinalized == false) { return curItem; @@ -1073,21 +1055,19 @@ 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 AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.size(); 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->mTrackIndex != trackIndex) { continue; } @@ -1108,12 +1088,6 @@ namespace EMotionFX 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 { @@ -1140,14 +1114,12 @@ 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; + size_t result = 0; const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (const NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[i]; if (curItem->mTrackIndex > result) { result = curItem->mTrackIndex; @@ -1159,14 +1131,12 @@ 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; + size_t result = 0; const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (const EventHistoryItem* curItem : historyItems) { - EventHistoryItem* curItem = historyItems[i]; if (curItem->mTrackIndex > result) { result = curItem->mTrackIndex; @@ -1178,14 +1148,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; @@ -1212,16 +1182,15 @@ namespace EMotionFX const AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; // finalize all items - const uint32 numItems = historyItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (NodeHistoryItem* historyItem : historyItems) { // remove unneeded key frames - if (historyItems[i]->mIsFinalized == false) + if (historyItem->mIsFinalized == false) { - historyItems[i]->mGlobalWeights.Optimize(0.0001f); - historyItems[i]->mLocalWeights.Optimize(0.0001f); - historyItems[i]->mPlayTimes.Optimize(0.0001f); - historyItems[i]->mIsFinalized = true; + historyItem->mGlobalWeights.Optimize(0.0001f); + historyItem->mLocalWeights.Optimize(0.0001f); + historyItem->mPlayTimes.Optimize(0.0001f); + historyItem->mIsFinalized = true; } } } @@ -1246,8 +1215,8 @@ namespace EMotionFX // iterate over all events AZStd::vector& historyItems = actorInstanceData->mEventHistoryItems; - const uint32 numEvents = eventBuffer.GetNumEvents(); - for (uint32 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); if (eventInfo.m_eventState == EventInfo::EventInfo::ACTIVE) @@ -1284,11 +1253,8 @@ namespace EMotionFX { MCORE_UNUSED(recordTime); const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (const EventHistoryItem* curItem : historyItems) { - EventHistoryItem* curItem = historyItems[i]; - if (curItem->mStartTime < eventInfo.mTimeValue) { continue; @@ -1300,19 +1266,17 @@ 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 AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.size(); 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) { continue; @@ -1353,15 +1317,14 @@ namespace EMotionFX const AnimGraphInstanceData* animGraphData = actorInstanceData.mAnimGraphData; if (animGraphData == nullptr) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - const uint32 numFrames = animGraphData->mFrames.size(); + const size_t numFrames = animGraphData->mFrames.size(); if (numFrames == 0) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - else if (numFrames == 1) { return 0; @@ -1377,7 +1340,7 @@ namespace EMotionFX return animGraphData->mFrames.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]; @@ -1387,7 +1350,7 @@ namespace EMotionFX } } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } void Recorder::RemoveActorInstanceFromRecording(ActorInstance* actorInstance) @@ -1401,7 +1364,7 @@ namespace EMotionFX 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) { @@ -1458,12 +1421,12 @@ namespace EMotionFX // extract sorted active items - void Recorder::ExtractNodeHistoryItems(const ActorInstanceData& actorInstanceData, float timeValue, bool sort, EValueType valueType, AZStd::vector* outItems, AZStd::vector* 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); + const size_t maxIndex = CalcMaxNodeHistoryTrackIndex(actorInstanceData); outItems->resize(maxIndex + 1); - for (uint32 i = 0; i <= maxIndex; ++i) + for (size_t i = 0; i <= maxIndex; ++i) { ExtractedNodeHistoryItem item; item.mTrackIndex = i; @@ -1475,10 +1438,8 @@ namespace EMotionFX // find all node history items const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[i]; if (curItem->mStartTime <= timeValue && curItem->mEndTime > timeValue) { ExtractedNodeHistoryItem item; @@ -1511,7 +1472,7 @@ namespace EMotionFX // build the map outMap->resize(maxIndex + 1); - for (uint32 i = 0; i <= maxIndex; ++i) + for (size_t i = 0; i <= maxIndex; ++i) { outMap->emplace(AZStd::next(begin(*outMap), i), i); } @@ -1521,7 +1482,7 @@ namespace EMotionFX { AZStd::sort(begin(*outItems), end(*outItems)); - for (uint32 i = 0; i <= maxIndex; ++i) + for (size_t i = 0; i <= maxIndex; ++i) { outMap->emplace(AZStd::next(begin(*outMap), outItems->at(i).mTrackIndex), i); } @@ -1529,17 +1490,17 @@ namespace EMotionFX } - 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.size(); - for (uint32 i = 0; i < numNodeHistoryItems; ++i) + const size_t numNodeHistoryItems = actorInstanceData.mNodeHistoryItems.size(); + for (size_t i = 0; i < numNodeHistoryItems; ++i) { EMotionFX::Recorder::NodeHistoryItem* item = actorInstanceData.mNodeHistoryItems[i]; @@ -1556,10 +1517,10 @@ namespace EMotionFX } // We at least have a single active motion. - AZ::u32 intermediateResult = 1; + size_t intermediateResult = 1; trackFlags[item->mTrackIndex] = true; - for (uint32 j = 0; j < numNodeHistoryItems; ++j) + for (size_t j = 0; j < numNodeHistoryItems; ++j) { EMotionFX::Recorder::NodeHistoryItem* innerItem = actorInstanceData.mNodeHistoryItems[j]; @@ -1586,20 +1547,20 @@ namespace EMotionFX } } - 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 02a61627a4..a727750d1f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h @@ -63,7 +63,7 @@ namespace EMotionFX 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. */ + size_t 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). */ @@ -95,8 +95,8 @@ namespace EMotionFX struct EMFX_API EventHistoryItem { EventInfo mEventInfo; - uint32 mEventIndex; /**< The index to use in combination with GetEventManager().GetEvent(index). */ - uint32 mTrackIndex; + size_t mEventIndex; /**< The index to use in combination with GetEventManager().GetEvent(index). */ + size_t mTrackIndex; AnimGraphNodeId mEmitterNodeId; uint32 mAnimGraphID; AZ::Color mColor; @@ -106,8 +106,8 @@ namespace EMotionFX EventHistoryItem() { - mEventIndex = MCORE_INVALIDINDEX32; - mTrackIndex = MCORE_INVALIDINDEX32; + mEventIndex = InvalidIndex; + mTrackIndex = InvalidIndex; mEmitterNodeId = AnimGraphNodeId(); mAnimGraphID = MCORE_INVALIDINDEX32; @@ -130,7 +130,7 @@ namespace EMotionFX 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 + size_t 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 @@ -146,7 +146,7 @@ namespace EMotionFX mStartTime = 0.0f; mEndTime = 0.0f; mMotionID = MCORE_INVALIDINDEX32; - mTrackIndex = MCORE_INVALIDINDEX32; + mTrackIndex = InvalidIndex; mCachedKey = MCORE_INVALIDINDEX32; mNodeId = AnimGraphNodeId(); mAnimGraphInstance = nullptr; @@ -169,7 +169,7 @@ namespace EMotionFX struct EMFX_API ExtractedNodeHistoryItem { NodeHistoryItem* mNodeHistoryItem; - uint32 mTrackIndex; + size_t mTrackIndex; float mValue; float mKeyTrackSampleTime; @@ -194,7 +194,7 @@ namespace EMotionFX struct EMFX_API AnimGraphAnimObjectInfo { - uint32 mFrameByteOffset; + size_t mFrameByteOffset; AnimGraphObject* mObject; }; @@ -202,8 +202,8 @@ namespace EMotionFX struct EMFX_API AnimGraphAnimFrame { float mTimeValue = 0.0f; - uint32 mByteOffset = 0; - uint32 mNumBytes = 0; + size_t mByteOffset = 0; + size_t mNumBytes = 0; AZStd::vector mObjectInfos{}; AZStd::vector> mParameterValues{}; }; @@ -211,8 +211,8 @@ namespace EMotionFX struct EMFX_API AnimGraphInstanceData { AnimGraphInstance* mAnimGraphInstance = nullptr; - uint32 mNumFrames = 0; - uint32 mDataBufferSize = 0; + size_t mNumFrames = 0; + size_t mDataBufferSize = 0; uint8* mDataBuffer = nullptr; AZStd::vector mFrames{}; @@ -287,18 +287,16 @@ namespace EMotionFX ~ActorInstanceData() { // clear the node history items - const uint32 numMotionItems = mNodeHistoryItems.size(); - for (uint32 i = 0; i < numMotionItems; ++i) + for (NodeHistoryItem* nodeHistoryItem : mNodeHistoryItems) { - delete mNodeHistoryItems[i]; + delete nodeHistoryItem; } mNodeHistoryItems.clear(); // clear the event history items - const uint32 numEventItems = mEventHistoryItems.size(); - for (uint32 i = 0; i < numEventItems; ++i) + for (auto & eventHistoryItem : mEventHistoryItems) { - delete mEventHistoryItems[i]; + delete eventHistoryItem; } mEventHistoryItems.clear(); @@ -315,7 +313,6 @@ namespace EMotionFX static Recorder* Create(); - void Reserve(uint32 numTransformKeys); bool HasRecording() const; void Clear(); void StartRecording(const RecordSettings& settings); @@ -348,17 +345,17 @@ namespace EMotionFX 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, AZStd::vector* outItems, AZStd::vector* outMap); + void ExtractNodeHistoryItems(const ActorInstanceData& actorInstanceData, float timeValue, bool sort, EValueType valueType, AZStd::vector* outItems, AZStd::vector* outMap) const; void StartPlayBack(); void StopPlayBack(); @@ -403,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; + 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 68c2f2a5c3..6bbf60700b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp @@ -26,7 +26,7 @@ namespace EMotionFX RepositioningLayerPass::RepositioningLayerPass(MotionLayerSystem* motionLayerSystem) : LayerPass(motionLayerSystem) { - mLastReposNode = MCORE_INVALIDINDEX32; + mLastReposNode = InvalidIndex; } @@ -77,8 +77,8 @@ 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 = mMotionSystem->GetNumMotionInstances(); + for (size_t i = numMotionInstances - 1; i != InvalidIndex; --i) { MotionInstance* motionInstance = mMotionSystem->GetMotionInstance(i); if (!motionInstance->GetMotionExtractionEnabled()) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h index 05f09d6329..4df680092a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h @@ -59,8 +59,8 @@ namespace EMotionFX private: - AZStd::vector 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 mHierarchyPath; /**< The path of node indices to the repositioning node. */ + size_t mLastReposNode; /**< 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 006be1d9a5..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; } @@ -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..0e871499df 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp @@ -50,8 +50,8 @@ namespace EMotionFX mNumSampled.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) @@ -117,8 +108,8 @@ namespace EMotionFX 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/SkinningInfoVertexAttributeLayer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp index 3ccfa85ca8..4483d98e40 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp @@ -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..48eeabac77 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h @@ -171,7 +171,7 @@ namespace EMotionFX * @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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp index a8fd925123..004e415501 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp @@ -61,7 +61,7 @@ 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); @@ -89,7 +89,7 @@ namespace EMotionFX const size_t numBones = mBoneMatrices.size(); for (size_t i = 0; i < numBones; i++) { - const uint32 nodeIndex = mNodeNumbers[i]; + const size_t nodeIndex = mNodeNumbers[i]; mBoneMatrices[i] = skinningMatrices[nodeIndex]; } @@ -240,15 +240,15 @@ 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; + boneIndex = mBoneMatrices.size() - 1; } // set the bone number in the influence diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h index ab2d805ff1..466f1702a7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h @@ -78,7 +78,7 @@ namespace EMotionFX * @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. @@ -107,7 +107,7 @@ namespace EMotionFX * @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 mNodeNumbers[index]; } /** * Pre-allocate space for a given number of local bones. @@ -119,7 +119,7 @@ namespace EMotionFX protected: AZStd::vector mBoneMatrices; - AZStd::vector mNodeNumbers; + AZStd::vector mNodeNumbers; /** * Default constructor. @@ -137,18 +137,10 @@ namespace EMotionFX * @param nodeIndex The node number to search for. * @result The index inside the mBones member array, which uses the given node. */ - MCORE_INLINE uint32 FindLocalBoneIndex(uint32 nodeIndex) const + 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(mNodeNumbers), end(mNodeNumbers), nodeIndex); + return foundBoneIndex != end(mNodeNumbers) ? AZStd::distance(begin(mNodeNumbers), 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/StandardMaterial.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp index 98a192936e..4ee3a24056 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp @@ -396,9 +396,9 @@ namespace EMotionFX standardMaterial->mWireFrame = mWireFrame; // copy the layers - const uint32 numLayers = mLayers.size(); + const size_t numLayers = mLayers.size(); standardMaterial->mLayers.resize(numLayers); - for (uint32 i = 0; i < numLayers; ++i) + for (size_t i = 0; i < numLayers; ++i) { standardMaterial->mLayers[i] = StandardMaterialLayer::Create(); standardMaterial->mLayers[i]->InitFrom(mLayers[i]); @@ -559,14 +559,14 @@ namespace EMotionFX } - StandardMaterialLayer* StandardMaterial::GetLayer(uint32 nr) + StandardMaterialLayer* StandardMaterial::GetLayer(size_t nr) { MCORE_ASSERT(nr < mLayers.size()); return mLayers[nr]; } - void StandardMaterial::RemoveLayer(uint32 nr, bool delFromMem) + void StandardMaterial::RemoveLayer(size_t nr, bool delFromMem) { MCORE_ASSERT(nr < mLayers.size()); if (delFromMem) @@ -580,33 +580,27 @@ namespace EMotionFX void StandardMaterial::RemoveAllLayers() { - const uint32 numLayers = mLayers.size(); - for (uint32 i = 0; i < numLayers; ++i) + for (StandardMaterialLayer* mLayer : mLayers) { - mLayers[i]->Destroy(); + mLayer->Destroy(); } mLayers.clear(); } - uint32 StandardMaterial::FindLayer(uint32 layerType) const + size_t StandardMaterial::FindLayer(uint32 layerType) const { // search through all layers - const uint32 numLayers = mLayers.size(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(mLayers), end(mLayers), [layerType](const StandardMaterialLayer* layer) { - if (mLayers[i]->GetType() == layerType) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetType() == layerType; + }); + return foundLayer != end(mLayers) ? AZStd::distance(begin(mLayers), foundLayer) : InvalidIndex; } - void StandardMaterial::ReserveLayers(uint32 numLayers) + void StandardMaterial::ReserveLayers(size_t numLayers) { mLayers.reserve(numLayers); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h index de637cf3df..05f8154a72 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h @@ -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. @@ -422,14 +422,14 @@ namespace EMotionFX * @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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp index 7701771952..5164f97c01 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp @@ -72,7 +72,7 @@ namespace EMotionFX mPose.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(); @@ -93,7 +93,7 @@ namespace EMotionFX } // 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(); } @@ -119,27 +119,27 @@ namespace EMotionFX 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 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; @@ -148,7 +148,7 @@ namespace EMotionFX ) // EMFX_SCALECODE // set the number of morph weights - void TransformData::SetNumMorphWeights(uint32 numMorphWeights) + void TransformData::SetNumMorphWeights(size_t numMorphWeights) { mPose.ResizeNumMorphs(numMorphWeights); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h index fa0d430871..d4e70134a3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h @@ -81,14 +81,14 @@ namespace EMotionFX * 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) { mPose.SetLocalSpaceTransform(nodeIndex, mBindPose->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 < mNumTransforms; ++i) { mPose.SetLocalSpaceTransform(i, mBindPose->GetLocalSpaceTransform(i)); } @@ -96,23 +96,23 @@ namespace EMotionFX 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 size_t GetNumTransforms() const { return mNumTransforms; } 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. */ + size_t 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)? */ /** 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..d0e8730e52 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" @@ -80,25 +81,15 @@ namespace EMStudio mPlugins.clear(); // delete all active plugins - const int32 numActivePlugins = static_cast(mActivePlugins.size()); - if (numActivePlugins > 0) + for (auto plugin = mActivePlugins.rbegin(); plugin != mActivePlugins.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 : mActivePlugins) { - 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; + mActivePlugins.pop_back(); } } @@ -114,8 +105,8 @@ 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; } @@ -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(mPlugins), end(mPlugins), [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(mPlugins) ? AZStd::distance(begin(mPlugins), 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(mActivePlugins), end(mActivePlugins), [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(mActivePlugins) ? *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(mActivePlugins), end(mActivePlugins), [&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(mActivePlugins.begin(), mActivePlugins.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(mActivePlugins), end(mActivePlugins), [classID](const EMStudioPlugin* plugin) { - if (mActivePlugins[i]->GetClassID() == classID) - { - return mActivePlugins[i]; - } - } - - return nullptr; + return plugin->GetClassID() == classID; + }); + return foundPlugin != end(mActivePlugins) ? *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(mActivePlugins.begin(), mActivePlugins.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..2937c3b387 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,15 +47,15 @@ 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 mPlugins.size(); } + MCORE_INLINE EMStudioPlugin* GetPlugin(const size_t index) { return mPlugins[index]; } - MCORE_INLINE uint32 GetNumActivePlugins() const { return static_cast(mActivePlugins.size()); } - MCORE_INLINE EMStudioPlugin* GetActivePlugin(const uint32 index) { return mActivePlugins[index]; } + MCORE_INLINE size_t GetNumActivePlugins() const { return mActivePlugins.size(); } + MCORE_INLINE EMStudioPlugin* GetActivePlugin(const size_t index) { return mActivePlugins[index]; } MCORE_INLINE const PluginVector& GetActivePlugins() { return mActivePlugins; } - 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; 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..ea41b0ab65 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 @@ -203,26 +204,17 @@ namespace EMStudio // calculate the number of selected elements - uint32 TimeTrack::CalcNumSelectedElements() const + size_t TimeTrack::CalcNumSelectedElements() const { if (mVisible == 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(mElements), end(mElements), size_t{0}, [](size_t total, const TimeTrackElement* element) { - if (mElements[i]->GetIsSelected()) - { - result++; - } - } - - return result; + return total + element->GetIsSelected(); + }); } @@ -234,28 +226,20 @@ namespace EMStudio 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(mElements), end(mElements), [](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(mElements) ? *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(); @@ -281,11 +265,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 : mElements) { // 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..4046ebf55f 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 @@ -45,8 +45,8 @@ namespace EMStudio // @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)]; } + MCORE_INLINE size_t GetNumElements() const { return mElements.size(); } + MCORE_INLINE TimeTrackElement* GetElement(size_t index) const { return mElements[index]; } void AddElement(TimeTrackElement* elem) { elem->SetTrack(this); mElements.push_back(elem); } void RemoveElement(TimeTrackElement* elem, bool delFromMem = true) { @@ -56,7 +56,7 @@ namespace EMStudio delete elem; } } - void RemoveElement(uint32 index, bool delFromMem = true) + void RemoveElement(size_t index, bool delFromMem = true) { if (delFromMem) { @@ -70,9 +70,9 @@ namespace EMStudio mElements.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; } 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/MultiThreadManager.h b/Gems/EMotionFX/Code/MCore/Source/MultiThreadManager.h index b97f7b2f22..a4fe6eaa10 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MultiThreadManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/MultiThreadManager.h @@ -104,6 +104,22 @@ namespace MCore }; + class MCORE_API AtomicSizeT + { + public: + MCORE_INLINE AtomicSizeT() { SetValue(0); } + + MCORE_INLINE void SetValue(size_t value) { mAtomic.store(value); } + MCORE_INLINE size_t GetValue() const { size_t value = mAtomic.load(); return value; } + + MCORE_INLINE size_t Increment() { return mAtomic++; } + MCORE_INLINE size_t Decrement() { return mAtomic--; } + + private: + AZStd::atomic mAtomic; + }; + + class MCORE_API Thread { public: diff --git a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp index 279a7aec1e..4e89072f70 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp @@ -43,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 = mStringToIndex.emplace(objectName, aznumeric_caster(mStrings.size())); if (!iterator.second) { // could not insert, we have the element @@ -148,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/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index b033e46a87..9f996f46fd 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -722,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) @@ -762,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) @@ -870,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/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/System/SystemComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp index c1b7be1239..78aa3b4426 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp @@ -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); 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/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/AnimGraphNodeEventFilterTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphNodeEventFilterTests.cpp index 67f6fa860e..eb1da8f0a3 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphNodeEventFilterTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphNodeEventFilterTests.cpp @@ -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); } 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/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/AnimGraphSyncTrackTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphSyncTrackTests.cpp index fedd77bb24..d23638c9ea 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphSyncTrackTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphSyncTrackTests.cpp @@ -95,8 +95,8 @@ namespace EMotionFX { MakeNoEvents, 0.5f, - MCORE_INVALIDINDEX32, - MCORE_INVALIDINDEX32 + InvalidIndex, + InvalidIndex }, { MakeOneEvent, @@ -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/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/BlendTreeFootIKNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp index 48350ce071..609d291800 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp @@ -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); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp index 29c6269639..e63fd2c2c7 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp @@ -68,8 +68,8 @@ 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); @@ -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(); 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/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/PoseComparisonTests.cpp b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp index dff4f4162c..d50b72cb4d 100644 --- a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp +++ b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp @@ -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) @@ -222,7 +222,7 @@ 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.mActorInstance->GetActor()->GetSkeleton()->GetNode(trackNum)->GetName(); EXPECT_THAT(gotTrack.mPositions, MatchesKeyTrack(expectedTrack.mPositions, nodeName)); EXPECT_THAT(gotTrack.mRotations, MatchesKeyTrack(expectedTrack.mRotations, nodeName)); @@ -285,7 +285,7 @@ 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.mActorInstance->GetActor()->GetSkeleton()->GetNode(trackNum)->GetName(); EXPECT_THAT(gotTrack.mPositions, MatchesKeyTrack(expectedTrack.mPositions, nodeName)); EXPECT_THAT(gotTrack.mRotations, MatchesKeyTrack(expectedTrack.mRotations, nodeName)); 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/Mocks/AnimGraph.h b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h index 90da8d5890..00eca16f44 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h @@ -30,7 +30,7 @@ namespace EMotionFX //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 711392f6cf..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); 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/Node.h b/Gems/EMotionFX/Code/Tests/Mocks/Node.h index 9479883487..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(AZStd::vector& 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/MorphTargetRuntimeTests.cpp b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp index 24afc7af47..10f735ca24 100644 --- a/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp @@ -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..a857efb2ca 100644 --- a/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp @@ -191,7 +191,7 @@ 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]; diff --git a/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp b/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp index 7498eed311..02256e1e12 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; diff --git a/Gems/EMotionFX/Code/Tests/PoseTests.cpp b/Gems/EMotionFX/Code/Tests/PoseTests.cpp index 1785a4d512..0dd592cda7 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; @@ -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); @@ -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); @@ -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); @@ -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); @@ -1228,8 +1228,8 @@ namespace EMotionFX } // 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); } 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/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/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 9ba4e4f6cb..c261f63bc1 100644 --- a/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp @@ -35,7 +35,7 @@ namespace EMotionFX 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); diff --git a/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp b/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp index 28f139fe39..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()."; @@ -47,12 +47,12 @@ namespace EMotionFX const Skeleton* skeleton = actor->GetSkeleton(); const AZStd::vector& enabledJoints = actorInstance->GetEnabledNodes(); - const AZ::u32 numEnabledJoints = enabledJoints.size(); - EXPECT_EQ(actorInstance->GetNumEnabledNodes(), actor->GetNumNodes() - static_cast(disabledJointNames.size())) + 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/UniformMotionDataTests.cpp b/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp index 79bb4627d0..7433a403e1 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; 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. From 120ee641447aae95c0f65c691282c3f6e60d104d Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 2 Jun 2021 16:33:36 -0700 Subject: [PATCH 185/251] Convert EMotionFX editor uint32 -> size_t Signed-off-by: Chris Burel --- .../SceneAPIExt/Rules/MetaDataRule.cpp | 8 +- .../EMotionFX/Rendering/Common/RenderUtil.cpp | 62 ++--- .../EMotionFX/Rendering/Common/RenderUtil.h | 8 +- .../Rendering/OpenGL2/Source/GLActor.cpp | 121 ++++----- .../Rendering/OpenGL2/Source/GLRenderUtil.cpp | 27 +- .../Rendering/OpenGL2/Source/GLRenderUtil.h | 2 +- .../Rendering/OpenGL2/Source/GLSLShader.cpp | 108 ++++---- .../Rendering/OpenGL2/Source/GLSLShader.h | 8 +- .../OpenGL2/Source/GraphicsManager.cpp | 5 +- .../Rendering/OpenGL2/Source/ShaderCache.cpp | 33 +-- .../OpenGL2/Source/StandardMaterial.cpp | 29 +-- .../Rendering/OpenGL2/Source/TextureCache.cpp | 63 ++--- .../Rendering/OpenGL2/Source/glactor.h | 12 +- .../AnimGraphGameControllerSettings.cpp | 33 +-- .../Source/AnimGraphGameControllerSettings.h | 4 +- .../Code/EMotionFX/Source/AnimGraphNode.cpp | 2 +- .../Code/EMotionFX/Source/EventHandler.h | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h | 2 +- .../Code/EMotionFX/Source/Recorder.h | 4 +- .../EMStudioSDK/Source/Commands.cpp | 4 +- .../EMStudioSDK/Source/EMStudioManager.cpp | 8 +- .../EMStudioSDK/Source/EMStudioManager.h | 12 +- .../EMStudioSDK/Source/FileManager.cpp | 20 +- .../EMStudioSDK/Source/FileManager.h | 4 +- .../EMStudioSDK/Source/LayoutManager.cpp | 6 +- .../EMStudioSDK/Source/MainWindow.cpp | 67 +++-- .../Source/MorphTargetSelectionWindow.cpp | 4 +- .../Source/MotionSetHierarchyWidget.cpp | 18 +- .../Source/NodeHierarchyWidget.cpp | 79 ++---- .../Source/NotificationWindowManager.cpp | 14 +- .../RenderPlugin/ManipulatorCallbacks.cpp | 28 +-- .../Source/RenderPlugin/RenderPlugin.cpp | 144 ++++------- .../Source/RenderPlugin/RenderPlugin.h | 6 +- .../RenderPlugin/RenderUpdateCallback.cpp | 12 +- .../Source/RenderPlugin/RenderWidget.cpp | 42 ++-- .../Source/ResetSettingsDialog.cpp | 4 +- .../EMStudioSDK/Source/Workspace.cpp | 34 +-- .../ActionHistory/ActionHistoryCallback.cpp | 20 +- .../AnimGraph/AnimGraphActionManager.cpp | 12 +- .../Source/AnimGraph/AnimGraphEditor.cpp | 26 +- .../Source/AnimGraph/AnimGraphEditor.h | 2 +- .../Source/AnimGraph/AnimGraphModel.cpp | 42 ++-- .../AnimGraph/AnimGraphModelCallbacks.cpp | 2 +- .../Source/AnimGraph/AnimGraphPlugin.cpp | 81 +++--- .../Source/AnimGraph/AnimGraphPlugin.h | 4 +- .../Source/AnimGraph/BlendGraphViewWidget.cpp | 8 +- .../Source/AnimGraph/BlendGraphWidget.cpp | 16 +- .../Source/AnimGraph/BlendGraphWidget.h | 4 +- .../Source/AnimGraph/BlendTreeVisualNode.cpp | 28 +-- .../Source/AnimGraph/ContextMenu.cpp | 10 +- .../Source/AnimGraph/GameController.cpp | 2 +- .../Source/AnimGraph/GameController.h | 2 +- .../Source/AnimGraph/GameControllerWindow.cpp | 109 +++----- .../Source/AnimGraph/GraphNode.cpp | 236 +++++------------- .../Source/AnimGraph/GraphNode.h | 22 +- .../Source/AnimGraph/NodeConnection.cpp | 2 +- .../Source/AnimGraph/NodeConnection.h | 14 +- .../Source/AnimGraph/NodeGraph.cpp | 179 ++++++------- .../Source/AnimGraph/NodeGraph.h | 18 +- .../Source/AnimGraph/NodeGraphWidget.cpp | 39 ++- .../Source/AnimGraph/NodeGraphWidget.h | 6 +- .../Source/AnimGraph/NodeGroupWindow.cpp | 69 +++-- .../Source/AnimGraph/NodeGroupWindow.h | 4 +- .../Source/AnimGraph/ParameterWindow.cpp | 16 +- .../AnimGraph/StateFilterSelectionWindow.cpp | 6 +- .../Source/AnimGraph/StateGraphNode.cpp | 4 +- .../Source/AnimGraph/StateGraphNode.h | 6 +- .../Attachments/AttachmentNodesWindow.cpp | 35 ++- .../AttachmentsHierarchyWindow.cpp | 12 +- .../Source/Attachments/AttachmentsWindow.cpp | 60 ++--- .../Source/LogWindow/LogWindowCallback.cpp | 18 +- .../Source/LogWindow/LogWindowPlugin.cpp | 4 +- .../PhonemeSelectionWindow.cpp | 38 ++- .../PhonemeSelectionWindow.h | 4 +- .../MotionSetManagementWindow.cpp | 99 ++++---- .../MotionSetsWindow/MotionSetWindow.cpp | 100 ++++---- .../Source/MotionSetsWindow/MotionSetWindow.h | 6 +- .../MotionSetsWindowPlugin.cpp | 14 +- .../MotionWindow/MotionExtractionWindow.cpp | 12 +- .../Source/MotionWindow/MotionListWindow.cpp | 43 ++-- .../MotionWindow/MotionRetargetingWindow.cpp | 8 +- .../MotionWindow/MotionWindowPlugin.cpp | 156 +++--------- .../Source/NodeGroups/NodeGroupWidget.cpp | 7 +- .../Source/NodeGroups/NodeGroupWidget.h | 2 +- .../Source/NodeWindow/ActorInfo.cpp | 2 +- .../Source/NodeWindow/ActorInfo.h | 2 +- .../Source/NodeWindow/MeshInfo.cpp | 2 +- .../Source/NodeWindow/MeshInfo.h | 4 +- .../Source/NodeWindow/NodeInfo.cpp | 14 +- .../Source/NodeWindow/NodeWindowPlugin.h | 4 +- .../SceneManager/ActorPropertiesWindow.cpp | 12 +- .../Source/SceneManager/ActorsWindow.cpp | 75 +++--- .../Source/SceneManager/ActorsWindow.h | 2 +- .../SceneManager/SceneManagerPlugin.cpp | 8 +- .../Source/TimeView/PlaybackControlsGroup.cpp | 4 +- .../Source/TimeView/PlaybackOptionsGroup.cpp | 6 +- .../Source/TimeView/TimeTrack.cpp | 11 +- .../Source/TimeView/TimeTrack.h | 4 +- .../Source/TimeView/TimeTrackElement.cpp | 2 +- .../Source/TimeView/TimeTrackElement.h | 8 +- .../Source/TimeView/TimeViewPlugin.cpp | 205 ++++++--------- .../Source/TimeView/TimeViewPlugin.h | 10 +- .../Source/TimeView/TimeViewToolBar.cpp | 24 +- .../Source/TimeView/TrackDataWidget.cpp | 187 ++++++-------- .../Source/TimeView/TrackDataWidget.h | 6 +- .../Source/TimeView/TrackHeaderWidget.cpp | 12 +- .../Source/TimeView/TrackHeaderWidget.h | 12 +- .../Code/MysticQt/Source/DialogStack.cpp | 207 +++++++-------- .../Code/MysticQt/Source/DialogStack.h | 13 +- .../Source/KeyboardShortcutManager.cpp | 2 +- .../Source/Editor/ActorJointBrowseEdit.cpp | 4 +- .../Source/Editor/ColliderContainerWidget.cpp | 10 +- .../Ragdoll/RagdollNodeInspectorPlugin.cpp | 16 +- .../SimulatedObject/SimulatedObjectWidget.cpp | 14 +- .../Source/Editor/SimulatedObjectHelpers.cpp | 8 +- .../Source/Editor/SimulatedObjectModel.cpp | 8 +- .../Code/Source/Editor/SimulatedObjectModel.h | 2 +- .../Code/Source/Editor/SkeletonModel.cpp | 36 +-- .../Integration/Components/ActorComponent.h | 4 +- .../Components/SimpleLODComponent.cpp | 19 +- .../Components/SimpleLODComponent.h | 4 +- .../Components/EditorActorComponent.cpp | 10 +- .../Editor/Components/EditorActorComponent.h | 4 +- .../Components/EditorSimpleLODComponent.cpp | 4 +- 125 files changed, 1502 insertions(+), 2127 deletions(-) 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/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index 34ab2a8a69..34dba922ca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -314,7 +314,7 @@ namespace MCommon // render the given types of AABBs of a actor instance void RenderUtil::RenderAabbs(EMotionFX::ActorInstance* actorInstance, const AABBRenderSettings& renderSettings, bool directlyRender) { - const uint32 lodLevel = actorInstance->GetLODLevel(); + const size_t lodLevel = actorInstance->GetLODLevel(); // handle the node based AABB if (renderSettings.mNodeBasedAABB) @@ -365,19 +365,19 @@ 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())) @@ -385,8 +385,8 @@ namespace MCommon const AZ::Vector3 currentJointPos = pose->GetWorldSpaceTransform(jointIndex).mPosition; 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; @@ -419,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); @@ -481,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); @@ -513,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); @@ -634,11 +634,11 @@ namespace MCommon EMotionFX::TransformData* transformData = actorInstance->GetTransformData(); const EMotionFX::Pose* pose = transformData->GetCurrentPose(); - const uint32 nodeIndex = node->GetNodeIndex(); - const uint32 parentIndex = node->GetParentIndex(); + const size_t nodeIndex = node->GetNodeIndex(); + const size_t parentIndex = node->GetParentIndex(); const AZ::Vector3 nodeWorldPos = pose->GetWorldSpaceTransform(nodeIndex).mPosition; - if (parentIndex != MCORE_INVALIDINDEX32) + if (parentIndex != InvalidIndex) { const AZ::Vector3 parentWorldPos = pose->GetWorldSpaceTransform(parentIndex).mPosition; const AZ::Vector3 bone = parentWorldPos - nodeWorldPos; @@ -653,7 +653,7 @@ namespace MCommon // render the advanced skeleton - 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) + 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) @@ -715,7 +715,7 @@ namespace MCommon // render node orientations - void RenderUtil::RenderNodeOrientations(EMotionFX::ActorInstance* actorInstance, const AZStd::vector& 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()); @@ -775,11 +775,11 @@ 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); @@ -789,8 +789,8 @@ namespace MCommon // 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); @@ -1582,8 +1582,8 @@ namespace MCommon 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); @@ -1673,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; } @@ -1710,7 +1710,7 @@ namespace MCommon // fast access to the trajectory trace particles const AZStd::vector& traceParticles = trajectoryPath->mTraceParticles; - const int32 numTraceParticles = traceParticles.size(); + const size_t numTraceParticles = traceParticles.size(); if (traceParticles.empty()) { return; @@ -1781,7 +1781,7 @@ 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; @@ -1883,18 +1883,18 @@ 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 size_t jointIndex = joint->GetNodeIndex(); const AZ::Vector3 worldPos = pose->GetWorldSpaceTransform(jointIndex).mPosition; // check if the current enabled node is along the visible nodes and render it if that is the case diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h index d62816fa65..6e870c870e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h @@ -177,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); @@ -191,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 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)); + 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. @@ -202,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 AZStd::vector& 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. @@ -224,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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp index 5a7d2032a7..f7f21629a3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp @@ -56,42 +56,36 @@ 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 : mVertexBuffers) { - // get rid of the given vertex buffers - const uint32 numVertexBuffers = mVertexBuffers[a].size(); - 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].size(); - for (i = 0; i < numIndexBuffers; ++i) + } + for (AZStd::vector& indexBuffers : mIndexBuffers) + { + for (IndexBuffer* indexBuffer : indexBuffers) { - delete mIndexBuffers[a][i]; + delete indexBuffer; } } // delete all materials - const uint32 numLOD = mMaterials.size(); - for (uint32 l = 0; l < numLOD; l++) + for (AZStd::vector& materialsPerLod : mMaterials) { - const uint32 numMaterials = mMaterials[l].size(); - for (uint32 n = 0; n < numMaterials; n++) + for (MaterialPrimitives* materialPrimitives : materialsPerLod) { - delete mMaterials[l][n]->mMaterial; - delete mMaterials[l][n]; + delete materialPrimitives->mMaterial; + 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); @@ -120,18 +114,19 @@ namespace RenderGL mMaterials.resize(numGeometryLODLevels); // resize the vertex and index buffers - for (uint32 a = 0; a < 3; ++a) + for (AZStd::vector& vertexBuffers : mVertexBuffers) { - 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 : mIndexBuffers) + { + indexBuffers.resize(numGeometryLODLevels); + AZStd::fill(begin(indexBuffers), end(indexBuffers), nullptr); + } + for (MCore::Array2D& primitives : mPrimitives) + { + primitives.Resize(numGeometryLODLevels); } mHomoMaterials.resize(numGeometryLODLevels); @@ -140,7 +135,7 @@ namespace RenderGL 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); @@ -172,7 +167,7 @@ namespace RenderGL // get the number of submeshes and iterate through them const size_t numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 s = 0; s < numSubMeshes; ++s) + for (size_t s = 0; s < numSubMeshes; ++s) { // get the current submesh EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(s); @@ -212,7 +207,7 @@ namespace RenderGL } // 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(); @@ -230,7 +225,7 @@ 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(); @@ -248,7 +243,7 @@ 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(); @@ -275,7 +270,7 @@ 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 (size_t n = 0; n < numNodes; ++n) @@ -312,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); @@ -356,11 +351,11 @@ namespace RenderGL // 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 = mActor->GetNumMaterials(lodLevel); + for (size_t m = 0; m < numMaterials; ++m) { EMotionFX::Material* emfxMaterial = mActor->GetMaterial(lodLevel, m); Material* material = InitMaterial(emfxMaterial); @@ -402,8 +397,8 @@ 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].size(); + const size_t lodLevel = actorInstance->GetLODLevel(); + const size_t numMaterials = mMaterials[lodLevel].size(); if (numMaterials == 0) { @@ -425,11 +420,9 @@ namespace RenderGL mIndexBuffers[meshType][lodLevel]->Activate(); // render all the primitives in each material - for (uint32 n = 0; n < numMaterials; n++) + for (const MaterialPrimitives* materialPrims : mMaterials[lodLevel]) { - const MaterialPrimitives* materialPrims = mMaterials[lodLevel][n]; - const uint32 numPrimitives = materialPrims->mPrimitives[meshType].size(); - if (numPrimitives == 0) + if (materialPrims->mPrimitives[meshType].empty()) { continue; } @@ -450,9 +443,9 @@ namespace RenderGL material->Activate(activationFlags); // render all primitives - for (uint32 i = 0; i < numPrimitives; ++i) + for (const Primitive& primitive : materialPrims->mPrimitives[meshType]) { - material->Render(actorInstance, &materialPrims->mPrimitives[meshType][i]); + material->Render(actorInstance, &primitive); } material->Deactivate(); @@ -464,7 +457,7 @@ namespace RenderGL void GLActor::UpdateDynamicVertices(EMotionFX::ActorInstance* actorInstance) { // get the number of dynamic nodes - const uint32 lodLevel = actorInstance->GetLODLevel(); + const size_t lodLevel = actorInstance->GetLODLevel(); const size_t numNodes = mDynamicNodes.GetNumElements(lodLevel); if (numNodes == 0) { @@ -491,7 +484,7 @@ namespace RenderGL { // get the node and its mesh const size_t nodeIndex = mDynamicNodes.GetElement(lodLevel, n); - EMotionFX::Mesh* mesh = mActor->GetMesh(lodLevel, aznumeric_cast(nodeIndex)); + EMotionFX::Mesh* mesh = mActor->GetMesh(lodLevel, nodeIndex); // is the mesh valid? if (mesh == nullptr) @@ -536,7 +529,7 @@ namespace RenderGL // fill the index buffers with data - void GLActor::FillIndexBuffers(uint32 lodLevel) + void GLActor::FillIndexBuffers(size_t lodLevel) { // initialize the index buffers uint32* staticIndices = nullptr; @@ -597,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); @@ -621,9 +613,6 @@ namespace RenderGL polyStartIndex += numPolyVerts; } - //for (uint32 i=0; iGetNumVertices(); break; } @@ -644,10 +633,6 @@ namespace RenderGL polyStartIndex += numPolyVerts; } - // fill in static index buffers - //for (uint32 i=0; iGetNumVertices(); break; } @@ -668,10 +653,6 @@ namespace RenderGL polyStartIndex += numPolyVerts; } - // fill in gpu skinned index buffers - //for (uint32 i=0; iGetNumVertices(); break; } @@ -695,7 +676,7 @@ namespace RenderGL // fill the static vertex buffer - void GLActor::FillStaticVertexBuffers(uint32 lodLevel) + void GLActor::FillStaticVertexBuffers(size_t lodLevel) { if (mVertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] == nullptr) { @@ -785,7 +766,7 @@ namespace RenderGL // 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) { @@ -849,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); @@ -877,9 +858,9 @@ 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()); + const size_t boneIndex = subMesh->FindBoneIndex(influence->GetNodeNr()); skinnedVertices[globalVert].mBoneIndices[i] = static_cast(boneIndex); - MCORE_ASSERT(boneIndex != MCORE_INVALIDINDEX32); + MCORE_ASSERT(boneIndex != InvalidIndex); } // reset remaining weights and offsets diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp index 2ef39bd7c5..c67ec180ed 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp @@ -37,16 +37,11 @@ namespace RenderGL mCurrentLineVB = 0; - for (uint32 i = 0; i < MAX_LINE_VERTEXBUFFERS; ++i) - { - mLineVertexBuffers[i] = nullptr; - } - // initialize the vertex buffers and the shader used for line rendering - for (uint32 i = 0; i < MAX_LINE_VERTEXBUFFERS; ++i) + for (VertexBuffer*& lineVertexBuffer : mLineVertexBuffers) { - mLineVertexBuffers[i] = new VertexBuffer(); - if (mLineVertexBuffers[i]->Init(sizeof(LineVertex), mNumMaxLineVertices, USAGE_DYNAMIC) == false) + lineVertexBuffer = new VertexBuffer(); + if (lineVertexBuffer->Init(sizeof(LineVertex), mNumMaxLineVertices, USAGE_DYNAMIC) == false) { MCore::LogError("[OpenGL] Failed to create render utility line vertex buffer."); CleanUp(); @@ -139,10 +134,10 @@ namespace RenderGL // destroy the allocated memory void GLRenderUtil::CleanUp() { - for (uint32 i = 0; i < MAX_LINE_VERTEXBUFFERS; ++i) + for (VertexBuffer*& lineVertexBuffer : mLineVertexBuffers) { - delete mLineVertexBuffers[i]; - mLineVertexBuffers[i] = nullptr; + delete lineVertexBuffer; + lineVertexBuffer = nullptr; } delete mMeshVertexBuffer; @@ -163,10 +158,9 @@ namespace RenderGL delete[] mTextures; // get rid of texture entries - const uint32 numTextEntries = mTextEntries.size(); - for (uint32 i = 0; i < numTextEntries; ++i) + for (TextEntry* mTextEntrie : mTextEntries) { - delete mTextEntries[i]; + delete mTextEntrie; } mTextEntries.clear(); } @@ -244,9 +238,6 @@ namespace RenderGL glPopAttrib(); - //const float renderTime = time.GetTime(); - //LOG("numTextures=%i, renderTime=%.3fms", mNumTextures, renderTime*1000); - mNumTextures = 0; } @@ -491,7 +482,7 @@ namespace RenderGL glDisable(GL_CULL_FACE); // get the number of vertices to render - const uint32 numVertices = triangleVertices.size(); + const uint32 numVertices = aznumeric_caster(triangleVertices.size()); MCORE_ASSERT(numVertices <= mNumMaxTriangleVertices); // lock the vertex buffer diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h index 672a8c524f..0f323ab00c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h @@ -74,7 +74,7 @@ namespace RenderGL #define MAX_LINE_VERTEXBUFFERS 2 GraphicsManager* mGraphicsManager; - VertexBuffer* mLineVertexBuffers[MAX_LINE_VERTEXBUFFERS]; + VertexBuffer* mLineVertexBuffers[MAX_LINE_VERTEXBUFFERS]{}; uint16 mCurrentLineVB; GLSLShader* mLineShader; GLSLShader* mMeshShader; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp index 451246a8e2..b1a5c4699d 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" @@ -65,17 +66,13 @@ namespace RenderGL // Deactivate void GLSLShader::Deactivate() { - const uint32 numAttribs = mActivatedAttribs.size(); - for (uint32 i = 0; i < numAttribs; ++i) + for (const size_t index : mActivatedAttribs) { - const uint32 index = mActivatedAttribs[i]; glDisableVertexAttribArray(mAttributes[index].mLocation); } - const uint32 numTextures = mActivatedTextures.size(); - for (uint32 i = 0; i < numTextures; ++i) + for (const size_t index : mActivatedTextures) { - const uint32 index = mActivatedTextures[i]; assert(mUniforms[index].mType == GL_SAMPLER_2D); glActiveTexture(GL_TEXTURE0 + mUniforms[index].mTextureUnit); glBindTexture(GL_TEXTURE_2D, 0); @@ -124,10 +121,9 @@ namespace RenderGL text = "#version 120\n"; // build define string - const uint32 numDefines = mDefines.size(); - for (uint32 n = 0; n < numDefines; ++n) + for (const AZStd::string& define : mDefines) { - 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 @@ -175,20 +171,16 @@ namespace RenderGL AZStd::invoke(func, static_cast(this), object, logLen, &logWritten, text.data()); // if there are any defines, print that out too - if (mDefines.size() > 0) + if (!mDefines.empty()) { AZStd::string dStr; - const uint32 numDefines = mDefines.size(); - for (uint32 n = 0; n < numDefines; ++n) + for (const AZStd::string& define : mDefines) { - if (n < numDefines - 1) + if (!dStr.empty()) { - dStr += mDefines[n] + " "; - } - else - { - dStr += mDefines[n]; + dStr.append(" "); } + dStr.append(define); } MCore::LogDetailedInfo("[GLSL] Compiling shader '%s', with defines %s", mFileName.c_str(), dStr.c_str()); @@ -260,8 +252,8 @@ 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; } @@ -273,20 +265,16 @@ namespace RenderGL // FindAttributeIndex size_t GLSLShader::FindAttributeIndex(const char* name) { - const uint32 numAttribs = mAttributes.size(); - for (uint32 i = 0; i < numAttribs; ++i) + const auto foundAttribute = AZStd::find_if(begin(mAttributes), end(mAttributes), [name](const auto& attribute) { - if (AzFramework::StringFunc::Equal(mAttributes[i].mName.c_str(), name, false /* no case */)) - { + return AzFramework::StringFunc::Equal(attribute.mName.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.mLocation >= 0; + }); + if (foundAttribute != end(mAttributes)) + { + return AZStd::distance(begin(mAttributes), foundAttribute); } // the parameter wasn't cached, try to retrieve it @@ -295,7 +283,7 @@ namespace RenderGL if (loc < 0) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } return mAttributes.size() - 1; @@ -303,12 +291,12 @@ namespace RenderGL // 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; @@ -318,8 +306,8 @@ namespace RenderGL // 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; } @@ -331,18 +319,14 @@ namespace RenderGL // FindUniformIndex size_t GLSLShader::FindUniformIndex(const char* name) { - const uint32 numUniforms = mUniforms.size(); - for (uint32 i = 0; i < numUniforms; ++i) + const auto foundUniform = AZStd::find_if(begin(mUniforms), end(mUniforms), [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.mName.c_str(), name, false /* no case */) && + uniform.mLocation >= 0; + }); + if (foundUniform != end(mUniforms)) + { + return AZStd::distance(begin(mUniforms), foundUniform); } // the parameter wasn't cached, try to retrieve it @@ -351,7 +335,7 @@ namespace RenderGL if (loc < 0) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } return mUniforms.size() - 1; @@ -361,8 +345,8 @@ namespace RenderGL // 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; } @@ -503,8 +487,8 @@ namespace RenderGL // 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; } @@ -534,8 +518,8 @@ namespace RenderGL // 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; } @@ -563,20 +547,12 @@ namespace RenderGL // 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.size(); - for (uint32 i = 0; i < numDefines; ++i) + return AZStd::any_of(begin(mDefines), end(mDefines), [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 6eb77b69c2..0db7948e8f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h @@ -36,11 +36,11 @@ 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); + bool CheckIfIsDefined(const char* attributeName) const; 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; @@ -84,8 +84,8 @@ namespace RenderGL AZ::IO::Path mFileName; - AZStd::vector mActivatedAttribs; - AZStd::vector mActivatedTextures; + AZStd::vector mActivatedAttribs; + AZStd::vector mActivatedTextures; AZStd::vector mUniforms; AZStd::vector mAttributes; AZStd::vector mDefines; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp index 78b5813770..4802477e08 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp @@ -416,10 +416,9 @@ namespace RenderGL // construct the lookup string for the shader cache AZStd::string cacheLookupStr = vertexPath.Native() + pixelPath.Native(); - const uint32 numDefines = defines.size(); - 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 diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp index 26acd0e77d..b02ab99505 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp @@ -30,11 +30,10 @@ namespace RenderGL void ShaderCache::Release() { // delete all shaders - const uint32 numEntries = mEntries.size(); - for (uint32 i = 0; i < numEntries; ++i) + for (Entry& entry : mEntries) { - mEntries[i].mName.clear(); - delete mEntries[i].mShader; + entry.mName.clear(); + delete entry.mShader; } // clear all entries @@ -52,32 +51,20 @@ namespace RenderGL // try to locate a shader based on its name Shader* ShaderCache::FindShader(AZStd::string_view filename) const { - const uint32 numEntries = mEntries.size(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundShader = AZStd::find_if(begin(mEntries), end(mEntries), [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.mName, filename, false /* no case */); + }); + return foundShader != end(mEntries) ? foundShader->mShader : nullptr; } // check if we have a given shader in the cache bool ShaderCache::CheckIfHasShader(Shader* shader) const { - const uint32 numEntries = mEntries.size(); - for (uint32 i = 0; i < numEntries; ++i) + return AZStd::any_of(begin(mEntries), end(mEntries), [shader](const Entry& entry) { - if (mEntries[i].mShader == shader) - { - return true; - } - } - - return false; + return entry.mShader == 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 46c7e5c13e..18281f286b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp @@ -183,8 +183,8 @@ namespace RenderGL 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()) @@ -232,11 +232,9 @@ namespace RenderGL // void StandardMaterial::SetAttribute(EAttribute attribute, bool enabled) { - const uint32 index = (uint32)attribute; - - if (mAttributes[index] != enabled) + if (mAttributes[attribute] != enabled) { - mAttributes[index] = enabled; + mAttributes[attribute] = enabled; mAttributesUpdated = true; } } @@ -264,15 +262,15 @@ namespace RenderGL const AZ::Matrix3x4* skinningMatrices = transformData->GetSkinningMatrices(); // multiple each transform by its inverse bind pose - const uint32 numBones = primitive->mBoneNodeIndices.size(); - for (uint32 i = 0; i < numBones; ++i) + const size_t numBones = primitive->mBoneNodeIndices.size(); + for (size_t i = 0; i < numBones; ++i) { - const uint32 nodeNr = primitive->mBoneNodeIndices[i]; + const size_t nodeNr = primitive->mBoneNodeIndices[i]; const AZ::Matrix3x4& skinTransform = skinningMatrices[nodeNr]; mBoneMatrices[i] = AZ::Matrix4x4::CreateFromMatrix3x4(skinTransform); } - mActiveShader->SetUniform("matBones", mBoneMatrices, numBones); + mActiveShader->SetUniform("matBones", mBoneMatrices, aznumeric_caster(numBones)); } const MCommon::Camera* camera = GetGraphicsManager()->GetCamera(); @@ -305,10 +303,9 @@ namespace RenderGL mActiveShader = nullptr; // get the number of shaders and iterate through them - const uint32 numShaders = mShaders.size(); - for (uint32 i = 0; i < numShaders; ++i) + for (GLSLShader* shader : mShaders) { - if (mShaders[i] == nullptr) + if (shader == nullptr) { continue; } @@ -319,7 +316,7 @@ namespace RenderGL { if (mAttributes[n]) { - if (mShaders[i]->CheckIfIsDefined(AttributeToString((EAttribute)n)) == false) + if (shader->CheckIfIsDefined(AttributeToString((EAttribute)n)) == false) { match = false; break; @@ -327,7 +324,7 @@ namespace RenderGL } else { - if (mShaders[i]->CheckIfIsDefined(AttributeToString((EAttribute)n))) + if (shader->CheckIfIsDefined(AttributeToString((EAttribute)n))) { match = false; break; @@ -338,7 +335,7 @@ namespace RenderGL // in case we have found a matching shader update the active shader if (match) { - mActiveShader = mShaders[i]; + mActiveShader = shader; break; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp index 7ef5b49c67..dfdce36284 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp @@ -73,10 +73,9 @@ namespace RenderGL void TextureCache::Release() { // delete all textures - const uint32 numEntries = mEntries.size(); - for (uint32 i = 0; i < numEntries; ++i) + for (Entry& entry : mEntries) { - delete mEntries[i].mTexture; + delete entry.mTexture; } // clear all entries @@ -102,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.size(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [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.mName.c_str(), filename, false /* no case */); + }); + return foundEntry != end(mEntries) ? foundEntry->mTexture : nullptr; } @@ -120,31 +113,25 @@ namespace RenderGL bool TextureCache::CheckIfHasTexture(Texture* texture) const { // get the number of entries and iterate through them - const uint32 numEntries = mEntries.size(); - for (uint32 i = 0; i < numEntries; ++i) + return AZStd::any_of(begin(mEntries), end(mEntries), [texture](const Entry& entry) { - if (mEntries[i].mTexture == texture) - { - return true; - } - } - - return false; + return entry.mTexture == texture; + }); } // remove an item from the cache void TextureCache::RemoveTexture(Texture* texture) { - const uint32 numEntries = mEntries.size(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [texture](const Entry& entry) + { + return entry.mTexture == texture; + }); + + if (foundEntry != end(mEntries)) { - if (mEntries[i].mTexture == texture) - { - delete mEntries[i].mTexture; - mEntries.erase(AZStd::next(begin(mEntries), i)); - return; - } + delete foundEntry->mTexture; + mEntries.erase(foundEntry); } } @@ -154,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); @@ -180,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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h index 4de5d7198a..0b87477114 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h @@ -75,18 +75,18 @@ namespace RenderGL 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); AZStd::vector< AZStd::vector > mMaterials; - MCore::Array2D mDynamicNodes; + MCore::Array2D mDynamicNodes; MCore::Array2D mPrimitives[3]; AZStd::vector mHomoMaterials; AZStd::vector mVertexBuffers[3]; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp index 83df46b74d..6f2d6083a1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp @@ -230,50 +230,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; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h index 715b280690..f543246599 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h @@ -153,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); @@ -164,6 +164,6 @@ namespace EMotionFX private: AZStd::vector m_presets; - AZ::u32 m_activePresetIndex; + size_t m_activePresetIndex; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp index e73f8cf731..67c3f276cc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp @@ -550,7 +550,7 @@ namespace EMotionFX { const size_t currentSize = mOutputPorts.size(); mOutputPorts.emplace_back(); - return static_cast(currentSize); + return currentSize; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h b/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h index 19024bb351..c0b7696205 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h @@ -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); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index d946344622..135a37200c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -1474,7 +1474,7 @@ namespace EMotionFX // 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index d9c09d66bb..b38a1445f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -596,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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h index a727750d1f..7d76b09483 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h @@ -131,7 +131,7 @@ namespace EMotionFX KeyTrackLinearDynamic mPlayTimes; // normalized time values (current time in the node/motion) uint32 mMotionID; // the ID of the Motion object used size_t mTrackIndex; // the track index - uint32 mCachedKey; // a cached key + size_t 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 @@ -147,7 +147,7 @@ namespace EMotionFX mEndTime = 0.0f; mMotionID = MCORE_INVALIDINDEX32; mTrackIndex = InvalidIndex; - mCachedKey = MCORE_INVALIDINDEX32; + mCachedKey = InvalidIndex; mNodeId = AnimGraphNodeId(); mAnimGraphInstance = nullptr; mAnimGraphID = MCORE_INVALIDINDEX32; 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/EMStudioManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp index c0867139e7..2f557ad290 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp @@ -177,7 +177,7 @@ namespace EMStudio #endif // EMFX_EMSTUDIOLYEMBEDDED // Give a chance to every plugin to reflect data - const uint32 numPlugins = mPluginManager->GetNumPlugins(); + const size_t numPlugins = mPluginManager->GetNumPlugins(); if (numPlugins) { AZ::SerializeContext* serializeContext = nullptr; @@ -188,7 +188,7 @@ namespace EMStudio } else { - for (uint32 i = 0; i < numPlugins; ++i) + for (size_t i = 0; i < numPlugins; ++i) { EMStudioPlugin* plugin = mPluginManager->GetPlugin(i); plugin->Reflect(serializeContext); @@ -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; } 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 915c45bc18..95dbd3012a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h @@ -93,11 +93,11 @@ 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; } @@ -123,8 +123,8 @@ namespace EMStudio NotificationWindowManager* mNotificationWindowManager; CommandSystem::CommandManager* mCommandManager; AZStd::string mCompileDate; - AZStd::unordered_set m_visibleJointIndices; - AZStd::unordered_set m_selectedJointIndices; + AZStd::unordered_set m_visibleJointIndices; + AZStd::unordered_set m_selectedJointIndices; Workspace mWorkspace; bool mAutoLoadLastWorkspace; AZStd::string mHTMLLinkString; 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..dcb7c46fe5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.cpp @@ -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()) @@ -570,7 +570,7 @@ namespace EMStudio } - 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(); 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 baf721d2ce..50dfce390a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h @@ -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); 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..eed352ad7c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.cpp @@ -127,7 +127,7 @@ namespace EMStudio header.mLayoutVersionHigh = 0; header.mLayoutVersionLow = 1; - header.mNumPlugins = GetPluginManager()->GetNumActivePlugins(); + header.mNumPlugins = aznumeric_caster(GetPluginManager()->GetNumActivePlugins()); if (file.write((char*)&header, sizeof(LayoutHeader)) == -1) { MCore::LogWarning("Failed to write layout header to layout file '%s'", filename); @@ -339,8 +339,8 @@ 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(); } 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 7303c8d559..c5781ebf12 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp @@ -1037,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(); @@ -1087,12 +1087,12 @@ 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 AZStd::vector sortedPlugins; sortedPlugins.reserve(numPlugins); - for (uint32 p = 0; p < numPlugins; ++p) + for (size_t p = 0; p < numPlugins; ++p) { EMStudioPlugin* plugin = pluginManager->GetPlugin(p); sortedPlugins.emplace_back(plugin->GetName()); @@ -1103,10 +1103,10 @@ namespace EMStudio mCreateWindowMenu->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 @@ -1222,8 +1222,8 @@ namespace EMStudio generalPropertyWidget->AddInstance(&mOptions, azrtti_typeid(mOptions)); 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(); @@ -1769,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(); @@ -1862,15 +1862,14 @@ namespace EMStudio } // add each menu - const uint32 numLayoutNames = mLayoutNames.size(); - for (uint32 i = 0; i < numLayoutNames; ++i) + for (const AZStd::string& layoutName : mLayoutNames) { - QAction* action = mLayoutsMenu->addAction(mLayoutNames[i].c_str()); + QAction* action = mLayoutsMenu->addAction(layoutName.c_str()); connect(action, &QAction::triggered, this, &MainWindow::OnLoadLayout); } // add the separator only if at least one layout - if (numLayoutNames > 0) + if (!mLayoutNames.empty()) { mLayoutsMenu->addSeparator(); } @@ -1880,22 +1879,22 @@ namespace EMStudio connect(saveCurrentAction, &QAction::triggered, this, &MainWindow::OnLayoutSaveAs); // remove menu is needed only if at least one layout - if (numLayoutNames > 0) + if (!mLayoutNames.empty()) { // add the remove menu QMenu* removeMenu = mLayoutsMenu->addMenu("Remove"); removeMenu->setObjectName("RemoveMenu"); // add each layout in the remove menu - for (uint32 i = 0; i < numLayoutNames; ++i) + for (const AZStd::string& layoutName : mLayoutNames) { // 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); } } @@ -1905,9 +1904,9 @@ namespace EMStudio // update the combo box mApplicationMode->clear(); - for (uint32 i = 0; i < numLayoutNames; ++i) + for (const AZStd::string& layoutName : mLayoutNames) { - mApplicationMode->addItem(mLayoutNames[i].c_str()); + mApplicationMode->addItem(layoutName.c_str()); } // update the current selection of combo box @@ -2055,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) { @@ -2080,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) { @@ -2279,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(); @@ -2320,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()) @@ -2465,8 +2464,8 @@ namespace EMStudio // 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(); @@ -2757,8 +2756,8 @@ namespace EMStudio } else if (dirtyObjects[i].mAnimGraph) { - 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].mAnimGraph); + 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) @@ -2803,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/MorphTargetSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.cpp index 47b282824a..e189b98dcf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.cpp @@ -90,8 +90,8 @@ namespace EMStudio mSelection = 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(); 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..a5e3a64f1f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.cpp @@ -116,8 +116,8 @@ namespace EMStudio 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); @@ -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); } @@ -303,21 +303,19 @@ namespace EMStudio { // Get the selected items in the tree widget. QList selectedItems = mHierarchy->selectedItems(); - const uint32 numSelectedItems = selectedItems.count(); // Reset the selection. mSelected.clear(); - mSelected.reserve(numSelectedItems); + mSelected.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); 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 4dabd18e5c..55f7324b75 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp @@ -156,8 +156,8 @@ namespace EMStudio 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); @@ -187,11 +187,10 @@ namespace EMStudio mHierarchy->clear(); // get the number actor instances and iterate over them - const uint32 numActorInstances = mActorInstanceIDs.size(); - for (uint32 i = 0; i < numActorInstances; ++i) + for (const uint32 mActorInstanceID : mActorInstanceIDs) { // get the actor instance by its id - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(mActorInstanceIDs[i]); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(mActorInstanceID); if (actorInstance) { AddActorInstance(actorInstance); @@ -241,7 +240,7 @@ namespace EMStudio // get the number of root nodes and iterate through them const size_t numRootNodes = actor->GetSkeleton()->GetNumRootNodes(); - for (uint32 i = 0; i < numRootNodes; ++i) + for (size_t i = 0; i < numRootNodes; ++i) { // get the root node index and the corresponding node const size_t rootNodeIndex = actor->GetSkeleton()->GetRootNodeIndex(i); @@ -349,7 +348,7 @@ namespace EMStudio 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 size_t childIndex = node->GetChildIndex(i); @@ -362,7 +361,7 @@ 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 size_t childIndex = node->GetChildIndex(i); @@ -470,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)); } @@ -480,33 +479,20 @@ 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(); // remove the unselected tree widget items from the selected nodes - const uint32 numTopLevelItems = mHierarchy->topLevelItemCount(); - for (i = 0; i < numTopLevelItems; ++i) + const int numTopLevelItems = mHierarchy->topLevelItemCount(); + for (int i = 0; i < numTopLevelItems; ++i) { RecursiveRemoveUnselectedItems(mHierarchy->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 + // get the item name FromQtString(item->text(0), &mItemName); FromQtString(item->whatsThis(0), &mActorInstanceIDString); @@ -644,32 +630,20 @@ namespace EMStudio // 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.mActorInstanceID == 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.mActorInstanceID == actorInstanceID && selectedItem.GetNodeNameString().empty(); + }); } @@ -685,15 +659,12 @@ namespace EMStudio m_selectedNodes.clear(); // get the number actor instances and iterate over them - const uint32 numActorInstances = mActorInstanceIDs.size(); - for (uint32 i = 0; i < numActorInstances; ++i) + for (const uint32 actorInstanceID : mActorInstanceIDs) { // 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) @@ -725,12 +696,6 @@ namespace EMStudio return mFilterState.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/NotificationWindowManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp index 9eb2c7f23e..d203e4386b 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.size(); - for (uint32 i = 0; i < numNotificationWindows; ++i) + for (const NotificationWindow* mNotificationWindow : mNotificationWindows) { - allNotificationWindowsHeight += mNotificationWindows[i]->geometry().height() + notificationWindowSpacing; + allNotificationWindowsHeight += mNotificationWindow->geometry().height() + notificationWindowSpacing; } // move the notification window @@ -82,16 +81,15 @@ namespace EMStudio // move each notification window int currentNotificationWindowHeight = notificationWindowMainWindowPadding; - const uint32 numNotificationWindows = mNotificationWindows.size(); - for (uint32 i = 0; i < numNotificationWindows; ++i) + for (NotificationWindow* mNotificationWindow : mNotificationWindows) { // add the height of the notification window - currentNotificationWindowHeight += mNotificationWindows[i]->geometry().height(); + currentNotificationWindowHeight += mNotificationWindow->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 = mNotificationWindow->geometry(); + mNotificationWindow->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/RenderPlugin/ManipulatorCallbacks.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/ManipulatorCallbacks.cpp index df54968f0c..750de85344 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,8 +21,8 @@ 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(mActorInstance); + if (actorInstanceID != InvalidIndex) { mActorInstance->SetLocalSpacePosition(value); } @@ -31,8 +31,8 @@ namespace EMStudio 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(mActorInstance); + if (actorInstanceID != InvalidIndex) { mOldValueVec = mActorInstance->GetLocalSpaceTransform().mPosition; } @@ -66,8 +66,8 @@ 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(mActorInstance); + if (actorInstanceID != InvalidIndex) { // temporarily update the actor instance mActorInstance->SetLocalSpaceRotation(value * mActorInstance->GetLocalSpaceTransform().mRotation.GetNormalized()); @@ -80,8 +80,8 @@ namespace EMStudio 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(mActorInstance); + if (actorInstanceID != InvalidIndex) { mOldValueQuat = mActorInstance->GetLocalSpaceTransform().mRotation; } @@ -117,8 +117,8 @@ namespace EMStudio AZ::Vector3 ScaleManipulatorCallback::GetCurrValueVec() { - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + if (actorInstanceID != InvalidIndex) { #ifndef EMFX_SCALE_DISABLED return mActorInstance->GetLocalSpaceTransform().mScale; @@ -137,8 +137,8 @@ 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(mActorInstance); + if (actorInstanceID != InvalidIndex) { float minScale = 0.001f; const AZ::Vector3 scale = AZ::Vector3( @@ -159,8 +159,8 @@ 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(mActorInstance); + if (actorInstanceID != InvalidIndex) { mOldValueVec = mActorInstance->GetLocalSpaceTransform().mScale; } 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 abbb9b7d81..506605fec4 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 @@ -128,12 +128,11 @@ namespace EMStudio void RenderPlugin::CleanEMStudioActors() { // get rid of the actors - const uint32 numActors = mActors.size(); - for (uint32 i = 0; i < numActors; ++i) + for (EMStudioRenderActor* mActor : mActors) { - if (mActors[i]) + if (mActor) { - delete mActors[i]; + delete mActor; } } mActors.clear(); @@ -152,8 +151,8 @@ 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; @@ -167,7 +166,6 @@ namespace EMStudio { // get the current manipulator AZStd::vector* transformationManipulators = GetManager()->GetTransformationManipulators(); - const uint32 numGizmos = transformationManipulators->size(); // init the active manipulator to nullptr MCommon::TransformationManipulator* activeManipulator = nullptr; @@ -175,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->at(i); if (currentManipulator == nullptr || currentManipulator->GetIsVisible() == false) { continue; @@ -275,8 +272,8 @@ namespace EMStudio const AZ::Vector3 jointPosition = pose->GetWorldSpaceTransform(joint->GetNodeIndex()).mPosition; aabb.AddPoint(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; @@ -314,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.size(); - for (uint32 i = 0; i < numEMStudioRenderActors; ++i) + const auto foundActor = AZStd::find_if(begin(mActors), end(mActors), [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->mActor == 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.size(); - for (uint32 a = 0; a < numActorInstances; ++a) - { - if (EMStudioRenderActor->mActorInstances[a] == actorInstance) - { - return EMStudioRenderActor; - } - } - } - else - { - return EMStudioRenderActor; + const auto foundActorInstance = AZStd::find(begin(renderActor->mActorInstances), end(renderActor->mActorInstances), actorInstance); + return foundActorInstance != end(renderActor->mActorInstances); } + return true; } - } - - return nullptr; + return false; + }); + return foundActor != end(mActors) ? *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.size(); - for (uint32 i = 0; i < numEMStudioRenderActors; ++i) + const auto foundActor = AZStd::find_if(begin(mActors), end(mActors), [match = actor](const EMStudioRenderActor* actor) { - EMStudioRenderActor* EMStudioRenderActor = mActors[i]; - - if (EMStudioRenderActor->mActor == actor) - { - return EMStudioRenderActor; - } - } - - return nullptr; + return actor->mActor == match; + }); + return foundActor != end(mActors) ? *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.size(); - 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(mActors), end(mActors), EMStudioRenderActor); + return foundActor != end(mActors) ? AZStd::distance(begin(mActors), foundActor) : InvalidIndex; } @@ -417,8 +383,8 @@ namespace EMStudio } // 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); @@ -438,13 +404,13 @@ namespace EMStudio } } - for (uint32 i = 0; i < mActors.size(); ++i) + for (size_t i = 0; i < mActors.size(); ++i) { EMStudioRenderActor* emstudioActor = mActors[i]; EMotionFX::Actor* actor = emstudioActor->mActor; 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) @@ -462,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(); @@ -476,9 +442,8 @@ namespace EMStudio if (!emstudioActor) { - for (uint32 j = 0; j < mActors.size(); ++j) + for (EMStudioRenderActor* currentEMStudioActor : mActors) { - EMStudioRenderActor* currentEMStudioActor = mActors[j]; if (actor == currentEMStudioActor->mActor) { emstudioActor = currentEMStudioActor; @@ -503,12 +468,12 @@ namespace EMStudio // 4. Unlink invalid actor instances from the emstudio actors for (EMStudioRenderActor* emstudioActor : mActors) { - for (uint32 j = 0; j < emstudioActor->mActorInstances.size();) + for (size_t j = 0; j < emstudioActor->mActorInstances.size();) { EMotionFX::ActorInstance* emstudioActorInstance = emstudioActor->mActorInstances[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)) { @@ -566,14 +531,11 @@ namespace EMStudio RenderPlugin::EMStudioRenderActor::~EMStudioRenderActor() { // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.size(); - for (uint32 i = 0; i < numActorInstances; ++i) + for (EMotionFX::ActorInstance* actorInstance : mActorInstances) { - 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(); } @@ -587,13 +549,9 @@ 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(mActor) == 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); } @@ -810,8 +768,8 @@ namespace EMStudio 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); @@ -889,8 +847,8 @@ namespace EMStudio } // 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); @@ -1045,10 +1003,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); @@ -1080,7 +1038,7 @@ namespace EMStudio } else { - const uint32 numParticles = trajectoryPath->mTraceParticles.size(); + const size_t numParticles = trajectoryPath->mTraceParticles.size(); const EMotionFX::Transform& oldWorldTM = trajectoryPath->mTraceParticles[numParticles - 1].mWorldTM; const AZ::Vector3& oldPos = oldWorldTM.mPosition; @@ -1141,8 +1099,8 @@ 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)) @@ -1219,12 +1177,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)); - const AZ::u32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); EMotionFX::Mesh* mesh = emstudioActor->mActor->GetMesh(geomLODLevel, nodeIndex); renderUtil->ResetCurrentMesh(); 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 f55604b38c..a99a64ef68 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 @@ -106,9 +106,9 @@ namespace EMStudio PluginOptions* GetOptions() override { return &mRenderOptions; } // 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); 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 24b4471280..3c146c528b 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 @@ -90,7 +90,7 @@ namespace EMStudio } else { - const uint32 numParticles = trajectoryPath->mTraceParticles.size(); + const size_t numParticles = trajectoryPath->mTraceParticles.size(); const EMotionFX::Transform& oldGlobalTM = trajectoryPath->mTraceParticles[numParticles - 1].mWorldTM; const AZ::Vector3& oldPos = oldGlobalTM.mPosition; @@ -160,8 +160,8 @@ namespace EMStudio RenderViewWidget* widget = mPlugin->GetActiveViewWidget(); RenderOptions* renderOptions = mPlugin->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)) @@ -216,9 +216,9 @@ 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()); 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 b123f62ac5..56d27222bb 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 @@ -256,10 +256,8 @@ namespace EMStudio const AZStd::vector* transformationManipulators = GetManager()->GetTransformationManipulators(); // render all visible gizmos - const uint32 numGizmos = transformationManipulators->size(); - for (uint32 i = 0; i < numGizmos; ++i) + for (MCommon::TransformationManipulator* activeManipulator : *transformationManipulators) { - MCommon::TransformationManipulator* activeManipulator = transformationManipulators->at(i); if (activeManipulator == nullptr) { continue; @@ -527,10 +525,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()) @@ -557,8 +555,8 @@ namespace EMStudio const MCore::Ray ray = mCamera->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()) @@ -622,8 +620,8 @@ namespace EMStudio 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.emplace_back(selection.GetActorInstance(i)); } @@ -922,8 +920,8 @@ namespace EMStudio 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); @@ -1007,14 +1005,10 @@ namespace EMStudio } AZStd::vector* transformationManipulators = GetManager()->GetTransformationManipulators(); - const uint32 numGizmos = transformationManipulators->size(); // render all visible gizmos - for (uint32 i = 0; i < numGizmos; ++i) + for (MCommon::TransformationManipulator* activeManipulator : *transformationManipulators) { - // update the gizmos - MCommon::TransformationManipulator* activeManipulator = transformationManipulators->at(i); - // update the gizmos if there is an active manipulator if (activeManipulator == nullptr) { @@ -1046,11 +1040,9 @@ namespace EMStudio } // render custom triangles - const uint32 numTriangles = mTriangles.size(); - for (uint32 i = 0; i < numTriangles; ++i) + for (const Triangle& curTri : mTriangles) { - 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.mPosA, curTri.mPosB, curTri.mPosC, curTri.mNormalA, curTri.mNormalB, curTri.mNormalC, curTri.mColor); // TODO: make renderutil use uint32 colors instead } ClearTriangles(); @@ -1068,8 +1060,8 @@ namespace EMStudio } // 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); @@ -1131,8 +1123,8 @@ 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) 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/Workspace.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.cpp index 9919c4cbb3..a791b17e25 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.cpp @@ -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) @@ -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); 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 e99838b7bb..ac23dd489b 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 @@ -42,8 +42,8 @@ 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) + const size_t numParameters = commandLine.GetNumParameters(); + for (size_t i = 0; i < numParameters; ++i) { mTempString += " -"; mTempString += commandLine.GetParameterName(i); @@ -130,8 +130,8 @@ namespace EMStudio MCORE_UNUSED(commandLine); mTempString = MCore::CommandManager::CommandHistoryEntry::ToString(group, command, mIndex++).c_str(); - mList->insertItem(historyIndex, new QListWidgetItem(mTempString.c_str(), mList)); - mList->setCurrentRow(historyIndex); + mList->insertItem(aznumeric_caster(historyIndex), new QListWidgetItem(mTempString.c_str(), mList)); + mList->setCurrentRow(aznumeric_caster(historyIndex)); } // Remove an item from the history. @@ -168,7 +168,7 @@ namespace EMStudio mList->setCurrentRow(aznumeric_caster(index)); // Get the current history index. - const uint32 historyIndex = GetCommandManager()->GetHistoryIndex(); + const size_t historyIndex = GetCommandManager()->GetHistoryIndex(); if (historyIndex == InvalidIndex) { AZStd::string outResult; @@ -189,8 +189,8 @@ 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(); @@ -207,8 +207,8 @@ 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); @@ -223,7 +223,7 @@ namespace EMStudio } 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); } 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..9a4170d1b0 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 @@ -210,8 +210,8 @@ namespace EMStudio defaultPlayBackInfo->mBlendOutTime = 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..f6e308f07b 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 @@ -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,7 +301,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(); AnimGraphEditor::m_lastMotionSetText = m_motionSetComboBox->itemText(index); // if no one actor instance is selected, the combo box has no effect @@ -310,7 +310,7 @@ namespace EMotionFX 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..1d17c46815 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,7 +51,7 @@ namespace EMotionFX void OnMotionSetChanged(int index); private: - AZ::Outcome GetMotionSetIndex(int comboBoxIndex) const; + AZ::Outcome GetMotionSetIndex(int comboBoxIndex) const; MCORE_DEFINECOMMANDCALLBACK(UpdateMotionSetComboBoxCallback) 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..5de2b58905 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 @@ -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 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 5026af3b06..62c0fe0a14 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); @@ -147,11 +147,9 @@ 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) { continue; @@ -429,19 +427,17 @@ namespace EMStudio void AnimGraphPlugin::SetOptionFlag(EDockWindowOptionFlag option, bool isEnabled) { - const uint32 optionIndex = (uint32)option; - if (mDockWindowActions[optionIndex]) + if (mDockWindowActions[option]) { - mDockWindowActions[optionIndex]->setChecked(isEnabled); + mDockWindowActions[option]->setChecked(isEnabled); } } void AnimGraphPlugin::SetOptionEnabled(EDockWindowOptionFlag option, bool isEnabled) { - const uint32 optionIndex = (uint32)option; - if (mDockWindowActions[optionIndex]) + if (mDockWindowActions[option]) { - mDockWindowActions[optionIndex]->setEnabled(isEnabled); + mDockWindowActions[option]->setEnabled(isEnabled); } } @@ -739,8 +735,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); @@ -787,20 +783,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 +796,10 @@ namespace EMStudio const AZStd::string& paramName = animGraphInstance->GetAnimGraph()->FindParameter(paramIndex)->GetName(); // iterate over all gizmos that are active - AZStd::vector* gizmos = manager->GetTransformationManipulators(); - const uint32 numGizmos = gizmos->size(); - for (uint32 i = 0; i < numGizmos; ++i) + const AZStd::vector* gizmos = manager->GetTransformationManipulators(); + for (MCommon::TransformationManipulator* gizmo : *gizmos) { - MCommon::TransformationManipulator* gizmo = gizmos->at(i); - - // check the gizmo name + // check the gizmo name if (paramName == gizmo->GetName()) { gizmo->SetRenderOffset(offset); @@ -835,8 +820,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 +912,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 +923,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); @@ -1059,8 +1044,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 +1059,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 +1086,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; } @@ -1146,8 +1131,8 @@ namespace EMStudio 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; @@ -1176,7 +1161,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 +1187,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 +1207,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 +1239,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()) 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 ad4098308d..af6fcde3d6 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 @@ -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; @@ -135,7 +135,7 @@ namespace EMStudio void SetActiveAnimGraph(EMotionFX::AnimGraph* animGraph); EMotionFX::AnimGraph* GetActiveAnimGraph() { return mActiveAnimGraph; } - 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); 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..037d75a9b9 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 @@ -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/BlendGraphWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp index 8a4a338b6e..edf5579720 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 @@ -810,7 +810,7 @@ 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); @@ -845,8 +845,8 @@ 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) @@ -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); GraphNode* realSourceNode; GraphNode* realTargetNode; - uint32 realInputPortNr; - uint32 realOutputPortNr; + AZ::u16 realInputPortNr; + AZ::u16 realOutputPortNr; if (sourceIsInputPort) { @@ -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) 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..fa0801cdc1 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); 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 43225692ac..0cf44af794 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 @@ -39,9 +39,9 @@ namespace EMStudio // add all input ports const AZStd::vector& inPorts = mEMFXNode->GetInputPorts(); - const uint32 numInputs = static_cast(inPorts.size()); + const AZ::u16 numInputs = aznumeric_caster(inPorts.size()); mInputPorts.reserve(numInputs); - for (uint32 i = 0; i < numInputs; ++i) + for (AZ::u16 i = 0; i < numInputs; ++i) { NodePort* port = AddInputPort(false); port->SetNameID(inPorts[i].mNameID); @@ -52,9 +52,9 @@ namespace EMStudio { // add all output ports const AZStd::vector& outPorts = mEMFXNode->GetOutputPorts(); - const uint32 numOutputs = static_cast(outPorts.size()); + const AZ::u16 numOutputs = aznumeric_caster(outPorts.size()); mOutputPorts.reserve(numOutputs); - for (uint32 i = 0; i < numOutputs; ++i) + for (AZ::u16 i = 0; i < numOutputs; ++i) { NodePort* port = AddOutputPort(false); port->SetNameID(outPorts[i].mNameID); @@ -73,8 +73,8 @@ namespace EMStudio GraphNode* source = mParentGraph->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); target->AddConnection(visualConnection); @@ -302,8 +302,8 @@ namespace EMStudio { // draw the input ports QColor portBrushColor, portPenColor; - const uint32 numInputs = mInputPorts.size(); - for (uint32 i = 0; i < numInputs; ++i) + const AZ::u16 numInputs = aznumeric_caster(mInputPorts.size()); + for (AZ::u16 i = 0; i < numInputs; ++i) { // get the input port and the corresponding rect NodePort* inputPort = &mInputPorts[i]; @@ -321,8 +321,8 @@ namespace EMStudio if (GetHasVisualOutputPorts()) { // draw the output ports - const uint32 numOutputs = mOutputPorts.size(); - for (uint32 i = 0; i < numOutputs; ++i) + const AZ::u16 numOutputs = aznumeric_caster(mOutputPorts.size()); + for (AZ::u16 i = 0; i < numOutputs; ++i) { // get the output port and the corresponding rect NodePort* outputPort = &mOutputPorts[i]; @@ -455,8 +455,8 @@ namespace EMStudio painter.setFont(mPortNameFont); // draw input port text - const uint32 numInputs = mInputPorts.size(); - for (uint32 i = 0; i < numInputs; ++i) + const AZ::u16 numInputs = aznumeric_caster(mInputPorts.size()); + for (AZ::u16 i = 0; i < numInputs; ++i) { NodePort* inputPort = &mInputPorts[i]; const QRect& portRect = inputPort->GetRect(); @@ -468,8 +468,8 @@ namespace EMStudio } // draw output port text - const uint32 numOutputs = mOutputPorts.size(); - for (uint32 i = 0; i < numOutputs; ++i) + const AZ::u16 numOutputs = aznumeric_caster(mOutputPorts.size()); + for (AZ::u16 i = 0; i < numOutputs; ++i) { NodePort* outputPort = &mOutputPorts[i]; const QRect& portRect = outputPort->GetRect(); 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..da092f93f6 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 @@ -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); 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..c1d0d25c9e 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 @@ -559,7 +559,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..f1ee2e0e9d 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 @@ -78,7 +78,7 @@ public: void SetDeadZone(float deadZone) { mDeadZone = deadZone; } MCORE_INLINE float GetDeadZone() const { return mDeadZone; } 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 GetIsButtonPressed(uint8 buttonIndex) const 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 5ce488ee70..eeb765ce54 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 @@ -327,7 +327,7 @@ namespace EMStudio 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"); @@ -345,14 +345,13 @@ namespace EMStudio mParameterGridLayout->setMargin(0); // add all parameters - // uint32 startRow = 0; mParameterInfos.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()); + mParameterInfos.reserve(numParameters); - for (size_t parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex) + for (int parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex) { const EMotionFX::ValueParameter* parameter = parameters[parameterIndex]; @@ -599,16 +598,16 @@ namespace EMStudio mPresetComboBox->blockSignals(true); mPresetComboBox->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()); } // 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); + mPresetComboBox->setCurrentIndex(aznumeric_caster(activePresetIndex)); } mPresetComboBox->blockSignals(false); @@ -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.size(); - for (uint32 i = 0; i < numButtonInfos; ++i) + const auto foundButtonInfo = AZStd::find_if(begin(mButtonInfos), end(mButtonInfos), [widget](const ButtonInfo& buttonInfo) { - if (mButtonInfos[i].mWidget == widget) - { - return &mButtonInfos[i]; - } - } - - // return failure - return nullptr; + return buttonInfo.mWidget == widget; + }); + return foundButtonInfo != end(mButtonInfos) ? &(*foundButtonInfo) : nullptr; } GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByModeComboBox(QComboBox* comboBox) { // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.size(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [comboBox](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mMode == comboBox) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.mMode == comboBox; + }); + return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -736,17 +723,11 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindButtonInfoByAttributeInfo(const EMotionFX::Parameter* parameter) { // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.size(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [parameter](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mParameter == parameter) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.mParameter == parameter; + }); + return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -1053,12 +1034,12 @@ namespace EMStudio // get the game controller settings from the current anim graph EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->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(); + mString = AZStd::string::format("Preset %zu", presetNumber); + while (gameControllerSettings.FindPresetIndexByName(mString.c_str()) != InvalidIndex) { presetNumber++; - mString = AZStd::string::format("Preset %d", presetNumber); + mString = AZStd::string::format("Preset %zu", presetNumber); } EMotionFX::AnimGraphGameControllerSettings::Preset* preset = aznew EMotionFX::AnimGraphGameControllerSettings::Preset(mString.c_str()); @@ -1123,8 +1104,8 @@ namespace EMStudio // get the currently selected preset uint32 presetIndex = mPresetComboBox->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()); @@ -1139,8 +1120,8 @@ namespace EMStudio EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->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); } @@ -1153,18 +1134,11 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByAxisComboBox(QComboBox* comboBox) { - // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.size(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [comboBox](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mAxis == comboBox) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.mAxis == comboBox; + }); + return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -1195,7 +1169,7 @@ namespace EMStudio #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER if (azrtti_istypeof(paramInfo->mParameter)) { - const uint32 elementID = mGameController->FindElemendIDByName(FromQtString(combo->currentText()).c_str()); + const uint32 elementID = mGameController->FindElementIDByName(FromQtString(combo->currentText()).c_str()); if (elementID >= MCORE_INVALIDINDEX8) { settingsInfo->m_axis = MCORE_INVALIDINDEX8; @@ -1231,18 +1205,11 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByCheckBox(QCheckBox* checkBox) { - // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.size(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [checkBox](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mInvert == checkBox) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.mInvert == checkBox; + }); + return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -1675,7 +1642,7 @@ namespace EMStudio 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) { 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 f0c06bc7e0..f6b0b72bf6 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 @@ -22,7 +22,7 @@ namespace EMStudio // 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) { mRect = QRect(0, 0, 200, 128); @@ -119,9 +119,9 @@ namespace EMStudio mInfoText.prepare(QTransform(), mSubTitleFont); // input ports - const uint32 numInputs = mInputPorts.size(); + const size_t numInputs = mInputPorts.size(); mInputPortText.resize(numInputs); - for (uint32 i = 0; i < numInputs; ++i) + for (size_t i = 0; i < numInputs; ++i) { QStaticText& staticText = mInputPortText[i]; staticText.setTextFormat(Qt::PlainText); @@ -132,9 +132,9 @@ namespace EMStudio } // output ports - const uint32 numOutputs = mOutputPorts.size(); + const size_t numOutputs = mOutputPorts.size(); mOutputPortText.resize(numOutputs); - for (uint32 i = 0; i < numOutputs; ++i) + for (size_t i = 0; i < numOutputs; ++i) { QStaticText& staticText = mOutputPortText[i]; staticText.setTextFormat(Qt::PlainText); @@ -143,104 +143,15 @@ namespace EMStudio staticText.setText(mOutputPorts[i].GetName()); staticText.prepare(QTransform(), mPortNameFont); } - - //------------------------------------------- - /* - // 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.size(); - for (uint32 i = 0; i < numConnections; ++i) + for (NodeConnection* mConnection : mConnections) { - delete mConnections[i]; + delete mConnection; } mConnections.clear(); @@ -333,17 +244,16 @@ namespace EMStudio mVisualizeRect.setCoords(mRect.right() - 13, mRect.top() + 6, mRect.right() - 5, mRect.top() + 14); // update the input ports and reset the port highlight flags - uint32 i; - const uint32 numInputPorts = mInputPorts.size(); - for (i = 0; i < numInputPorts; ++i) + const AZ::u16 numInputPorts = aznumeric_caster(mInputPorts.size()); + for (AZ::u16 i = 0; i < numInputPorts; ++i) { mInputPorts[i].SetRect(CalcInputPortRect(i)); mInputPorts[i].SetIsHighlighted(false); } // update the output ports and reset the port highlight flags - const uint32 numOutputPorts = mOutputPorts.size(); - for (i = 0; i < numOutputPorts; ++i) + const AZ::u16 numOutputPorts = aznumeric_caster(mOutputPorts.size()); + for (AZ::u16 i = 0; i < numOutputPorts; ++i) { mOutputPorts[i].SetRect(CalcOutputPortRect(i)); mOutputPorts[i].SetIsHighlighted(false); @@ -367,16 +277,15 @@ namespace EMStudio { // set the set highlight flags for the input ports bool highlightedPortFound = false; - for (i = 0; i < numInputPorts; ++i) + for (NodePort& inputPort : mInputPorts) { // 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; } @@ -386,16 +295,15 @@ namespace EMStudio if (highlightedPortFound == false) { // set the set highlight flags for the output ports - for (i = 0; i < numOutputPorts; ++i) + for (NodePort& outputPort : mOutputPorts) { // 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; } } @@ -403,8 +311,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); } @@ -570,8 +478,8 @@ namespace EMStudio // draw the input ports QColor portBrushColor, portPenColor; - const uint32 numInputs = mInputPorts.size(); - for (uint32 i = 0; i < numInputs; ++i) + const AZ::u16 numInputs = aznumeric_caster(mInputPorts.size()); + for (AZ::u16 i = 0; i < numInputs; ++i) { // get the input port and the corresponding rect NodePort* inputPort = &mInputPorts[i]; @@ -595,8 +503,8 @@ namespace EMStudio if (GetHasVisualOutputPorts()) { // draw the output ports - const uint32 numOutputs = mOutputPorts.size(); - for (uint32 i = 0; i < numOutputs; ++i) + const AZ::u16 numOutputs = aznumeric_caster(mOutputPorts.size()); + for (AZ::u16 i = 0; i < numOutputs; ++i) { // get the output port and the corresponding rect NodePort* outputPort = &mOutputPorts[i]; @@ -823,10 +731,8 @@ namespace EMStudio const bool alwaysColor = GetAlwaysColor(); // for all connections - const uint32 numConnections = mConnections.size(); - for (uint32 c = 0; c < numConnections; ++c) + for (NodeConnection* nodeConnection : mConnections) { - NodeConnection* nodeConnection = mConnections[c]; if (nodeConnection->GetIsVisible()) { float opacity = 1.0f; @@ -982,14 +888,14 @@ namespace EMStudio } // 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); } // 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); } @@ -1010,7 +916,7 @@ namespace EMStudio // 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) { @@ -1024,7 +930,7 @@ namespace EMStudio // 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) { @@ -1076,32 +982,10 @@ namespace EMStudio return &mOutputPorts.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) { @@ -1117,8 +1001,8 @@ namespace EMStudio // check the input ports if (includeInputPorts) { - const uint32 numInputPorts = mInputPorts.size(); - for (i = 0; i < numInputPorts; ++i) + const AZ::u16 numInputPorts = aznumeric_caster(mInputPorts.size()); + for (AZ::u16 i = 0; i < numInputPorts; ++i) { QRect rect = CalcInputPortRect(i); if (rect.contains(QPoint(x, y))) @@ -1131,8 +1015,8 @@ namespace EMStudio } // check the output ports - const uint32 numOutputPorts = mOutputPorts.size(); - for (i = 0; i < numOutputPorts; ++i) + const AZ::u16 numOutputPorts = aznumeric_caster(mOutputPorts.size()); + for (AZ::u16 i = 0; i < numOutputPorts; ++i) { QRect rect = CalcOutputPortRect(i); if (rect.contains(QPoint(x, y))) @@ -1149,42 +1033,44 @@ namespace EMStudio // remove a given connection bool GraphNode::RemoveConnection(const void* connection, bool removeFromMemory) { - const uint32 numConnections = mConnections.size(); - for (uint32 i = 0; i < numConnections; ++i) + const auto foundConnection = AZStd::find_if(begin(mConnections), end(mConnections), [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.erase(AZStd::next(begin(mConnections), i)); - return true; - } + return connection->GetModelIndex().data(AnimGraphModel::ROLE_POINTER).value() == match; + }); + + if (foundConnection == end(mConnections)) + { + return false; } - return false; + + if (removeFromMemory) + { + delete *foundConnection; + } + mConnections.erase(foundConnection); + return true; } // Remove a given connection by model index bool GraphNode::RemoveConnection(const QModelIndex& modelIndex, bool removeFromMemory) { - const uint32 numConnections = mConnections.size(); - for (uint32 i = 0; i < numConnections; ++i) + const auto foundConnection = AZStd::find_if(begin(mConnections), end(mConnections), [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.erase(AZStd::next(begin(mConnections), i)); - return true; - } + return connection->GetModelIndex() == match; + }); + + if (foundConnection == end(mConnections)) + { + return false; + } + + if (removeFromMemory) + { + delete *foundConnection; } - return false; + mConnections.erase(foundConnection); + return true; } 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 061444f9d1..125317408d 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 @@ -78,7 +78,7 @@ 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; } @@ -86,12 +86,12 @@ namespace EMStudio MCORE_INLINE void UpdateNameAndPorts() { mNameAndPortsUpdated = false; } MCORE_INLINE AZStd::vector& GetConnections() { return mConnections; } MCORE_INLINE size_t GetNumConnections() { return mConnections.size(); } - MCORE_INLINE NodeConnection* GetConnection(uint32 index) { return mConnections[index]; } + MCORE_INLINE NodeConnection* GetConnection(size_t index) { return mConnections[index]; } MCORE_INLINE NodeConnection* AddConnection(NodeConnection* con) { mConnections.emplace_back(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 NodePort* GetInputPort(AZ::u16 index) { return &mInputPorts[index]; } + MCORE_INLINE NodePort* GetOutputPort(AZ::u16 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; } @@ -134,8 +134,8 @@ namespace EMStudio MCORE_INLINE float GetOpacity() const { return mOpacity; } MCORE_INLINE void SetOpacity(float opacity) { mOpacity = opacity; } - size_t GetNumInputPorts() const { return mInputPorts.size(); } - size_t GetNumOutputPorts() const { return mOutputPorts.size(); } + AZ::u16 GetNumInputPorts() const { return aznumeric_caster(mInputPorts.size()); } + AZ::u16 GetNumOutputPorts() const { return aznumeric_caster(mOutputPorts.size()); } NodePort* AddInputPort(bool updateTextPixMap); NodePort* AddOutputPort(bool updateTextPixMap); @@ -173,9 +173,9 @@ 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; } @@ -188,8 +188,8 @@ namespace EMStudio 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; } 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..cefbb0d0af 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,7 +17,7 @@ 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) { 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..2e305dbd0c 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; @@ -62,8 +62,8 @@ namespace EMStudio MCORE_INLINE bool GetIsVisible() { return mIsVisible; } - MCORE_INLINE uint32 GetInputPortNr() const { return mPortNr; } - MCORE_INLINE uint32 GetOutputPortNr() const { return mSourcePortNr; } + MCORE_INLINE AZ::u16 GetInputPortNr() const { return mPortNr; } + MCORE_INLINE AZ::u16 GetOutputPortNr() const { return mSourcePortNr; } MCORE_INLINE GraphNode* GetSourceNode() { return mSourceNode; } MCORE_INLINE GraphNode* GetTargetNode() { return mTargetNode; } @@ -103,7 +103,7 @@ namespace EMStudio void SetSourceNode(GraphNode* node) { mSourceNode = node; } void SetTargetNode(GraphNode* node) { mTargetNode = node; } - void SetTargetPort(uint32 portIndex) { mPortNr = portIndex; } + void SetTargetPort(AZ::u16 portIndex) { mPortNr = portIndex; } protected: @@ -115,8 +115,8 @@ namespace EMStudio 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 + AZ::u16 mPortNr; // input port where this is connected to + AZ::u16 mSourcePortNr; // source output port number bool mIsVisible; // is this connection visible? bool mIsProcessed; // is this connection processed? bool mIsDisabled; 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 39a9a0630d..37ec2cfd8b 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 @@ -54,7 +55,7 @@ namespace EMStudio // init connection creation mConStartOffset = QPoint(0, 0); mConEndOffset = QPoint(0, 0); - mConPortNr = MCORE_INVALIDINDEX32; + mConPortNr = InvalidIndex16; mConIsInputPort = true; mConNode = nullptr; // nullptr when no connection is being created mConPort = nullptr; @@ -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()) @@ -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 @@ -606,8 +607,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 +633,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(); @@ -797,28 +798,6 @@ namespace EMStudio #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) @@ -898,8 +877,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 +949,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); @@ -1217,20 +1196,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 +1225,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 +1254,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(); } @@ -1499,7 +1470,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,7 +1498,7 @@ 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; @@ -1538,7 +1509,7 @@ namespace EMStudio // 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; @@ -1604,7 +1575,7 @@ namespace EMStudio // reset members void NodeGraph::StopRelinkConnection() { - mConPortNr = MCORE_INVALIDINDEX32; + mConPortNr = InvalidIndex16; mConNode = nullptr; mRelinkConnection = nullptr; mConIsValid = false; @@ -1616,7 +1587,7 @@ namespace EMStudio // reset members void NodeGraph::StopCreateConnection() { - mConPortNr = MCORE_INVALIDINDEX32; + mConPortNr = InvalidIndex16; mConIsInputPort = true; mConNode = nullptr; // nullptr when no connection is being created mConPort = nullptr; @@ -1640,8 +1611,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 +1643,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,8 +1669,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 (CheckIfIsRelinkConnectionValid(mRelinkConnection, node, i, true)) { @@ -1778,8 +1746,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 +1761,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)) { @@ -1864,10 +1832,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 +1856,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 +1935,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; @@ -2014,8 +1982,8 @@ namespace EMStudio for (const GraphNodeByModelIndex::value_type& target : m_graphNodeByModelIndex) { AZStd::vector& connections = target.second->GetConnections(); - const uint32 connectionsCount = connections.size(); - for (uint32 i = 0; i < connectionsCount; ++i) + const size_t connectionsCount = connections.size(); + for (size_t i = 0; i < connectionsCount; ++i) { if (connections[i]->GetType() == StateConnection::TYPE_ID) { @@ -2087,12 +2055,11 @@ namespace EMStudio bool foundConnection = false; AZStd::vector& connections = targetGraphNode->GetConnections(); - const uint32 connectionsCount = connections.size(); - for (uint32 i = 0; i < connectionsCount; ++i) + 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); @@ -2175,12 +2142,11 @@ namespace EMStudio for (const GraphNodeByModelIndex::value_type& target : m_graphNodeByModelIndex) { AZStd::vector& connections = target.second->GetConnections(); - const uint32 connectionsCount = connections.size(); - for (uint32 i = 0; i < connectionsCount; ++i) + 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; @@ -2204,12 +2170,11 @@ namespace EMStudio if (target) { AZStd::vector& connections = target->GetConnections(); - const uint32 connectionsCount = connections.size(); - for (uint32 i = 0; i < connectionsCount; ++i) + 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; @@ -2237,8 +2202,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) @@ -2253,8 +2218,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) @@ -2264,8 +2229,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) @@ -2285,12 +2250,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) @@ -2341,8 +2306,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); @@ -2458,8 +2423,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); @@ -2471,7 +2436,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; @@ -2483,7 +2448,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); 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..11490d8b49 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 @@ -81,24 +81,24 @@ namespace EMStudio GraphNode* GetCreateConnectionNode() { return mConNode; } NodeConnection* GetRelinkConnection() { return mRelinkConnection; } - uint32 GetCreateConnectionPortNr() const { return mConPortNr; } + AZ::u16 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; } - 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,7 +118,7 @@ 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; } @@ -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); @@ -197,7 +197,7 @@ namespace EMStudio // connection info QPoint mConStartOffset; QPoint mConEndOffset; - uint32 mConPortNr; + AZ::u16 mConPortNr; bool mConIsInputPort; GraphNode* mConNode; // nullptr when no connection is being created NodeConnection* mRelinkConnection; // nullptr when not relinking a connection 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..d7afe634a1 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 @@ -406,7 +406,7 @@ namespace EMStudio // 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); @@ -767,8 +767,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); } } @@ -810,7 +810,7 @@ namespace EMStudio // 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); if (port) @@ -824,18 +824,10 @@ namespace EMStudio 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(); return; } @@ -1054,7 +1046,7 @@ namespace EMStudio { if (mActiveGraph->GetIsCreateConnectionValid()) { - uint32 targetPortNr; + AZ::u16 targetPortNr; bool targetIsInputPort; GraphNode* targetNode; @@ -1096,7 +1088,7 @@ namespace EMStudio AZ_Assert(!mActiveGraph->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); @@ -1119,10 +1111,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)) { @@ -1412,7 +1404,7 @@ 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); @@ -1432,7 +1424,7 @@ 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); @@ -1551,21 +1543,18 @@ namespace EMStudio // return the number of selected nodes - uint32 NodeGraphWidget::CalcNumSelectedNodes() const + size_t NodeGraphWidget::CalcNumSelectedNodes() const { if (mActiveGraph) { return mActiveGraph->CalcNumSelectedNodes(); } - else - { - return 0; - } + 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); @@ -1608,7 +1597,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..d8b73ee5be 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 @@ -59,7 +59,7 @@ namespace EMStudio MCORE_INLINE void SetMousePos(const QPoint& pos) { mMousePos = pos; } MCORE_INLINE void SetShowFPS(bool showFPS) { mShowFPS = 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); } 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 51b170c5aa..3183bc8a0f 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 @@ -12,6 +12,7 @@ #include #include #include +#include "MCore/Source/Config.h" #include "NodeGroupWindow.h" #include "AnimGraphPlugin.h" #include "GraphNode.h" @@ -111,8 +112,8 @@ namespace EMStudio 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 = mAnimGraph->GetNumNodeGroups(); + for (size_t i = 0; i < numNodeGroups; ++i) { EMotionFX::AnimGraphNodeGroup* nodeGroup = mAnimGraph->GetNodeGroup(i); if (nodeGroup->GetNameString() == convertedNewName) @@ -285,13 +286,13 @@ namespace EMStudio const QList selectedItems = mTableWidget->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) + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = selectedItems[i]->row(); + const int rowIndex = selectedItems[i]->row(); const AZStd::string nodeGroupName = FromQtString(mTableWidget->item(rowIndex, 2)->text()); if (AZStd::find(begin(selectedNodeGroups), end(selectedNodeGroups), nodeGroupName) == end(selectedNodeGroups)) { @@ -315,7 +316,7 @@ namespace EMStudio mTableWidget->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); @@ -324,7 +325,7 @@ namespace EMStudio mTableWidget->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); @@ -452,19 +453,13 @@ 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.size(); - for (uint32 i = 0; i < numWidgets; ++i) + const auto foundGroup = AZStd::find_if(begin(mWidgetTable), end(mWidgetTable), [widget](const auto& tableEntry) { - if (mWidgetTable[i].mWidget == widget) // this is button we search for - { - return mWidgetTable[i].mGroupIndex; - } - } - - return MCORE_INVALIDINDEX32; + return tableEntry.mWidget == widget; + }); + return foundGroup != end(mWidgetTable) ? foundGroup->mGroupIndex : MCore::InvalidIndexT; } @@ -478,8 +473,8 @@ namespace EMStudio } // 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); @@ -516,8 +511,8 @@ namespace EMStudio } // 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); @@ -574,18 +569,18 @@ namespace EMStudio const QList selectedItems = mTableWidget->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 - AZStd::vector rowIndices; + AZStd::vector rowIndices; rowIndices.reserve(numSelectedItems); - for (uint32 i = 0; i < numSelectedItems; ++i) + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = selectedItems[i]->row(); + const int rowIndex = selectedItems[i]->row(); if (AZStd::find(begin(rowIndices), end(rowIndices), rowIndex) == end(rowIndices)) { rowIndices.emplace_back(rowIndex); @@ -597,7 +592,7 @@ namespace EMStudio AZStd::sort(begin(rowIndices), end(rowIndices)); // get the number of selected rows - const uint32 numRowIndices = rowIndices.size(); + const size_t numRowIndices = rowIndices.size(); // set the command group name AZStd::string commandGroupName; @@ -607,7 +602,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 @@ -615,7 +610,7 @@ 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()); if (i == 0 || i == numRowIndices - 1) @@ -636,7 +631,7 @@ namespace EMStudio } // selected the next row - if (rowIndices[0] > ((uint32)mTableWidget->rowCount() - 1)) + if (rowIndices[0] > (mTableWidget->rowCount() - 1)) { mTableWidget->selectRow(rowIndices[0] - 1); } @@ -723,18 +718,18 @@ namespace EMStudio const QList selectedItems = mTableWidget->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 - AZStd::vector rowIndices; + AZStd::vector rowIndices; rowIndices.reserve(numSelectedItems); - for (uint32 i = 0; i < numSelectedItems; ++i) + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = selectedItems[i]->row(); + const int rowIndex = selectedItems[i]->row(); if (AZStd::find(begin(rowIndices), end(rowIndices), rowIndex) == end(rowIndices)) { rowIndices.emplace_back(rowIndex); @@ -752,7 +747,7 @@ namespace EMStudio } // at least one selected, remove action is possible - if (rowIndices.size() > 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 5f0354b223..e19b831790 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 @@ -91,7 +91,7 @@ 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); @@ -105,7 +105,7 @@ namespace EMStudio struct WidgetLookup { QObject* mWidget; - uint32 mGroupIndex; + int mGroupIndex; }; AnimGraphPlugin* mPlugin; 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..9664011083 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 @@ -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)); } } @@ -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; @@ -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); @@ -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()); @@ -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/StateFilterSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.cpp index 3a43d640e0..b7abf10da0 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 @@ -98,9 +98,9 @@ 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; + const size_t numNodeGroups = animGraph->GetNumNodeGroups(); + const size_t numNodes = m_stateMachine->GetNumChildNodes(); + const int numRows = aznumeric_caster(numNodeGroups + numNodes); mTableWidget->setRowCount(numRows); // Block signals for the table widget to not reach OnSelectionChanged() when adding rows as that 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 0c4f8b8138..0ce567c366 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 @@ -830,13 +830,13 @@ namespace EMStudio 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); } - QRect StateGraphNode::CalcOutputPortRect(uint32 portNr) + QRect StateGraphNode::CalcOutputPortRect(AZ::u16 portNr) { switch (portNr) { 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..cee57b4a4f 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,7 +54,7 @@ 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); @@ -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 d84b22f5d5..78eab3d362 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 @@ -144,11 +145,11 @@ namespace EMStudio mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (mNodeTable->selectedItems().size() != 0)); // counter for attachment nodes - size_t numAttachmentNodes = 0; + int numAttachmentNodes = 0; // set the row count - const size_t numNodes = mActor->GetNumNodes(); - for (size_t i = 0; i < numNodes; ++i) + const int numNodes = aznumeric_caster(mActor->GetNumNodes()); + for (int i = 0; i < numNodes; ++i) { // get the nodegroup EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); @@ -162,7 +163,7 @@ namespace EMStudio mNodeTable->setRowCount(numAttachmentNodes); // set header items for the table - QTableWidgetItem* nameHeaderItem = new QTableWidgetItem(AZStd::string::format("Attachment Nodes (%zu / %zu)", numAttachmentNodes, mActor->GetNumNodes()).c_str()); + QTableWidgetItem* nameHeaderItem = new QTableWidgetItem(AZStd::string::format("Attachment Nodes (%d / %zu)", numAttachmentNodes, mActor->GetNumNodes()).c_str()); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignCenter); mNodeTable->setHorizontalHeaderItem(0, nameHeaderItem); @@ -250,8 +251,8 @@ namespace EMStudio mNodeSelectionList.Clear(); if (senderWidget == mSelectNodesButton) { - const uint32 numNodes = mActor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); if (node->GetIsAttachmentNode()) @@ -272,9 +273,9 @@ 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 = mNodeTable->rowCount(); + for (int i = 0; i < numTableRows; ++i) { // get the current table item QTableWidgetItem* item = mNodeTable->item(i, 0); @@ -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(); } } } @@ -310,7 +311,7 @@ namespace EMStudio } // selected the next row - if (lowestSelectedRow > ((uint32)mNodeTable->rowCount() - 1)) + if (lowestSelectedRow > mNodeTable->rowCount() - 1) { mNodeTable->selectRow(lowestSelectedRow - 1); } @@ -324,8 +325,7 @@ namespace EMStudio // add / select nodes void AttachmentNodesWindow::NodeSelectionFinished(AZStd::vector selectionList) { - // return if no nodes are selected - if (selectionList.size() == 0) + if (selectionList.empty()) { return; } @@ -333,10 +333,9 @@ namespace EMStudio // generate node list string AZStd::string nodeList; nodeList.reserve(16384); - const uint32 numSelectedNodes = selectionList.size(); - 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 */); @@ -364,7 +363,7 @@ namespace EMStudio // handle item selection changes of the node table void AttachmentNodesWindow::OnItemSelectionChanged() { - mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (mNodeTable->selectedItems().size() != 0)); + mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (!mNodeTable->selectedItems().empty())); } 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..536ff16f57 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 @@ -72,8 +72,8 @@ namespace EMStudio mHierarchy->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); @@ -96,8 +96,8 @@ namespace EMStudio mHierarchy->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/AttachmentsWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.cpp index c78d37dd7b..2ffc56d25b 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 @@ -236,13 +238,13 @@ namespace EMStudio } // the number of existing attachments - const uint32 numAttachments = mActorInstance->GetNumAttachments(); + const int numAttachments = aznumeric_caster(mActorInstance->GetNumAttachments()); // set table size and add header items mTableWidget->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); if (attachment == nullptr) @@ -253,18 +255,11 @@ 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::Node* attachedToNode = + !attachment->GetIsInfluencedByMultipleJoints() + ? attachedToNode = attachedToActor->GetSkeleton()->GetNode( + static_cast(attachment)->GetAttachToNodeIndex()) + : nullptr; // create table items mTempString = AZStd::string::format("%i", attachmentInstance->GetID()); @@ -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%"); @@ -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, mActorInstance->GetID(), nodeName.c_str()).c_str()); } // execute the group command @@ -708,20 +701,19 @@ namespace EMStudio // remove selected attachments void AttachmentsWindow::OnRemoveButtonClicked() { - uint32 lowestSelectedRow = MCORE_INVALIDINDEX32; + int lowestSelectedRow = AZStd::numeric_limits::max(); const QList selectedItems = mTableWidget->selectedItems(); - const int numSelectedItems = selectedItems.size(); - for (int i = 0; i < numSelectedItems; ++i) + 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 > (mTableWidget->rowCount() - 1)) { mTableWidget->selectRow(lowestSelectedRow - 1); } @@ -808,7 +800,7 @@ namespace EMStudio AZStd::string AttachmentsWindow::GetSelectedNodeName() { const QList items = mTableWidget->selectedItems(); - const uint32 numItems = items.length(); + const size_t numItems = items.length(); if (numItems < 1) { return AZStd::string(); @@ -845,7 +837,7 @@ namespace EMStudio QTableWidgetItem* item = mTableWidget->item(row, 1); if (item == nullptr) { - return MCORE_INVALIDINDEX32; + return MCore::InvalidIndexT; } AZStd::string id; @@ -861,7 +853,7 @@ namespace EMStudio QTableWidgetItem* item = mTableWidget->item(row, 4); if (item == nullptr) { - return AZStd::string(); + return {}; } return FromQtString(item->whatsThis()); @@ -872,11 +864,11 @@ 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 = mTableWidget->rowCount(); + const int numCols = mTableWidget->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) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp index 51c7e1d8de..fa039c1666 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.cpp @@ -281,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) @@ -290,11 +290,11 @@ namespace EMStudio } // filter the items - AZStd::vector rowIndices; + AZStd::vector rowIndices; rowIndices.reserve(numSelectedItems); - for (uint32 i = 0; i < numSelectedItems; ++i) + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = items[i]->row(); + const int rowIndex = items[i]->row(); if (AZStd::find(begin(rowIndices), end(rowIndices), rowIndex) == end(rowIndices)) { rowIndices.emplace_back(rowIndex); @@ -305,12 +305,12 @@ namespace EMStudio AZStd::sort(begin(rowIndices), end(rowIndices)); // get the number of selected rows - const uint32 numSelectedRows = rowIndices.size(); + 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(); @@ -360,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); @@ -370,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/LogWindowPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.cpp index 49bf04bf3b..a9a7c6a174 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 @@ -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(mLogCallback); + if (index != InvalidIndex) { MCore::GetLogManager().RemoveLogCallback(index); } 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..910f8456e5 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 @@ -133,7 +133,7 @@ namespace EMStudio // 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 @@ -327,14 +327,14 @@ namespace EMStudio mSelectedPhonemeSetsTable->clear(); // get number of morph targets - const uint32 numMorphTargets = mMorphSetup->GetNumMorphTargets(); + const size_t numMorphTargets = mMorphSetup->GetNumMorphTargets(); const uint32 numPhonemeSets = mMorphTarget->GetNumAvailablePhonemeSets(); - uint32 insertPosition = 0; - for (uint32 i = 1; i < numPhonemeSets; ++i) + 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); if (morphTarget->GetIsPhonemeSetEnabled((EMotionFX::MorphTarget::EPhonemeSet)(1 << i))) @@ -381,9 +381,9 @@ namespace EMStudio 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()); + const int numSelectedPhonemeSets = aznumeric_caster(splittedPhonemeSets.size()); mSelectedPhonemeSetsTable->setRowCount(numSelectedPhonemeSets); - for (uint32 i = 0; i < numSelectedPhonemeSets; ++i) + for (int i = 0; i < numSelectedPhonemeSets; ++i) { // create dummy table widget item. const EMotionFX::MorphTarget::EPhonemeSet phonemeSet = mMorphTarget->FindPhonemeSet(splittedPhonemeSets[i].c_str()); @@ -425,7 +425,7 @@ namespace EMStudio QTableWidget* table = (QTableWidget*)sender(); // disable/enable buttons - bool selected = (table->selectedItems().size() > 0); + bool selected = !table->selectedItems().empty(); if (table == mPossiblePhonemeSetsTable) { mAddPhonemesButton->setDisabled(!selected); @@ -438,8 +438,8 @@ namespace EMStudio } // 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); @@ -462,21 +462,20 @@ namespace EMStudio void PhonemeSelectionWindow::RemoveSelectedPhonemeSets() { QList selectedItems = mSelectedPhonemeSetsTable->selectedItems(); - const uint32 numSelectedItems = selectedItems.size(); - if (numSelectedItems == 0) + 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\"", mActor->GetID(), mLODLevel, mMorphTarget->GetName(), phonemeSets.c_str()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result)) @@ -494,21 +493,20 @@ namespace EMStudio void PhonemeSelectionWindow::AddSelectedPhonemeSets() { QList selectedItems = mSelectedPhonemeSetsTable->selectedItems(); - const uint32 numSelectedItems = selectedItems.size(); - if (numSelectedItems == 0) + 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\"", mActor->GetID(), mLODLevel, mMorphTarget->GetName(), phonemeSets.c_str()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result)) 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..a6bffffb75 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 @@ -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(); @@ -140,7 +140,7 @@ namespace EMStudio // the morph target EMotionFX::Actor* mActor; EMotionFX::MorphTarget* mMorphTarget; - uint32 mLODLevel; + size_t mLODLevel; EMotionFX::MorphSetup* mMorphSetup; // the dialogstacks 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 441c9555a7..5943263e3d 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 @@ -70,11 +72,11 @@ namespace EMStudio tableWidget->verticalHeader()->setVisible(false); // set the number of rows - const uint32 numMotions = motions.size(); + 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]; @@ -182,8 +184,8 @@ namespace EMStudio 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); @@ -359,8 +361,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); @@ -372,16 +374,15 @@ namespace EMStudio { // Get the selected items in the motion set tree widget.. const QList selectedItems = mMotionSetsTree->selectedItems(); - const int numSelectedItems = selectedItems.count(); + 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); @@ -392,8 +393,8 @@ namespace EMStudio // 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); @@ -446,8 +447,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); @@ -468,7 +469,7 @@ namespace EMStudio void MotionSetManagementWindow::OnSelectionChanged() { const QList selectedItems = mMotionSetsTree->selectedItems(); - const uint32 numSelected = selectedItems.count(); + const size_t numSelected = selectedItems.count(); if (numSelected != 1) { mPlugin->SetSelectedSet(nullptr); @@ -547,7 +548,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. @@ -585,7 +586,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()); }); @@ -649,16 +650,15 @@ namespace EMStudio { // Get the selected items from the motion set tree widget. const QList selectedItems = mMotionSetsTree->selectedItems(); - const int numSelectedItems = selectedItems.count(); - 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 +681,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 +693,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); @@ -722,22 +722,18 @@ namespace EMStudio void MotionSetManagementWindow::OnRemoveSelectedMotionSets() { const QList selectedItems = mMotionSetsTree->selectedItems(); - const uint32 numSelected = selectedItems.count(); - if (numSelected <= 0) + 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,10 +743,10 @@ 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); @@ -817,8 +813,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 +846,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); @@ -902,7 +898,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()) { @@ -948,7 +944,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 +957,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()) { @@ -1019,7 +1012,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/MotionSetWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.cpp index 10ceb2e43f..0ab738a259 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 @@ -328,8 +329,8 @@ namespace EMStudio void MotionSetWindow::ReInit() { EMotionFX::MotionSet* selectedSet = mPlugin->GetSelectedSet(); - const uint32 selectedSetIndex = EMotionFX::GetMotionManager().FindMotionSetIndex(selectedSet); - if (selectedSetIndex != MCORE_INVALIDINDEX32) + const size_t selectedSetIndex = EMotionFX::GetMotionManager().FindMotionSetIndex(selectedSet); + if (selectedSetIndex != InvalidIndex) { UpdateMotionSetTable(m_tableWidget, mPlugin->GetSelectedSet()); } @@ -824,7 +825,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 +836,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 +848,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)) @@ -913,7 +914,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; @@ -1133,16 +1134,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 +1182,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 +1200,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. @@ -1371,7 +1371,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,9 +1407,6 @@ 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); @@ -1419,12 +1416,11 @@ namespace EMStudio // 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()); } } @@ -1556,8 +1552,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; } @@ -1828,12 +1823,11 @@ 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 : mValids) { // 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 = mMotionIDs[validID]; + const AZStd::string& modifiedID = mModifiedMotionIDs[mMotionToModifiedMap[validID]]; commandString = AZStd::string::format("MotionSetAdjustMotion -motionSetID %i -idString \"%s\" -newIDString \"%s\" -updateMotionNodeStringIDs true", mMotionSet->GetID(), motionID.c_str(), modifiedID.c_str()); motionID = modifiedID; @@ -1954,9 +1948,6 @@ namespace EMStudio return; } - // found flags - uint32 numDuplicateFound = 0; - // Clear the arrays but keep the memory to avoid alloc. mValids.clear(); mModifiedMotionIDs.clear(); @@ -1974,7 +1965,7 @@ namespace EMStudio // 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& mMotionID : mMotionIDs) { // 0=Replace All, 1=Replace First, 2=Replace Last const int operationMode = mComboBox->currentIndex(); @@ -1984,7 +1975,7 @@ namespace EMStudio { case 0: { - tempString = mMotionIDs[i].c_str(); + tempString = mMotionID.c_str(); AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */); newMotionID = tempString.c_str(); break; @@ -1992,7 +1983,7 @@ namespace EMStudio case 1: { - tempString = mMotionIDs[i].c_str(); + tempString = mMotionID.c_str(); AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, true /* replace first */, false /* replace last */); newMotionID = tempString.c_str(); break; @@ -2000,7 +1991,7 @@ namespace EMStudio case 2: { - tempString = mMotionIDs[i].c_str(); + tempString = mMotionID.c_str(); AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, false /* replace first */, true /* replace last */); newMotionID = tempString.c_str(); break; @@ -2008,17 +1999,20 @@ namespace EMStudio } // change the value in the array and add the mapping motion to modified - auto iterator = AZStd::find(mModifiedMotionIDs.begin(), mModifiedMotionIDs.end(), mMotionIDs[i]); + auto iterator = AZStd::find(mModifiedMotionIDs.begin(), mModifiedMotionIDs.end(), mMotionID); const size_t modifiedIndex = iterator - mModifiedMotionIDs.begin(); mModifiedMotionIDs[modifiedIndex] = newMotionID; - mMotionToModifiedMap.push_back(static_cast(modifiedIndex)); + mMotionToModifiedMap.push_back(modifiedIndex); } // disable the sorting mTableWidget->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]]; @@ -2028,9 +2022,9 @@ namespace EMStudio 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 = mMotionSet->GetNumMotionEntries(); + for (size_t k = 0; k < numMotionEntries; ++k) { if (mModifiedMotionIDs[k] == modifiedID) { @@ -2063,8 +2057,8 @@ namespace EMStudio } // set the text of the row - mTableWidget->setItem(i, 0, beforeTableWidgetItem); - mTableWidget->setItem(i, 1, afterTableWidgetItem); + mTableWidget->setItem(aznumeric_caster(i), 0, beforeTableWidgetItem); + mTableWidget->setItem(aznumeric_caster(i), 1, afterTableWidgetItem); } // enable the sorting @@ -2085,7 +2079,7 @@ namespace EMStudio } // enable or disable the apply button - mApplyButton->setEnabled((mValids.size() > 0) && (numDuplicateFound == 0)); + mApplyButton->setEnabled((!mValids.empty()) && (numDuplicateFound == 0)); // Reselect the remembered motions. mTableWidget->clearSelection(); @@ -2130,9 +2124,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 +2135,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 +2143,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..33b3828e5a 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 @@ -91,8 +91,8 @@ namespace EMStudio EMotionFX::MotionSet* mMotionSet; AZStd::vector mMotionIDs; AZStd::vector mModifiedMotionIDs; - AZStd::vector mMotionToModifiedMap; - AZStd::vector mValids; + AZStd::vector mMotionToModifiedMap; + AZStd::vector mValids; QTableWidget* mTableWidget; QLineEdit* mStringALineEdit; QLineEdit* mStringBLineEdit; @@ -184,7 +184,7 @@ 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; 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..3860edd009 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 @@ -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); @@ -226,7 +226,7 @@ namespace EMStudio EMotionFX::MotionSet* MotionSetsWindowPlugin::GetSelectedSet() const { - if (EMotionFX::GetMotionManager().FindMotionSetIndex(mSelectedSet) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionSetIndex(mSelectedSet) == InvalidIndex) { return nullptr; } @@ -238,7 +238,7 @@ namespace EMStudio 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(mSelectedSet) == InvalidIndex) { mSelectedSet = nullptr; } @@ -488,7 +488,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 +680,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/MotionWindow/MotionExtractionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.cpp index ac284a5777..419535da81 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 @@ -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(); @@ -254,11 +254,11 @@ namespace EMStudio // 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; @@ -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); 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..c909098dae 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 @@ -243,7 +243,7 @@ namespace EMStudio mMotionTable->setSortingEnabled(false); // insert the new row - const uint32 rowIndex = 0; + const int rowIndex = 0; mMotionTable->insertRow(rowIndex); mMotionTable->setRowHeight(rowIndex, 21); @@ -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 = mMotionTable->rowCount(); + for (int i = 0; i < rowCount; ++i) { if (GetMotionID(i) == motionID) { @@ -469,7 +469,7 @@ namespace EMStudio mMotionTable->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 @@ -531,14 +531,14 @@ namespace EMStudio const QList selectedItems = mMotionTable->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); @@ -549,22 +549,20 @@ namespace EMStudio mSelectedMotionIDs.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) + mSelectedMotionIDs.reserve(rowIndices.size()); + for (const int rowIndex : rowIndices) { - mSelectedMotionIDs.push_back(GetMotionID(rowIndices[i])); + mSelectedMotionIDs.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 : mSelectedMotionIDs) { // 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); @@ -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()); @@ -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/MotionRetargetingWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.cpp index 5c0ab3d564..6596a7c868 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 @@ -67,8 +67,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::MotionTableEntry* entry = mMotionWindowPlugin->FindMotionEntryByID(selection.GetMotion(i)->GetID()); if (entry == nullptr) @@ -108,7 +108,7 @@ 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); @@ -120,7 +120,7 @@ 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()); if (entry == nullptr) 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..1452d0ac93 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 @@ -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); @@ -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()) @@ -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; + int lowestRowSelected = AZStd::numeric_limits::max(); const QList selectedItems = mMotionListWindow->GetMotionTable()->selectedItems(); - const int numSelectedItems = selectedItems.size(); - for (int i = 0; i < numSelectedItems; ++i) + 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,7 +366,7 @@ namespace EMStudio CommandSystem::RemoveMotions(motionsToRemove, &failedRemoveMotions); // selected the next row - if (lowestRowSelected > ((uint32)mMotionListWindow->GetMotionTable()->rowCount() - 1)) + if (lowestRowSelected > (mMotionListWindow->GetMotionTable()->rowCount() - 1)) { mMotionListWindow->GetMotionTable()->selectRow(lowestRowSelected - 1); } @@ -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()); @@ -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); @@ -481,21 +476,16 @@ namespace EMStudio } // iterate through all motions inside the motion window plugin - i = 0; - while (i < mMotionEntries.size()) + AZStd::erase_if(mMotionEntries, [](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) + if (EMotionFX::GetMotionManager().FindMotionIndexByID(entry->mMotionID) == InvalidIndex) { - delete mMotionEntries[i]; - mMotionEntries.erase(mMotionEntries.begin() + i); + delete entry; + return true; } - else - { - i++; - } - } + return false; + }); // update the motion list window mMotionListWindow->ReInit(); @@ -511,10 +501,8 @@ namespace EMStudio 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); @@ -537,8 +525,6 @@ namespace EMStudio mMotionNameLabel->setText(motion ? motion->GetName() : nullptr); } - const uint32 numMotions = EMotionFX::GetMotionManager().GetNumMotions(); - if (mSaveAction) { // related to the selected motions @@ -561,35 +547,30 @@ namespace EMStudio - 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(); - 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) @@ -606,17 +587,11 @@ namespace EMStudio 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(mMotionEntries), end(mMotionEntries), [motionID](const MotionTableEntry* entry) { - MotionTableEntry* entry = mMotionEntries[i]; - if (entry->mMotionID == motionID) - { - return entry; - } - } - - return nullptr; + return entry->mMotionID == motionID; + }); + return foundEntry != end(mMotionEntries) ? *foundEntry : nullptr; } @@ -633,10 +608,8 @@ 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. @@ -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) @@ -703,61 +676,6 @@ namespace EMStudio { 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); - } - } - } - } - */ } 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 552a6d45e7..1a95899c32 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,7 +9,8 @@ // inlude required headers #include "NodeGroupWidget.h" #include "../../../../EMStudioSDK/Source/EMStudioManager.h" -#include "AzCore/std/iterator.h" +#include +#include #include #include @@ -332,10 +333,10 @@ namespace EMStudio // add / select nodes - void NodeGroupWidget::NodeSelectionFinished(AZStd::vector selectionList) + void NodeGroupWidget::NodeSelectionFinished(const AZStd::vector& selectionList) { // return if no nodes are selected - if (selectionList.size() == 0) + if (selectionList.empty()) { return; } 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 f128fd8082..6861e77756 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(AZStd::vector selectionList); + void NodeSelectionFinished(const AZStd::vector& selectionList); void OnItemSelectionChanged(); private: 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 49b1d1b8f3..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. 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 28215e59c9..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; 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..a402dc869e 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(); @@ -60,24 +60,24 @@ namespace EMStudio } // 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.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.h index 7b1655bd05..582e9e9eac 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 @@ -82,8 +82,8 @@ namespace EMStudio AZStd::string mString; AZStd::string mTempGroupName; - AZStd::unordered_set m_visibleNodeIndices; - AZStd::unordered_set m_selectedNodeIndices; + 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/SceneManager/ActorPropertiesWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.cpp index cc5811b1f7..4e8e51b601 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 @@ -126,8 +126,8 @@ namespace EMStudio { mActor = 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) @@ -198,8 +198,8 @@ namespace EMStudio AZStd::vector jointsExcludedFromBounds; if (mActorInstance) { - const uint32 numNodes = mActor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = mActor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); if (!node->GetIncludeInBoundsCalc()) @@ -395,10 +395,10 @@ namespace EMStudio EMotionFX::Actor* actor = actorInstance->GetActor(); EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); - const uint32 numJoints = mActor->GetNumNodes(); + const size_t numJoints = mActor->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); } 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/SceneManagerPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.cpp index 820cb78d51..61b6c44dbb 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); @@ -49,11 +49,9 @@ 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) { continue; 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..14e2c79b88 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) 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 ea41b0ab65..0f276d640d 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 @@ -163,10 +163,9 @@ namespace EMStudio { if (delFromMem) { - const size_t numElems = mElements.size(); - for (size_t i = 0; i < numElems; ++i) + for (TimeTrackElement* mElement : mElements) { - delete mElements[i]; + delete mElement; } } @@ -175,7 +174,7 @@ namespace EMStudio // 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) { @@ -183,11 +182,9 @@ namespace EMStudio } // for all elements - const size_t numElems = mElements.size(); - for (size_t i = 0; i < numElems; ++i) + for (TimeTrackElement* element : mElements) { // check if its inside - TimeTrackElement* element = mElements[i]; if (element->GetIsVisible() == false) { continue; 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 4046ebf55f..55dcae73c3 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 @@ -78,7 +78,7 @@ namespace EMStudio 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)); } + bool GetIsInside(uint32 y) const { return (y >= mStartY) && (y <= (mStartY + mHeight)); } void SetName(const char* name) { mName = name; } const char* GetName() const { return mName.c_str(); } @@ -95,7 +95,7 @@ namespace EMStudio MCORE_INLINE bool GetIsHighlighted() const { return mIsHighlighted; } MCORE_INLINE void SetIsHighlighted(bool enabled) { mIsHighlighted = enabled; } - TimeTrackElement* GetElementAt(int32 x, int32 y); + TimeTrackElement* GetElementAt(int32 x, int32 y) const; protected: AZStd::string mName; 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..78e911eb0a 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 @@ -27,7 +27,7 @@ namespace EMStudio int32 TimeTrackElement::mTickHalfWidth = 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; 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..1e0d38486b 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,14 +35,14 @@ 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; } + MCORE_INLINE size_t GetElementNumber() const { return mElementNumber; } QColor GetColor() const { return mColor; } void SetIsSelected(bool selected) { mIsSelected = selected; } @@ -51,7 +51,7 @@ namespace EMStudio 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 SetElementNumber(size_t elementNumber) { mElementNumber = elementNumber; } void SetColor(QColor color) { mColor = color; } const QString& GetName() const { return mName; } @@ -91,7 +91,7 @@ namespace EMStudio QString mName; QString mToolTip; QColor mColor; - uint32 mElementNumber; + size_t mElementNumber; QPoint mTickPoints[6]; bool mVisible; 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 e909e9ead3..2ca600596a 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 @@ -107,10 +107,9 @@ namespace EMStudio delete mZoomOutCursor; // get rid of the motion infos - const uint32 numMotionInfos = mMotionInfos.size(); - for (uint32 i = 0; i < numMotionInfos; ++i) + for (MotionInfo* mMotionInfo : mMotionInfos) { - delete mMotionInfos[i]; + delete mMotionInfo; } } @@ -294,10 +293,9 @@ namespace EMStudio void TimeViewPlugin::RemoveAllTracks() { // get the number of time tracks and iterate through them - const uint32 numTracks = mTracks.size(); - for (uint32 i = 0; i < numTracks; ++i) + for (TimeTrack* track : mTracks) { - delete mTracks[i]; + delete track; } mTracks.clear(); @@ -306,37 +304,29 @@ namespace EMStudio TimeTrack* TimeViewPlugin::FindTrackByElement(TimeTrackElement* element) const { - // get the number of time tracks and iterate through them - const uint32 numTracks = mTracks.size(); - for (uint32 i = 0; i < numTracks; ++i) + const auto foundTrack = AZStd::find_if(begin(mTracks), end(mTracks), [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(mTracks) ? *foundTrack : nullptr; } - AZ::Outcome TimeViewPlugin::FindTrackIndex(const TimeTrack* track) const + AZ::Outcome TimeViewPlugin::FindTrackIndex(const TimeTrack* track) const { - const AZ::u32 numTracks = mTracks.size(); - for (AZ::u32 i = 0; i < numTracks; ++i) + const auto foundTrack = AZStd::find(begin(mTracks), end(mTracks), track); + if (foundTrack != end(mTracks)) { - if (mTracks[i] == track) - { - return AZ::Success(i); - } + return AZ::Success(static_cast(AZStd::distance(begin(mTracks), foundTrack))); } - return AZ::Failure(); } @@ -472,11 +462,10 @@ namespace EMStudio TimeTrackElement* TimeViewPlugin::GetElementAt(int32 x, int32 y) { // for all tracks - const uint32 numTracks = mTracks.size(); - for (uint32 i = 0; i < numTracks; ++i) + for (const TimeTrack* track : mTracks) { // check if the absolute pixel is inside - TimeTrackElement* result = mTracks[i]->GetElementAt(aznumeric_cast(x + mScrollX), y); + TimeTrackElement* result = track->GetElementAt(aznumeric_cast(x + mScrollX), y); if (result) { return result; @@ -491,17 +480,11 @@ namespace EMStudio TimeTrack* TimeViewPlugin::GetTrackAt(int32 y) { // for all tracks - const uint32 numTracks = mTracks.size(); - for (uint32 i = 0; i < numTracks; ++i) + const auto foundTrack = AZStd::find_if(begin(mTracks), end(mTracks), [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(mTracks) ? *foundTrack : nullptr; } @@ -509,14 +492,11 @@ namespace EMStudio void TimeViewPlugin::UnselectAllElements() { // for all tracks - const uint32 numTracks = mTracks.size(); - for (uint32 t = 0; t < numTracks; ++t) + for (TimeTrack* track : mTracks) { - 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); } @@ -603,18 +583,16 @@ namespace EMStudio } // for all tracks - const uint32 numTracks = mTracks.size(); - for (uint32 t = 0; t < numTracks; ++t) + for (TimeTrack* track : mTracks) { - 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 +624,18 @@ namespace EMStudio void TimeViewPlugin::RenderElementTimeHandles(QPainter& painter, uint32 dataWindowHeight, const QPen& pen) { // for all tracks - const uint32 numTracks = mTracks.size(); - for (uint32 t = 0; t < numTracks; ++t) + for (const TimeTrack* track : mTracks) { - 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 +658,11 @@ namespace EMStudio void TimeViewPlugin::DisableAllToolTips() { // for all tracks - const uint32 numTracks = mTracks.size(); - for (uint32 t = 0; t < numTracks; ++t) + for (const TimeTrack* track : mTracks) { - 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 +676,16 @@ namespace EMStudio bool TimeViewPlugin::FindResizePoint(int32 x, int32 y, TimeTrackElement** outElement, uint32* outID) { // for all tracks - const uint32 numTracks = mTracks.size(); - for (uint32 t = 0; t < numTracks; ++t) + for (const TimeTrack* track : mTracks) { - 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); @@ -1189,8 +1160,8 @@ namespace EMStudio const EMotionFX::MotionEventTable* eventTable = mMotion->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 +1177,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) @@ -1230,7 +1201,7 @@ namespace EMStudio void TimeViewPlugin::ReInit() { - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == InvalidIndex) { // set the motion first back to nullptr mMotion = nullptr; @@ -1289,7 +1260,7 @@ namespace EMStudio TimeTrackElement* element = nullptr; if (eventIndex < timeTrack->GetNumElements()) { - element = timeTrack->GetElement(static_cast(eventIndex)); + element = timeTrack->GetElement(eventIndex); } else { @@ -1298,15 +1269,13 @@ namespace EMStudio } // Select the element if in mSelectedEvents. - const AZ::u32 numSelectedEvents = mSelectedEvents.size(); - for (AZ::u32 selectedEventIndex = 0; selectedEventIndex < numSelectedEvents; ++selectedEventIndex) + for (const EventSelectionItem& selectionItem : mSelectedEvents) { - const EventSelectionItem& selectionItem = mSelectedEvents[selectedEventIndex]; if (mMotion != selectionItem.mMotion) { continue; } - if (selectionItem.mTrackNr == static_cast(trackIndex) && selectionItem.mEventNr == static_cast(eventIndex)) + if (selectionItem.mTrackNr == trackIndex && selectionItem.mEventNr == eventIndex) { element->SetIsSelected(true); break; @@ -1334,7 +1303,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()); @@ -1400,14 +1369,14 @@ namespace EMStudio } else // mMotion == 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); @@ -1447,15 +1416,13 @@ namespace EMStudio // find the motion info for the given motion id TimeViewPlugin::MotionInfo* TimeViewPlugin::FindMotionInfo(uint32 motionID) { - const uint32 numMotionInfos = mMotionInfos.size(); - for (uint32 i = 0; i < numMotionInfos; ++i) + const auto foundMotionInfo = AZStd::find_if(begin(mMotionInfos), end(mMotionInfos), [motionID](const MotionInfo* motionInfo) { - MotionInfo* motionInfo = mMotionInfos[i]; - - if (motionInfo->mMotionID == motionID) - { - return motionInfo; - } + return motionInfo->mMotionID == motionID; + }); + if (foundMotionInfo != end(mMotionInfos)) + { + return *foundMotionInfo; } // we haven't found a motion info for the given id yet, so create a new one @@ -1469,31 +1436,27 @@ namespace EMStudio void TimeViewPlugin::Select(const AZStd::vector& selection) { - uint32 i; - mSelectedEvents = 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.size(); - 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.mTrackNr); + TimeTrackElement* element = track->GetElement(selectionItem.mEventNr); element->SetIsSelected(true); } @@ -1583,8 +1546,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; } @@ -1636,18 +1599,18 @@ namespace EMStudio return; } - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == InvalidIndex) { return; } // get the motion event table // MotionEventTable& eventTable = mMotion->GetEventTable(); - AZStd::vector 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); @@ -1659,8 +1622,8 @@ namespace EMStudio 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); @@ -1695,18 +1658,18 @@ namespace EMStudio return; } - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == InvalidIndex) { return; } // get the motion event table // MotionEventTable& eventTable = mMotion->GetEventTable(); - AZStd::vector 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); @@ -1718,8 +1681,8 @@ namespace EMStudio 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()) @@ -1885,8 +1848,8 @@ 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(); const bool displayNodeActivity = recorderGroup->GetDisplayNodeActivity(); @@ -1928,11 +1891,9 @@ namespace EMStudio { if (mMotion) { - const uint32 numTracks = mTracks.size(); - for (uint32 i = 0; i < numTracks; ++i) + for (const TimeTrack* track : mTracks) { - TimeTrack* track = mTracks[i]; - if (track->GetIsVisible() == false) + if (track->GetIsVisible() == false) { continue; } 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 386117d3a3..e6af4e1ae1 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 @@ -39,7 +39,7 @@ namespace EMStudio EMotionFX::MotionEvent* GetMotionEvent(); EMotionFX::MotionEventTrack* GetEventTrack(); - uint32 mEventNr;// the motion event index in its track + size_t 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 }; @@ -115,9 +115,9 @@ namespace EMStudio void AddTrack(TimeTrack* track); void RemoveAllTracks(); - TimeTrack* GetTrack(uint32 index) { return mTracks[index]; } + TimeTrack* GetTrack(size_t index) { return mTracks[index]; } size_t GetNumTracks() const { return mTracks.size(); } - AZ::Outcome FindTrackIndex(const TimeTrack* track) const; + AZ::Outcome FindTrackIndex(const TimeTrack* track) const; TimeTrack* FindTrackByElement(TimeTrackElement* element) const; void UnselectAllElements(); @@ -152,7 +152,7 @@ namespace EMStudio void ZoomRect(const QRect& rect); size_t GetNumSelectedEvents() { return mSelectedEvents.size(); } - EventSelectionItem GetSelectedEvent(uint32 index) const { return mSelectedEvents[index]; } + EventSelectionItem GetSelectedEvent(size_t index) const { return mSelectedEvents[index]; } void Select(const AZStd::vector& selection); @@ -180,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: 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..618d5f2bf5 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 @@ -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); @@ -212,11 +212,9 @@ 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; } @@ -244,11 +242,9 @@ 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; } @@ -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()) @@ -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; 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 fc60867864..bbfae05dff 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 @@ -199,7 +199,7 @@ namespace EMStudio } } - void TrackDataWidget::RemoveTrack(AZ::u32 trackIndex) + void TrackDataWidget::RemoveTrack(size_t trackIndex) { mPlugin->SetRedrawFlag(); CommandSystem::CommandRemoveEventTrack(trackIndex); @@ -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; } @@ -369,11 +369,8 @@ namespace EMStudio const uint32 graphContentsCode = mPlugin->mTrackHeaderWidget->mGraphContentsComboBox->currentIndex(); - const uint32 numItems = historyItems.size(); - for (uint32 i = 0; i < numItems; ++i) + for (EMotionFX::Recorder::NodeHistoryItem* curItem : historyItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = historyItems[i]; - double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); double endTimePixel = mPlugin->TimeToPixel(curItem->mEndTime); @@ -455,11 +452,10 @@ namespace EMStudio recorder.ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(mPlugin->mCurTime), true, (EMotionFX::Recorder::EValueType)graphContentsCode, &mActiveItems, &mTrackRemap); // display the values and names - uint32 offset = 0; - const uint32 numActiveItems = mActiveItems.size(); - for (uint32 i = 0; i < numActiveItems; ++i) + int offset = 0; + for (const EMotionFX::Recorder::ExtractedNodeHistoryItem& mActiveItem : mActiveItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = mActiveItems[i].mNodeHistoryItem; + EMotionFX::Recorder::NodeHistoryItem* curItem = mActiveItem.mNodeHistoryItem; if (curItem == nullptr) { continue; @@ -473,7 +469,7 @@ namespace EMStudio mTempString += curItem->mName.c_str(); } - if (showMotionFiles && curItem->mMotionFileName.size() > 0) + if (showMotionFiles && !curItem->mMotionFileName.empty()) { if (!mTempString.empty()) { @@ -485,14 +481,14 @@ namespace EMStudio if (!mTempString.empty()) { - mTempString += AZStd::string::format(" = %.4f", mActiveItems[i].mValue); + mTempString += AZStd::string::format(" = %.4f", mActiveItem.mValue); } else { - mTempString = AZStd::string::format("%.4f", mActiveItems[i].mValue); + mTempString = AZStd::string::format("%.4f", mActiveItem.mValue); } - const AZ::Color colorCode = (useNodeColors) ? mActiveItems[i].mNodeHistoryItem->mTypeColor : mActiveItems[i].mNodeHistoryItem->mColor; + const AZ::Color colorCode = (useNodeColors) ? mActiveItem.mNodeHistoryItem->mTypeColor : mActiveItem.mNodeHistoryItem->mColor; QColor color; color.setRgbF(colorCode.GetR(), colorCode.GetG(), colorCode.GetB(), colorCode.GetA()); @@ -528,11 +524,8 @@ namespace EMStudio const float tickHeight = 16; QPointF tickPoints[6]; - const uint32 numItems = historyItems.size(); - 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); @@ -628,31 +621,28 @@ namespace EMStudio const bool sorted = recorderGroup->GetSortNodeActivity(); const bool useNodeColors = recorderGroup->GetUseNodeTypeColors(); - const uint32 graphContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); + const int graphContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); recorder.ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(mPlugin->mCurTime), sorted, (EMotionFX::Recorder::EValueType)graphContentsCode, &mActiveItems, &mTrackRemap); const bool showNodeNames = mPlugin->mTrackHeaderWidget->mNodeNamesCheckBox->isChecked(); const bool showMotionFiles = mPlugin->mTrackHeaderWidget->mMotionFilesCheckBox->isChecked(); const bool interpolate = recorder.GetRecordSettings().mInterpolate; - const uint32 nodeContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); + const int nodeContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); // for all history items QRectF itemRect; - const uint32 numItems = historyItems.size(); - 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); - const uint32 trackIndex = mTrackRemap[ curItem->mTrackIndex ]; + const size_t trackIndex = mTrackRemap[ curItem->mTrackIndex ]; itemRect.setLeft(startTimePixel); itemRect.setRight(endTimePixel - 1); - itemRect.setTop((mNodeRectsStartHeight + (trackIndex * (mNodeHistoryItemHeight + 3)) + 3) /* - mPlugin->mScrollY*/); + itemRect.setTop((mNodeRectsStartHeight + (aznumeric_cast(trackIndex) * (mNodeHistoryItemHeight + 3)) + 3)); itemRect.setBottom(itemRect.top() + mNodeHistoryItemHeight); if (!rect.intersects(itemRect.toRect())) @@ -698,7 +688,7 @@ 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->mGlobalWeights; // init on global weights if (nodeContentsCode == 1) { keyTrack = &curItem->mLocalWeights; @@ -774,7 +764,7 @@ namespace EMStudio mTempString += curItem->mName.c_str(); } - if (showMotionFiles && curItem->mMotionFileName.size() > 0) + if (showMotionFiles && !curItem->mMotionFileName.empty()) { if (!mTempString.empty()) { @@ -810,8 +800,8 @@ namespace EMStudio } // handle highlighting - const uint32 numTracks = mPlugin->GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = mPlugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { TimeTrack* track = mPlugin->GetTrack(i); @@ -825,8 +815,8 @@ namespace EMStudio TimeTrackElement* mouseCursorElement = mPlugin->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); @@ -923,35 +913,31 @@ namespace EMStudio visibleEndTime = mPlugin->PixelToTime(width); //mPlugin->CalcTime( width, &visibleEndTime, nullptr, nullptr, nullptr, nullptr ); // for all tracks - const uint32 numTracks = mPlugin->mTracks.size(); - for (uint32 i = 0; i < numTracks; ++i) + for (TimeTrack* track : mPlugin->mTracks) { - TimeTrack* track = mPlugin->mTracks[i]; track->SetStartY(yOffset); // path for making the cut elements a bit transparent if (mCutMode) { // 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 : mCopyElements) { // 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) && @@ -1436,11 +1422,11 @@ namespace EMStudio 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); @@ -1468,14 +1454,7 @@ namespace EMStudio } // if we're going to resize - if (mResizeElement && mResizeID != MCORE_INVALIDINDEX32) - { - mResizing = true; - } - else - { - mResizing = false; - } + mResizing = mResizeElement && mResizeID != InvalidIndex32; // store the last clicked position mMouseLeftClicked = true; @@ -1725,12 +1704,12 @@ namespace EMStudio TimeTrack* timeTrack = mPlugin->GetTrackAt(mContextMenuY); - 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 = mPlugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { // get the current time view track TimeTrack* track = mPlugin->GetTrack(i); @@ -1740,8 +1719,8 @@ namespace EMStudio } // 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 +1735,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); @@ -1916,11 +1895,11 @@ namespace EMStudio return; } - AZStd::vector 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); @@ -1950,11 +1929,11 @@ namespace EMStudio return; } - AZStd::vector 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.emplace_back(i); } @@ -1974,7 +1953,7 @@ namespace EMStudio return; } - const AZ::Outcome trackIndexOutcome = mPlugin->FindTrackIndex(timeTrack); + const AZ::Outcome trackIndexOutcome = mPlugin->FindTrackIndex(timeTrack); if (trackIndexOutcome.IsSuccess()) { RemoveTrack(trackIndexOutcome.GetValue()); @@ -2010,9 +1989,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); @@ -2146,7 +2125,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,9 +2139,9 @@ 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); } } } @@ -2170,10 +2149,8 @@ namespace EMStudio const float offset = useLocation ? aznumeric_cast(mPlugin->PixelToTime(mContextMenuX, 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 : mCopyElements) { - const CopyElement& copyElement = mCopyElements[i]; - float startTime = copyElement.m_startTime + offset; float endTime = copyElement.m_endTime + offset; @@ -2226,8 +2203,8 @@ 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 = mPlugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { // get the current time track TimeTrack* track = mPlugin->GetTrack(i); @@ -2315,9 +2292,9 @@ namespace EMStudio // if we recorded node history mNodeHistoryRect = QRect(); - if (actorInstanceData && actorInstanceData->mNodeHistoryItems.size() > 0) + if (actorInstanceData && !actorInstanceData->mNodeHistoryItems.empty()) { - const uint32 height = (recorder.CalcMaxNodeHistoryTrackIndex(*actorInstanceData) + 1) * (mNodeHistoryItemHeight + 3) + mNodeRectsStartHeight; + const int height = aznumeric_caster((recorder.CalcMaxNodeHistoryTrackIndex(*actorInstanceData) + 1) * (mNodeHistoryItemHeight + 3) + mNodeRectsStartHeight); mNodeHistoryRect.setTop(mNodeRectsStartHeight); mNodeHistoryRect.setBottom(height); mNodeHistoryRect.setLeft(0); @@ -2325,9 +2302,9 @@ namespace EMStudio } mEventHistoryTotalHeight = 0; - if (actorInstanceData && actorInstanceData->mEventHistoryItems.size() > 0) + if (actorInstanceData && !actorInstanceData->mEventHistoryItems.empty()) { - mEventHistoryTotalHeight = (recorder.CalcMaxEventHistoryTrackIndex(*actorInstanceData) + 1) * 20; + mEventHistoryTotalHeight = aznumeric_caster((recorder.CalcMaxEventHistoryTrackIndex(*actorInstanceData) + 1) * 20); } } @@ -2348,7 +2325,7 @@ namespace EMStudio // make sure the mTrackRemap array is up to date RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); const bool sorted = recorderGroup->GetSortNodeActivity(); - const uint32 graphContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); + const int graphContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); EMotionFX::GetRecorder().ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(mPlugin->mCurTime), sorted, (EMotionFX::Recorder::EValueType)graphContentsCode, &mActiveItems, &mTrackRemap); @@ -2356,11 +2333,8 @@ namespace EMStudio const AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; QRect rect; - const uint32 numItems = historyItems.size(); - 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); @@ -2372,7 +2346,7 @@ namespace EMStudio rect.setLeft(aznumeric_cast(startTimePixel)); rect.setRight(aznumeric_cast(endTimePixel)); - rect.setTop((mNodeRectsStartHeight + (mTrackRemap[curItem->mTrackIndex] * (mNodeHistoryItemHeight + 3)) + 3)); + rect.setTop((mNodeRectsStartHeight + (aznumeric_cast(mTrackRemap[curItem->mTrackIndex]) * (mNodeHistoryItemHeight + 3)) + 3)); rect.setBottom(rect.top() + mNodeHistoryItemHeight); if (rect.contains(x, y)) @@ -2398,8 +2372,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; } @@ -2466,19 +2440,19 @@ namespace EMStudio EMotionFX::AnimGraphNode* curNode = node->GetParentNode(); while (curNode) { - nodePath.emplace(0, curNode); + nodePath.emplace(nodePath.begin(), curNode); curNode = curNode->GetParentNode(); } AZStd::string nodePathString; nodePathString.reserve(256); - for (uint32 i = 0; i < nodePath.size(); ++i) + for (const EMotionFX::AnimGraphNode* parentNode : nodePath) { - nodePathString += nodePath[i]->GetName(); - if (i != nodePath.size() - 1) + if (!nodePathString.empty()) { nodePathString += " > "; } + nodePathString += parentNode->GetName(); } outString += AZStd::string::format("

Node Path: 

"); @@ -2493,16 +2467,16 @@ 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->mMotionID != InvalidIndex32 && !item->mMotionFileName.empty()) { outString += AZStd::string::format("

Motion FileName: 

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

%s

", item->mMotionFileName.c_str()); @@ -2555,14 +2529,10 @@ namespace EMStudio const float tickHalfWidth = 7; const float tickHeight = 16; - const uint32 numItems = historyItems.size(); - 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); + float height = aznumeric_caster((curItem->mTrackIndex * 20) + mEventsStartHeight); double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); - //double endTimePixel = mPlugin->TimeToPixel( curItem->mEndTime ); 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))) @@ -2657,14 +2627,13 @@ namespace EMStudio } AZStd::string nodePathString; - nodePathString.reserve(256); - for (uint32 i = 0; i < nodePath.size(); ++i) + for (const EMotionFX::AnimGraphNode* parentNode : nodePath) { - nodePathString += nodePath[i]->GetName(); - if (i != nodePath.size() - 1) + if (!nodePathString.empty()) { nodePathString += " > "; } + nodePathString += parentNode->GetName(); } outString += AZStd::string::format("

Node Path: 

"); @@ -2679,10 +2648,10 @@ 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()); } // show the motion info 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 2709927254..48effb92d0 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 @@ -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,7 +70,7 @@ 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); } @@ -137,7 +137,7 @@ namespace EMStudio double mOldCurrentTime; AZStd::vector mActiveItems; - AZStd::vector mTrackRemap; + AZStd::vector mTrackRemap; // copy and paste struct CopyElement 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 363a278b8e..5b21d8c7b5 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 @@ -173,8 +173,7 @@ namespace EMStudio setVisible(true); mStackWidget->setVisible(false); - const uint32 numTracks = mPlugin->mTracks.size(); - if (numTracks == 0) + if (mPlugin->mTracks.empty()) { return; } @@ -184,7 +183,8 @@ namespace EMStudio mTrackLayout->setMargin(0); mTrackLayout->setSpacing(1); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = mPlugin->mTracks.size(); + for (size_t i = 0; i < numTracks; ++i) { TimeTrack* track = mPlugin->mTracks[i]; @@ -206,7 +206,7 @@ namespace EMStudio } - 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; @@ -309,8 +309,8 @@ namespace EMStudio AZStd::string name = mNameEdit->text().toUtf8().data(); bool nameUnique = true; - const uint32 numTracks = mPlugin->GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = mPlugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { TimeTrack* track = mPlugin->GetTrack(i); 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..dae551d2bb 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,14 +46,14 @@ 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; + size_t mTrackIndex; TrackHeaderWidget* mHeaderTrackWidget; TimeViewPlugin* mPlugin; @@ -62,8 +62,8 @@ namespace EMStudio 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(); @@ -97,8 +97,8 @@ namespace EMStudio 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); diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp index 36c0edf986..6a6d540519 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 @@ -100,7 +102,7 @@ namespace MysticQt // add the dialog widget // the splitter is hierarchical : {a, {b, c}} - QSplitter* dialogSplitter; + DialogStackSplitter* dialogSplitter; if (mDialogs.empty()) { // add the dialog widget @@ -149,7 +151,7 @@ namespace MysticQt dialogSplitter->setChildrenCollapsible(false); // add the current last dialog and the new dialog after - dialogSplitter->addWidget(mDialogs.back().mDialogWidget.get()); + dialogSplitter->addWidget(mDialogs.back().mDialogWidget); dialogSplitter->addWidget(dialogWidget); // stretch if needed @@ -265,7 +267,7 @@ namespace MysticQt /*.mButton =*/ headerButton, /*.mFrame =*/ frame, /*.mWidget =*/ widget, - /*.mDialogWidget =*/ AZStd::unique_ptr{dialogWidget}, + /*.mDialogWidget =*/ dialogWidget, /*.mSplitter =*/ dialogSplitter, /*.mClosable =*/ closable, /*.mMaximizeSize =*/ maximizeSize, @@ -303,32 +305,27 @@ namespace MysticQt bool DialogStack::Remove(QWidget* widget) { - const uint32 numDialogs = mDialogs.size(); - for (uint32 i = 0; i < numDialogs; ++i) + const auto foundDialog = AZStd::find_if(begin(mDialogs), end(mDialogs), [widget](const Dialog& dialog) { - QLayout* layout = mDialogs[i].mFrame->layout(); - int index = layout->indexOf(widget); + return dialog.mFrame->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.erase(AZStd::next(begin(mDialogs), i)); + if (foundDialog == end(mDialogs)) + { + 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->mDialogWidget->hide(); + foundDialog->mDialogWidget->deleteLater(); + mDialogs.erase(foundDialog); - // done - return true; - } - } + // update the scroll bars + UpdateScrollBars(); - // not found - return false; + return true; } @@ -336,7 +333,7 @@ namespace MysticQt void DialogStack::OnHeaderButton() { QPushButton* button = (QPushButton*)sender(); - const uint32 dialogIndex = FindDialog(button); + const size_t dialogIndex = FindDialog(button); if (mDialogs[dialogIndex].mFrame->isHidden()) { Open(button); @@ -349,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.size(); - for (uint32 i = 0; i < numDialogs; ++i) + const auto foundDialog = AZStd::find_if(begin(mDialogs), end(mDialogs), [pushButton](const Dialog& dialog) { - if (mDialogs[i].mButton == pushButton) - { - return i; - } - } - return MCORE_INVALIDINDEX32; + return dialog.mButton == pushButton; + }); + return foundDialog != end(mDialogs) ? AZStd::distance(begin(mDialogs), 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(mDialogs), end(mDialogs), [button](const Dialog& dialog) + { + return dialog.mButton == button; + }); + if (dialog == end(mDialogs)) { return; } // show the widget inside the dialog - mDialogs[dialogIndex].mFrame->show(); + dialog->mFrame->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->mDialogWidget->setMinimumHeight(dialog->mMinimumHeightBeforeClose); + dialog->mDialogWidget->setMaximumHeight(dialog->mMaximumHeightBeforeClose); // 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.size() - 1)) + if (dialog != mDialogs.end() - 1) { - mDialogs[dialogIndex].mSplitter->handle(1)->setFixedHeight(4); - mDialogs[dialogIndex].mSplitter->setStyleSheet("QSplitter::handle{ height: 4px; background: transparent; }"); + dialog->mSplitter->handle(1)->setFixedHeight(4); + dialog->mSplitter->setStyleSheet("QSplitter::handle{ height: 4px; background: transparent; }"); } // enable the splitter - if (dialogIndex < (mDialogs.size() - 1)) + if (dialog != mDialogs.end() - 1) { - mDialogs[dialogIndex].mSplitter->handle(1)->setEnabled(true); + dialog->mSplitter->handle(1)->setEnabled(true); } // maximize the size if it's needed if (mDialogs.size() > 1) { - if (mDialogs[dialogIndex].mMaximizeSize) + if (dialog->mMaximizeSize) { // special case if it's the first dialog - if (dialogIndex == 0) + if (dialog == mDialogs.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->mStretchWhenMaximize == false && (dialog + 1)->mMaximizeSize && (dialog + 1)->mFrame->isHidden() == false) { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMin(); + static_cast(dialog->mSplitter)->MoveFirstSplitterToMin(); } else { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMax(); + static_cast(dialog->mSplitter)->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)->mFrame->isHidden() || (dialog - 1)->mMaximizeSize == false || ((dialog - 1)->mMaximizeSize && (dialog - 1)->mStretchWhenMaximize == false)) { - static_cast(mDialogs[dialogIndex - 1].mSplitter)->MoveFirstSplitterToMin(); + static_cast((dialog - 1)->mSplitter)->MoveFirstSplitterToMin(); } // special case if it's not the last dialog - if (dialogIndex < (mDialogs.size() - 1)) + if (dialog != mDialogs.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)->mFrame->isHidden()) { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMax(); + static_cast(dialog->mSplitter)->MoveFirstSplitterToMax(); } } } @@ -444,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(mDialogs), end(mDialogs), [button](const Dialog& dialog) + { + return dialog.mButton == button; + }); + if (dialog == end(mDialogs)) { return; } // only closable dialog can be closed - if (mDialogs[dialogIndex].mClosable == false) + if (dialog->mClosable == 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->mMinimumHeightBeforeClose = dialog->mDialogWidget->minimumHeight(); + dialog->mMaximumHeightBeforeClose = dialog->mDialogWidget->maximumHeight(); // hide the widget inside the dialog - mDialogs[dialogIndex].mFrame->hide(); + dialog->mFrame->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->mDialogWidget->setMinimumHeight(dialog->mButton->height()); + dialog->mDialogWidget->setMaximumHeight(dialog->mButton->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.size() - 1)) + if (dialog < mDialogs.end() - 1) { - mDialogs[dialogIndex].mSplitter->handle(1)->setFixedHeight(1); - mDialogs[dialogIndex].mSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); - } - - // disable the splitter - if (dialogIndex < (mDialogs.size() - 1)) - { - mDialogs[dialogIndex].mSplitter->handle(1)->setDisabled(true); - } - - // set the first splitter to the min if needed - if (dialogIndex < (mDialogs.size() - 1)) - { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMin(); + dialog->mSplitter->handle(1)->setFixedHeight(1); + dialog->mSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); + dialog->mSplitter->handle(1)->setDisabled(true); + static_cast(dialog->mSplitter)->MoveFirstSplitterToMin(); } // maximize the first needed to avoid empty space bool findPreviousMaximizedDialogNeeded = true; - const uint32 numDialogs = mDialogs.size(); - for (uint32 i = dialogIndex + 1; i < numDialogs; ++i) + for (auto curDialog = dialog + 1; curDialog != mDialogs.end(); ++curDialog) { - if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) + if (curDialog->mMaximizeSize && curDialog->mFrame->isHidden() == false) { - if (i < (numDialogs - 1) && mDialogs[i + 1].mFrame->isHidden()) + if (curDialog != (mDialogs.end() - 1) && (curDialog + 1)->mFrame->isHidden()) { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMax(); + static_cast(curDialog->mSplitter)->MoveFirstSplitterToMax(); } else { - static_cast(mDialogs[i - 1].mSplitter)->MoveFirstSplitterToMin(); + static_cast((curDialog - 1)->mSplitter)->MoveFirstSplitterToMin(); } findPreviousMaximizedDialogNeeded = false; break; @@ -512,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 != mDialogs.rend(); ++curDialog) { - if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) + if (curDialog->mMaximizeSize && curDialog->mFrame->isHidden() == false) { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMax(); + static_cast(curDialog->mSplitter)->MoveFirstSplitterToMax(); break; } } @@ -620,16 +606,15 @@ namespace MysticQt QScrollArea::resizeEvent(event); // maximize the first dialog needed - const uint32 numDialogs = mDialogs.size(); - const int32 lastDialogIndex = static_cast(numDialogs) - 1; - for (int32 i = lastDialogIndex; i >= 0; --i) + if (mDialogs.empty() || mDialogs.size() == 1) + { + return; + } + for (auto dialog = mDialogs.rbegin() + 1; dialog != mDialogs.rend(); ++dialog) { - if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) + if (dialog->mMaximizeSize && dialog->mFrame->isHidden() == false) { - if (i < lastDialogIndex) - { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMax(); - } + static_cast(dialog->mSplitter)->MoveFirstSplitterToMax(); break; } } @@ -639,54 +624,54 @@ namespace MysticQt // replace an internal widget void DialogStack::ReplaceWidget(QWidget* oldWidget, QWidget* newWidget) { - for (uint32 i = 0; i < mDialogs.size(); ++i) + for (auto dialog = mDialogs.begin(); dialog != mDialogs.end(); ++dialog) { // go next if the widget is not the same - if (mDialogs[i].mWidget != oldWidget) + if (dialog->mWidget != oldWidget) { continue; } // replace the widget - mDialogs[i].mFrame->layout()->replaceWidget(oldWidget, newWidget); - mDialogs[i].mWidget = newWidget; + dialog->mFrame->layout()->replaceWidget(oldWidget, newWidget); + dialog->mWidget = newWidget; // adjust size of the new widget newWidget->adjustSize(); // set the constraints - if (mDialogs[i].mMaximizeSize == false) + if (dialog->mMaximizeSize == false) { // get margins - const QMargins frameMargins = mDialogs[i].mLayout->contentsMargins(); - const QMargins dialogMargins = mDialogs[i].mDialogLayout->contentsMargins(); + const QMargins frameMargins = dialog->mLayout->contentsMargins(); + const QMargins dialogMargins = dialog->mDialogLayout->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->mFrame->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->mButton->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->mFrame->isHidden() == false) { // set the dialog height - mDialogs[i].mDialogWidget->setFixedHeight(dialogHeight); + dialog->mDialogWidget->setFixedHeight(dialogHeight); // set the first splitter to the min if needed - if (i < (mDialogs.size() - 1)) + if (dialog != mDialogs.end() - 1) { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMin(); + static_cast(dialog->mSplitter)->MoveFirstSplitterToMin(); } } else // dialog closed { // update the minimum and maximum stored height - mDialogs[i].mMinimumHeightBeforeClose = dialogHeight; - mDialogs[i].mMaximumHeightBeforeClose = dialogHeight; + dialog->mMinimumHeightBeforeClose = dialogHeight; + dialog->mMaximumHeightBeforeClose = dialogHeight; } } diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h index d5850a8cbf..6bf810b281 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h @@ -11,7 +11,6 @@ // #if !defined(Q_MOC_RUN) -#include #include "MysticQtConfig.h" #include #include @@ -29,6 +28,8 @@ QT_FORWARD_DECLARE_CLASS(QSplitter) namespace MysticQt { + class DialogStackSplitter; + /** * * @@ -64,8 +65,8 @@ namespace MysticQt QPushButton* mButton = nullptr; QWidget* mFrame = nullptr; QWidget* mWidget = nullptr; - AZStd::unique_ptr mDialogWidget = nullptr; - QSplitter* mSplitter = nullptr; + QWidget* mDialogWidget = nullptr; + DialogStackSplitter* mSplitter = nullptr; bool mClosable = true; bool mMaximizeSize = false; bool mStretchWhenMaximize = false; @@ -76,14 +77,14 @@ namespace MysticQt }; private: - uint32 FindDialog(QPushButton* pushButton); + size_t FindDialog(QPushButton* pushButton); void Open(QPushButton* button); void Close(QPushButton* button); void UpdateScrollBars(); private: - QSplitter* mRootSplitter; - AZStd::vector mDialogs; + DialogStackSplitter* mRootSplitter; + AZStd::vector mDialogs; int32 mPrevMouseX; int32 mPrevMouseY; }; 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/Source/Editor/ActorJointBrowseEdit.cpp b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp index a5d7a67f51..41253a513e 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp @@ -154,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) diff --git a/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp b/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp index d62e82f438..ef76629780 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,7 +616,7 @@ namespace EMotionFX EMStudio::EMStudioPlugin::RenderInfo* renderInfo, const MCore::RGBAColor& colliderColor) { - const AZ::u32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; for (const auto& collider : colliders) @@ -681,11 +681,11 @@ namespace EMotionFX 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/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp index bda6e68449..93c4e2cb67 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp @@ -436,8 +436,8 @@ namespace EMotionFX 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,8 +535,8 @@ 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; diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp index aa222c0405..bd57e24d08 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(); @@ -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)); @@ -547,7 +547,7 @@ 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(); 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 95e08eab77..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); diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 2bf85692be..f834456e45 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -80,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/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/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index 160cbe8ee4..485b56c077 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -680,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()) @@ -803,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); } } From 0547a1085a35f4952f744a55729cf1b5180465c9 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 3 Jun 2021 11:17:12 -0700 Subject: [PATCH 186/251] Add version converter for the game controller settings, since one of its field types has changed Signed-off-by: Chris Burel --- .../AnimGraphGameControllerSettings.cpp | 22 +++++++++++++++++-- .../Source/AnimGraphGameControllerSettings.h | 2 +- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp index 6f2d6083a1..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) { } @@ -369,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); @@ -383,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 f543246599..d36a448be4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h @@ -164,6 +164,6 @@ namespace EMotionFX private: AZStd::vector m_presets; - size_t m_activePresetIndex; + AZ::u64 m_activePresetIndex; }; } // namespace EMotionFX From 56025070247d4c0f7bb08379e19c6ab059bea0b3 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Fri, 25 Jun 2021 17:48:11 -0700 Subject: [PATCH 187/251] Fix EMotionFX Editor tests to compile with `-Wshorten-64-to-32` Signed-off-by: Chris Burel --- .../Code/Tests/MorphTargetPipelineTests.cpp | 8 ++++---- .../AnimGraph/CanEditAnimGraphNode.cpp | 2 +- .../Code/Tests/UI/AnimGraphUIFixture.cpp | 4 ++-- .../Tests/UI/CanAddMotionToAnimGraphNode.cpp | 4 ++-- .../Code/Tests/UI/CanAddMotionToMotionSet.cpp | 8 ++++---- .../Code/Tests/UI/CanAddReferenceNode.cpp | 2 +- .../Code/Tests/UI/CanEditParameters.cpp | 2 +- .../Code/Tests/UI/CanMorphManyShapes.cpp | 2 +- .../Tests/UI/CanRemoveMotionFromMotionSet.cpp | 16 ++++++++-------- Gems/EMotionFX/Code/Tests/UI/CanUseEditMenu.cpp | 6 +++--- Gems/EMotionFX/Code/Tests/UI/CanUseViewMenu.cpp | 2 +- Gems/EMotionFX/Code/Tests/UI/UIFixture.cpp | 4 ++-- 12 files changed, 30 insertions(+), 30 deletions(-) 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/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/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 ba24c501ab..2ed0407d53 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp @@ -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( 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/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()); From 2cfee517a0a68358caa97dd262b2111f251283b8 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 3 Jun 2021 11:18:24 -0700 Subject: [PATCH 188/251] Adjust EMotionFXAtom to work with the new EMotionFX size_t API Signed-off-by: Chris Burel --- .../EMotionFXAtom/Code/Source/ActorAsset.cpp | 14 +++---- .../Code/Source/AtomActorInstance.cpp | 42 +++++++++---------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp index 608635b395..ece2c2aca7 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(); @@ -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 14e1f26bdd..c8a09ddaf8 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp @@ -131,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)) @@ -146,8 +145,8 @@ namespace AZ continue; } - const AZ::u32 parentIndex = joint->GetParentIndex(); - if (parentIndex == InvalidIndex32) + const size_t parentIndex = joint->GetParentIndex(); + if (parentIndex == InvalidIndex) { continue; } @@ -162,7 +161,7 @@ namespace AZ 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; @@ -203,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); } @@ -450,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(); @@ -470,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); } } } @@ -584,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) @@ -593,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 @@ -611,7 +611,7 @@ 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); @@ -816,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) @@ -861,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); } From d57d263b5d158249b524620ec164f52cfd8621be Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Tue, 6 Jul 2021 08:58:34 -0700 Subject: [PATCH 189/251] Fix format strings in EMotionFX to use the correct token for size_t Signed-off-by: Chris Burel --- .../CommandSystem/Source/ActorInstanceCommands.cpp | 2 +- .../StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp | 4 ++-- .../Source/Attachments/AttachmentsWindow.cpp | 2 +- .../Source/MorphTargetsWindow/MorphTargetEditWindow.cpp | 2 +- .../Source/MorphTargetsWindow/MorphTargetGroupWidget.cpp | 8 ++++---- .../Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp | 2 +- .../Source/MotionSetsWindow/MotionSetWindow.cpp | 2 +- .../StandardPlugins/Source/TimeView/TimeViewPlugin.cpp | 2 +- Gems/EMotionFX/Code/Tests/Mocks/EventHandler.h | 2 +- 9 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp index 60f03f170e..45603b298e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp @@ -492,7 +492,7 @@ namespace CommandSystem commandString = AZStd::string::format("CreateActorInstance -actorID %i -actorInstanceID %i", mOldActorID, 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(), 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 edf5579720..5d57763ea6 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 @@ -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 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 2ffc56d25b..4b971f9c32 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 @@ -268,7 +268,7 @@ namespace EMStudio 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()); + mTempString = AZStd::string::format("%zu", attachmentInstance->GetNumNodes()); QTableWidgetItem* tableItemNumNodes = new QTableWidgetItem(mTempString.c_str()); QTableWidgetItem* tableItemNodeName = new QTableWidgetItem(""); // set node name if exists 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..a53ed94909 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 @@ -149,7 +149,7 @@ namespace EMStudio const float rangeMax = (float)mRangeMax->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", mActorInstance->GetID(), mActorInstance->GetLODLevel(), mMorphTarget->GetNameString().c_str(), rangeMin, rangeMax); if (EMStudio::GetCommandManager()->ExecuteCommand(command, result) == false) { AZ_Error("EMotionFX", false, result.c_str()); 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..aee88f9394 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 @@ -133,7 +133,7 @@ namespace EMStudio { EMotionFX::MorphTarget* morphTarget = mMorphTargets[i].mMorphTarget; - 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 ", mActorInstance->GetID(), mActorInstance->GetLODLevel(), morphTarget->GetName()); command += AZStd::to_string(value == Qt::Checked); commandGroup.AddCommandString(command); } @@ -159,7 +159,7 @@ namespace EMStudio { EMotionFX::MorphTarget* morphTarget = mMorphTargets[i].mMorphTarget; - 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", mActorInstance->GetID(), mActorInstance->GetLODLevel(), morphTarget->GetName(), morphTarget->CalcZeroInfluenceWeight()); commandGroup.AddCommandString(command); } @@ -179,7 +179,7 @@ namespace EMStudio EMotionFX::MorphTarget* morphTarget = mMorphTargets[morphTargetIndex].mMorphTarget; AZStd::string result; - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %i -name \"%s\" -weight %f -manualMode %s", + const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %zu -name \"%s\" -weight %f -manualMode %s", mActorInstance->GetID(), mActorInstance->GetLODLevel(), morphTarget->GetName(), @@ -219,7 +219,7 @@ namespace EMStudio // 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", mActorInstance->GetID(), mActorInstance->GetLODLevel(), morphTarget->GetName(), floatSlider->value()); if (EMStudio::GetCommandManager()->ExecuteCommand(command, result) == false) { AZ_Error("EMotionFX", false, result.c_str()); 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 910f8456e5..5619398c67 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 @@ -523,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\"", mActor->GetID(), mLODLevel, mMorphTarget->GetName()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result)) 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 0ab738a259..19f28c36e0 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 @@ -409,7 +409,7 @@ 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(); 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 2ca600596a..6ff8ea3775 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 @@ -1575,7 +1575,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", mMotion->GetID(), eventTrack->GetName(), motionEventNr, startTime, endTime); if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) { MCore::LogError(outResult.c_str()); 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)); From c34147d8619c3d21e3eb84d03e7db5923f18ea97 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 7 Jul 2021 15:12:36 -0700 Subject: [PATCH 190/251] Fix violation of -Wrange-loop-analysis Signed-off-by: Chris Burel --- .../StandardPlugins/Source/AnimGraph/AnimGraphPlugin.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 62c0fe0a14..1a713f52fe 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 @@ -147,7 +147,7 @@ namespace EMStudio return DirtyFileManager::FINISHED; } - for (const SaveDirtyFilesCallback::ObjectPointer objPointer : objects) + for (const SaveDirtyFilesCallback::ObjectPointer& objPointer : objects) { // get the current object pointer and skip directly if the type check fails if (objPointer.mAnimGraph == nullptr) From bf92c283a0891271b9f9ef42798749d8ad551e8f Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 7 Jul 2021 12:15:20 -0700 Subject: [PATCH 191/251] Fix NvCloth tests to work with new EMotionFX API Signed-off-by: Chris Burel --- Gems/NvCloth/Code/Tests/ActorHelper.cpp | 6 +++--- Gems/NvCloth/Code/Tests/ActorHelper.h | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) 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. From 04babd3cffeec6d398816c79711db61090b5330b Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Tue, 13 Jul 2021 17:16:42 -0700 Subject: [PATCH 192/251] Fix misnamed range-for loop variables Signed-off-by: Chris Burel --- .../Rendering/OpenGL2/Source/GLRenderUtil.cpp | 4 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp | 14 +++++++------- .../Code/EMotionFX/Source/ActorInstance.cpp | 8 ++++---- .../Code/EMotionFX/Source/AnimGraphInstance.cpp | 10 +++++----- .../Code/EMotionFX/Source/AnimGraphNode.h | 6 +++--- .../Code/EMotionFX/Source/AnimGraphPosePool.cpp | 4 ++-- .../Source/AnimGraphRefCountedDataPool.cpp | 4 ++-- .../Code/EMotionFX/Source/Importer/Importer.cpp | 4 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 4 ++-- .../Code/EMotionFX/Source/MorphMeshDeformer.cpp | 12 ++++++------ .../EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp | 8 ++++---- .../Code/EMotionFX/Source/MorphTargetStandard.cpp | 10 +++++----- .../Code/EMotionFX/Source/MotionInstancePool.cpp | 4 ++-- .../Code/EMotionFX/Source/MotionLayerSystem.cpp | 8 ++++---- .../Code/EMotionFX/Source/MotionManager.cpp | 4 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp | 4 ++-- .../Code/EMotionFX/Source/StandardMaterial.cpp | 4 ++-- .../EMStudioSDK/Source/NodeHierarchyWidget.cpp | 4 ++-- .../Source/NotificationWindowManager.cpp | 12 ++++++------ .../Source/RenderPlugin/RenderPlugin.cpp | 6 +++--- .../StandardPlugins/Source/AnimGraph/GraphNode.cpp | 4 ++-- .../Source/MotionSetsWindow/MotionSetWindow.cpp | 10 +++++----- .../StandardPlugins/Source/TimeView/TimeTrack.cpp | 4 ++-- .../Source/TimeView/TimeViewPlugin.cpp | 4 ++-- .../Source/TimeView/TrackDataWidget.cpp | 10 +++++----- Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp | 4 ++-- .../Code/MysticQt/Source/MysticQtManager.cpp | 10 +++++----- 27 files changed, 90 insertions(+), 90 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp index c67ec180ed..d53a7b0f72 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp @@ -158,9 +158,9 @@ namespace RenderGL delete[] mTextures; // get rid of texture entries - for (TextEntry* mTextEntrie : mTextEntries) + for (TextEntry* textEntry : mTextEntries) { - delete mTextEntrie; + delete textEntry; } mTextEntries.clear(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index 5d3f5e6ec8..6f1293e1a3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -261,12 +261,12 @@ namespace EMotionFX void Actor::RemoveAllMaterials() { // for all LODs - for (AZStd::vector& mMaterial : mMaterials) + for (AZStd::vector& materials : mMaterials) { // delete all materials - for (Material* m : mMaterial) + for (Material* material : materials) { - m->Destroy(); + material->Destroy(); } } @@ -749,14 +749,14 @@ namespace EMotionFX const size_t numLODs = GetNumLODLevels(); // for all LODs, get rid of all the morph setups for each geometry LOD - for (MorphSetup* mMorphSetup : mMorphSetups) + for (MorphSetup* morphSetup : mMorphSetups) { - if (mMorphSetup) + if (morphSetup) { - mMorphSetup->Destroy(); + morphSetup->Destroy(); } - mMorphSetup = nullptr; + morphSetup = nullptr; } // remove all modifiers from the stacks for each lod in all nodes diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index 126d376ae4..f394dc4f5f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -561,9 +561,9 @@ namespace EMotionFX // set the attachment matrices void ActorInstance::UpdateAttachments() { - for (Attachment* mAttachment : mAttachments) + for (Attachment* attachment : mAttachments) { - mAttachment->Update(); + attachment->Update(); } } @@ -1741,9 +1741,9 @@ namespace EMotionFX SetIsVisible(isVisible); // recurse to all child attachments - for (Attachment* mAttachment : mAttachments) + for (Attachment* attachment : mAttachments) { - mAttachment->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); + attachment->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp index c31f584498..9ed0a0e527 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp @@ -143,11 +143,11 @@ namespace EMotionFX { if (delFromMem) { - for (MCore::Attribute* mParamValue : mParamValues) + for (MCore::Attribute* paramValue : mParamValues) { - if (mParamValue) + if (paramValue) { - delete mParamValue; + delete paramValue; } } } @@ -930,9 +930,9 @@ namespace EMotionFX // reset all node flags void AnimGraphInstance::ResetFlagsForAllObjects(uint32 flagsToDisable) { - for (uint32& mObjectFlag : mObjectFlags) + for (uint32& objectFlag : mObjectFlags) { - mObjectFlag &= ~flagsToDisable; + objectFlag &= ~flagsToDisable; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h index 89f4db2e5d..31d85b6f48 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h @@ -97,16 +97,16 @@ namespace EMotionFX bool CheckIfIsCompatibleWith(const Port& otherPort) const { // check the data types - for (uint32 mCompatibleType : mCompatibleTypes) + for (uint32 compatibleType : mCompatibleTypes) { // If there aren't any more compatibility types and we haven't found a compatible one so far, return false - if (mCompatibleType == 0) + if (compatibleType == 0) { return false; } for (uint32 otherCompatibleTypeIndex : otherPort.mCompatibleTypes) { - if (otherCompatibleTypeIndex == mCompatibleType) + if (otherCompatibleTypeIndex == compatibleType) { return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp index 3314ff0a17..f7f3a6c0bf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp @@ -27,9 +27,9 @@ namespace EMotionFX AnimGraphPosePool::~AnimGraphPosePool() { // delete all poses - for (AnimGraphPose* mPose : mPoses) + for (AnimGraphPose* pose : mPoses) { - delete mPose; + delete pose; } mPoses.clear(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp index f4e7402fdf..1a04f18375 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp @@ -28,9 +28,9 @@ namespace EMotionFX AnimGraphRefCountedDataPool::~AnimGraphRefCountedDataPool() { // delete all items - for (AnimGraphRefCountedData*& mItem : mItems) + for (AnimGraphRefCountedData*& item : mItems) { - delete mItem; + delete item; } mItems.clear(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp index e710192afd..e2cc633012 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp @@ -60,9 +60,9 @@ namespace EMotionFX Importer::~Importer() { // remove all chunk processors - for (ChunkProcessor* mChunkProcessor : mChunkProcessors) + for (ChunkProcessor* chunkProcessor : mChunkProcessors) { - mChunkProcessor->Destroy(); + chunkProcessor->Destroy(); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index 135a37200c..450a546c27 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -374,9 +374,9 @@ namespace EMotionFX // copy all original data over the output data void Mesh::ResetToOriginalData() { - for (VertexAttributeLayer* mVertexAttribute : mVertexAttributes) + for (VertexAttributeLayer* vertexAttribute : mVertexAttributes) { - mVertexAttribute->ResetToOriginalData(); + vertexAttribute->ResetToOriginalData(); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp index 561e94b35b..e3fd1552b0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp @@ -88,17 +88,17 @@ namespace EMotionFX const size_t lodLevel = actorInstance->GetLODLevel(); // apply all deform passes - for (DeformPass& mDeformPasse : mDeformPasses) + for (DeformPass& deformPass : mDeformPasses) { // find the morph target - MorphTargetStandard* morphTarget = (MorphTargetStandard*)actor->GetMorphSetup(lodLevel)->FindMorphTargetByID(mDeformPasse.mMorphTarget->GetID()); + MorphTargetStandard* morphTarget = (MorphTargetStandard*)actor->GetMorphSetup(lodLevel)->FindMorphTargetByID(deformPass.mMorphTarget->GetID()); if (morphTarget == nullptr) { continue; } // get the deform data and number of vertices to deform - MorphTargetStandard::DeformData* deformData = morphTarget->GetDeformData(mDeformPasse.mDeformDataNr); + MorphTargetStandard::DeformData* deformData = morphTarget->GetDeformData(deformPass.mDeformDataNr); const uint32 numDeformVerts = deformData->mNumVerts; // this mesh deformer can't work on this mesh, because the deformdata number of vertices is bigger than the @@ -120,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 && mDeformPasse.mLastNearZero) + if (nearZero && deformPass.mLastNearZero) { continue; } @@ -128,11 +128,11 @@ namespace EMotionFX // update the flag if (nearZero) { - mDeformPasse.mLastNearZero = true; + deformPass.mLastNearZero = true; } else { - mDeformPasse.mLastNearZero = false; // we moved away from zero influence + deformPass.mLastNearZero = false; // we moved away from zero influence } // output data diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp index 069e7c971a..d4a70dd070 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp @@ -70,9 +70,9 @@ namespace EMotionFX // remove all morph targets void MorphSetup::RemoveAllMorphTargets() { - for (MorphTarget*& mMorphTarget : mMorphTargets) + for (MorphTarget*& morphTarget : mMorphTargets) { - mMorphTarget->Destroy(); + morphTarget->Destroy(); } mMorphTargets.clear(); @@ -176,9 +176,9 @@ namespace EMotionFX } // scale the morph targets - for (MorphTarget* mMorphTarget : mMorphTargets) + for (MorphTarget* morphTarget : mMorphTargets) { - mMorphTarget->Scale(scaleFactor); + morphTarget->Scale(scaleFactor); } } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp index 7612fd73d7..c86815be80 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp @@ -177,20 +177,20 @@ namespace EMotionFX const float normalizedWeight = CalcNormalizedWeight(newWeight); // convert in range of 0..1 // calculate the new transformations for all nodes of this morph target - for (const Transformation& mTransform : mTransforms) + for (const Transformation& transform : mTransforms) { // if this is the node that gets modified by this transform - if (mTransform.mNodeIndex != nodeIndex) + if (transform.mNodeIndex != nodeIndex) { continue; } - position += mTransform.mPosition * newWeight; - scale += mTransform.mScale * newWeight; + position += transform.mPosition * newWeight; + scale += transform.mScale * newWeight; // rotate additively const AZ::Quaternion& orgRot = actorInstance->GetTransformData()->GetBindPose()->GetLocalSpaceTransform(nodeIndex).mRotation; - const AZ::Quaternion rot = orgRot.NLerp(mTransform.mRotation, normalizedWeight); + const AZ::Quaternion rot = orgRot.NLerp(transform.mRotation, normalizedWeight); rotation = rotation * (orgRot.GetInverseFull() * rot); rotation.Normalize(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp index d31d81fe7a..a10a4722eb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp @@ -65,9 +65,9 @@ namespace EMotionFX MCORE_ASSERT(mData == nullptr); // delete all subpools - for (SubPool* mSubPool : mSubPools) + for (SubPool* subPool : mSubPools) { - delete mSubPool; + delete subPool; } mSubPools.clear(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp index 4c3ba95e59..b613ecc147 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp @@ -49,11 +49,11 @@ namespace EMotionFX void MotionLayerSystem::RemoveAllLayerPasses(bool delFromMem) { // delete all layer passes - for (LayerPass* mLayerPasse : mLayerPasses) + for (LayerPass* layerPass : mLayerPasses) { if (delFromMem) { - mLayerPasse->Destroy(); + layerPass->Destroy(); } } @@ -120,9 +120,9 @@ namespace EMotionFX mMotionQueue->Update(); // process all layer passes - for (LayerPass* mLayerPasse : mLayerPasses) + for (LayerPass* layerPass : mLayerPasses) { - mLayerPasse->Process(); + layerPass->Process(); } // process the repositioning as last diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp index 1954d23dc3..8472e46796 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp @@ -479,10 +479,10 @@ namespace EMotionFX size_t result = 0; // get the number of motion sets and iterate through them - for (const MotionSet* mMotionSet : mMotionSets) + for (const MotionSet* motionSet : mMotionSets) { // sum up the root motion sets - if (mMotionSet->GetParentSet() == nullptr) + if (motionSet->GetParentSet() == nullptr) { result++; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp index 1144cc3f42..4bb1d850c9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp @@ -90,9 +90,9 @@ namespace EMotionFX // copy the node attributes result->mAttributes.reserve(mAttributes.size()); - for (const NodeAttribute* mAttribute : mAttributes) + for (const NodeAttribute* attribute : mAttributes) { - result->AddAttribute(mAttribute->Clone()); + result->AddAttribute(attribute->Clone()); } // return the resulting clone diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp index 4ee3a24056..5f5c439f7c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp @@ -580,9 +580,9 @@ namespace EMotionFX void StandardMaterial::RemoveAllLayers() { - for (StandardMaterialLayer* mLayer : mLayers) + for (StandardMaterialLayer* layer : mLayers) { - mLayer->Destroy(); + layer->Destroy(); } mLayers.clear(); 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 55f7324b75..1aa8082f08 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp @@ -187,10 +187,10 @@ namespace EMStudio mHierarchy->clear(); // get the number actor instances and iterate over them - for (const uint32 mActorInstanceID : mActorInstanceIDs) + for (const uint32 actorInstanceID : mActorInstanceIDs) { // get the actor instance by its id - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(mActorInstanceID); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); if (actorInstance) { AddActorInstance(actorInstance); 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 d203e4386b..e1c22ee60d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp @@ -33,9 +33,9 @@ namespace EMStudio // compute the height of all notification windows with the spacing int allNotificationWindowsHeight = 0; - for (const NotificationWindow* mNotificationWindow : mNotificationWindows) + for (const NotificationWindow* currentNotificationWindow : mNotificationWindows) { - allNotificationWindowsHeight += mNotificationWindow->geometry().height() + notificationWindowSpacing; + allNotificationWindowsHeight += currentNotificationWindow->geometry().height() + notificationWindowSpacing; } // move the notification window @@ -81,15 +81,15 @@ namespace EMStudio // move each notification window int currentNotificationWindowHeight = notificationWindowMainWindowPadding; - for (NotificationWindow* mNotificationWindow : mNotificationWindows) + for (NotificationWindow* notificationWindow : mNotificationWindows) { // add the height of the notification window - currentNotificationWindowHeight += mNotificationWindow->geometry().height(); + currentNotificationWindowHeight += notificationWindow->geometry().height(); // move the notification window const QPoint mainWindowBottomRight = mainWindow->geometry().bottomRight(); - const QRect& notificationWindowGeometry = mNotificationWindow->geometry(); - mNotificationWindow->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/RenderPlugin/RenderPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.cpp index 506605fec4..d3e9593add 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 @@ -128,11 +128,11 @@ namespace EMStudio void RenderPlugin::CleanEMStudioActors() { // get rid of the actors - for (EMStudioRenderActor* mActor : mActors) + for (EMStudioRenderActor* actor : mActors) { - if (mActor) + if (actor) { - delete mActor; + delete actor; } } mActors.clear(); 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 f6b0b72bf6..4f29a15669 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 @@ -149,9 +149,9 @@ namespace EMStudio // remove all node connections void GraphNode::RemoveAllConnections() { - for (NodeConnection* mConnection : mConnections) + for (NodeConnection* connection : mConnections) { - delete mConnection; + delete connection; } mConnections.clear(); 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 19f28c36e0..3fd928c60c 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 @@ -1965,7 +1965,7 @@ namespace EMStudio // Modify each ID using the operation in the modified array. AZStd::string newMotionID; AZStd::string tempString; - for (const AZStd::string& mMotionID : mMotionIDs) + for (const AZStd::string& motionID : mMotionIDs) { // 0=Replace All, 1=Replace First, 2=Replace Last const int operationMode = mComboBox->currentIndex(); @@ -1975,7 +1975,7 @@ namespace EMStudio { case 0: { - tempString = mMotionID.c_str(); + tempString = motionID.c_str(); AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */); newMotionID = tempString.c_str(); break; @@ -1983,7 +1983,7 @@ namespace EMStudio case 1: { - tempString = mMotionID.c_str(); + tempString = motionID.c_str(); AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, true /* replace first */, false /* replace last */); newMotionID = tempString.c_str(); break; @@ -1991,7 +1991,7 @@ namespace EMStudio case 2: { - tempString = mMotionID.c_str(); + tempString = motionID.c_str(); AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, false /* replace first */, true /* replace last */); newMotionID = tempString.c_str(); break; @@ -1999,7 +1999,7 @@ namespace EMStudio } // change the value in the array and add the mapping motion to modified - auto iterator = AZStd::find(mModifiedMotionIDs.begin(), mModifiedMotionIDs.end(), mMotionID); + auto iterator = AZStd::find(mModifiedMotionIDs.begin(), mModifiedMotionIDs.end(), motionID); const size_t modifiedIndex = iterator - mModifiedMotionIDs.begin(); mModifiedMotionIDs[modifiedIndex] = newMotionID; mMotionToModifiedMap.push_back(modifiedIndex); 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 0f276d640d..c1c440d0d8 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 @@ -163,9 +163,9 @@ namespace EMStudio { if (delFromMem) { - for (TimeTrackElement* mElement : mElements) + for (TimeTrackElement* element : mElements) { - delete mElement; + delete element; } } 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 6ff8ea3775..6f8ab95891 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 @@ -107,9 +107,9 @@ namespace EMStudio delete mZoomOutCursor; // get rid of the motion infos - for (MotionInfo* mMotionInfo : mMotionInfos) + for (MotionInfo* motionInfo : mMotionInfos) { - delete mMotionInfo; + delete motionInfo; } } 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 bbfae05dff..06569b3bf3 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 @@ -453,9 +453,9 @@ namespace EMStudio // display the values and names int offset = 0; - for (const EMotionFX::Recorder::ExtractedNodeHistoryItem& mActiveItem : mActiveItems) + for (const EMotionFX::Recorder::ExtractedNodeHistoryItem& activeItem : mActiveItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = mActiveItem.mNodeHistoryItem; + EMotionFX::Recorder::NodeHistoryItem* curItem = activeItem.mNodeHistoryItem; if (curItem == nullptr) { continue; @@ -481,14 +481,14 @@ namespace EMStudio if (!mTempString.empty()) { - mTempString += AZStd::string::format(" = %.4f", mActiveItem.mValue); + mTempString += AZStd::string::format(" = %.4f", activeItem.mValue); } else { - mTempString = AZStd::string::format("%.4f", mActiveItem.mValue); + mTempString = AZStd::string::format("%.4f", activeItem.mValue); } - const AZ::Color colorCode = (useNodeColors) ? mActiveItem.mNodeHistoryItem->mTypeColor : mActiveItem.mNodeHistoryItem->mColor; + const AZ::Color colorCode = (useNodeColors) ? activeItem.mNodeHistoryItem->mTypeColor : activeItem.mNodeHistoryItem->mColor; QColor color; color.setRgbF(colorCode.GetR(), colorCode.GetG(), colorCode.GetB(), colorCode.GetA()); diff --git a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp index 4e89072f70..dc08f628fe 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp @@ -29,9 +29,9 @@ namespace MCore { Lock(); - for (AZStd::basic_string*& mString : mStrings) + for (AZStd::basic_string*& string : mStrings) { - delete mString; + delete string; } mStrings.clear(); diff --git a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp index 016664e017..3386e1a0d2 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp @@ -30,9 +30,9 @@ namespace MysticQt MysticQtManager::~MysticQtManager() { // get the number of icons and destroy them - for (IconData* mIcon : mIcons) + for (IconData* icon : mIcons) { - delete mIcon; + delete icon; } mIcons.clear(); } @@ -57,11 +57,11 @@ namespace MysticQt const QIcon& MysticQtManager::FindIcon(const char* filename) { // get the number of icons and iterate through them - for (IconData* mIcon : mIcons) + for (IconData* icon : mIcons) { - if (AzFramework::StringFunc::Equal(mIcon->mFileName.c_str(), filename, false /* no case */)) + if (AzFramework::StringFunc::Equal(icon->mFileName.c_str(), filename, false /* no case */)) { - return *(mIcon->mIcon); + return *(icon->mIcon); } } From f03df3e546277c278bd514bdecc06c3117c773a5 Mon Sep 17 00:00:00 2001 From: amzn-phist <52085794+amzn-phist@users.noreply.github.com> Date: Mon, 9 Aug 2021 11:51:06 -0500 Subject: [PATCH 193/251] Fix issues with audio localization bank switching (#2945) * Fix issues with locating and loading loc banks The code that initially checked the g_languageAudio cvar wasn't properly detecting when the cvar wasn't set. Fixed an issue discovering localized banks wasn't properly recursing into subdirectories. Simplified handling of audio language switching for Wwise. Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> * Address feedback on PR Change .size() == 0 to .empty() Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> --- Code/Legacy/CrySystem/SystemInit.cpp | 16 +++++++--------- .../Code/Source/Editor/AudioWwiseLoader.cpp | 6 ++++-- .../Code/Source/Engine/AudioSystemImpl_wwise.cpp | 11 +---------- 3 files changed, 12 insertions(+), 21 deletions(-) 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/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 += "/"; From 12579e5d2e3e477a8bbc26cc5414102504df9e3e Mon Sep 17 00:00:00 2001 From: Nicholas Lawson <70027408+lawsonamzn@users.noreply.github.com> Date: Mon, 9 Aug 2021 10:05:25 -0700 Subject: [PATCH 194/251] Fixes incorrect build dependencies for tests (#2959) The serialize context tools were not being auto built by CI because of this. Added missing dependency on AzTestRunner. Also moved the AssetBundlerBatch dependency directly in there No reason to add it to additional_dependnecies, since its only used for conditional inclusions. Signed-off-by: lawsonamzn <70027408+lawsonamzn@users.noreply.github.com> --- AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 600911e9f1..e84128ad1a 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,7 +25,9 @@ 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 ) From fb3195d9962e5efe1002dc7a28179db74793b4da Mon Sep 17 00:00:00 2001 From: Artur K <96597+nemerle@users.noreply.github.com> Date: Mon, 9 Aug 2021 19:05:55 +0200 Subject: [PATCH 195/251] Reduce size of AllocationInfo struct to 64 bytes ( was 72 ) (#2771) Signed-off-by: nemerle <96597+nemerle@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/Memory/AllocationRecords.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) 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. */ From fceb29fa5f4ee42af1eb98c1517de2acf850f151 Mon Sep 17 00:00:00 2001 From: Nemerle Date: Fri, 6 Aug 2021 14:06:59 +0200 Subject: [PATCH 196/251] Editor: code style fixups in 2 files A few small fixes ( for range loops + one -> check) Signed-off-by: Nemerle --- Code/Editor/PluginManager.cpp | 22 +++++++++------------- Code/Editor/ResourceSelectorHost.cpp | 8 ++------ 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/Code/Editor/PluginManager.cpp b/Code/Editor/PluginManager.cpp index 5efd52a97e..1530641fa7 100644 --- a/Code/Editor/PluginManager.cpp +++ b/Code/Editor/PluginManager.cpp @@ -17,9 +17,8 @@ // Editor #include "Include/IPlugin.h" - -using TPfnCreatePluginInstance = IPlugin *(*)(PLUGIN_INIT_PARAM *pInitParam); -using TPfnQueryPluginSettings = void (*)(SPluginSettings &); +using TPfnCreatePluginInstance = IPlugin* (*)(PLUGIN_INIT_PARAM* pInitParam); +using TPfnQueryPluginSettings = void (*)(SPluginSettings&); CPluginManager::CPluginManager() { @@ -155,7 +154,7 @@ bool CPluginManager::LoadPlugins(const char* pPathWithMask) } #endif } - if (plugins.size() == 0) + if (plugins.empty()) { CLogFile::FormatLine("[Plugin Manager] Cannot find any plugins in plugin directory '%s'", strPath.toUtf8().data()); return false; @@ -269,13 +268,13 @@ void CPluginManager::RegisterPlugin(QLibrary* dllHandle, IPlugin* pPlugin) IPlugin* CPluginManager::GetPluginByGUID(const char* pGUID) { - for (auto it = m_plugins.begin(); it != m_plugins.end(); ++it) + for (const SPluginEntry& pluginEntry : m_plugins) { - const char* pPluginGuid = it->pPlugin->GetPluginGUID(); + const char* pPluginGuid = pluginEntry.pPlugin->GetPluginGUID(); if (pPluginGuid && !strcmp(pPluginGuid, pGUID)) { - return it->pPlugin; + return pluginEntry.pPlugin; } } @@ -332,14 +331,11 @@ IUIEvent* CPluginManager::GetEventByIDAndPluginID(uint8 aPluginID, uint8 aEventI bool CPluginManager::CanAllPluginsExitNow() { - for (auto it = m_plugins.begin(); it != m_plugins.end(); ++it) + for (const SPluginEntry& pluginEntry : m_plugins) { - if (it->pPlugin) + if (pluginEntry.pPlugin && !pluginEntry.pPlugin->CanExitNow()) { - if (!it->pPlugin->CanExitNow()) - { - return false; - } + return false; } } diff --git a/Code/Editor/ResourceSelectorHost.cpp b/Code/Editor/ResourceSelectorHost.cpp index af6c398fe7..39d36346e7 100644 --- a/Code/Editor/ResourceSelectorHost.cpp +++ b/Code/Editor/ResourceSelectorHost.cpp @@ -75,11 +75,7 @@ public: void SetGlobalSelection(const char* resourceType, const char* value) override { - if (!resourceType) - { - return; - } - if (!value) + if (!resourceType || !value) { return; } @@ -101,7 +97,7 @@ public: } private: - using TTypeMap = std::map>; + using TTypeMap = std::map>; TTypeMap m_typeMap; std::map m_globallySelectedResources; From b21b0e12e402c8c63de01d16d51d4c223edf294b Mon Sep 17 00:00:00 2001 From: Cynthia Lin <15116870+synicalsyntax@users.noreply.github.com> Date: Mon, 9 Aug 2021 10:32:31 -0700 Subject: [PATCH 197/251] fix: Switch local environment detection to depend on BUILD_NUMBER instead of CI (#2962) CI is only available on Jenkins v2.289.1, nightly builds are still run on Jenkins 2.277.4 Signed-off-by: Cynthia Lin --- Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py b/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py index b5b75508ec..12681450de 100644 --- a/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py +++ b/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py @@ -22,7 +22,7 @@ class BenchmarkDataAggregator(object): def __init__(self, workspace, logger, test_suite): 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): From 6bf6ae948526d9fb6b4f0641fe95ae423c9c5452 Mon Sep 17 00:00:00 2001 From: Artur K <96597+nemerle@users.noreply.github.com> Date: Mon, 9 Aug 2021 20:06:29 +0200 Subject: [PATCH 198/251] Editor code: tidy up BOOLs,NULLs and overrides pt5. (#2876) A few 'typedefs' replaced by 'using's This shouldn't have any functional changes at all, just c++17 modernization It's a part 5 of a split #2847 Signed-off-by: Nemerle Co-authored-by: Nemerle --- Code/Editor/AboutDialog.cpp | 2 +- Code/Editor/AnimationContext.cpp | 14 ++--- Code/Editor/BaseLibrary.cpp | 22 +++---- Code/Editor/BaseLibraryItem.cpp | 20 +++---- Code/Editor/BaseLibraryManager.cpp | 42 +++++++------- Code/Editor/CheckOutDialog.h | 2 +- Code/Editor/ConfigGroup.cpp | 12 ++-- Code/Editor/ConfigGroup.h | 4 +- Code/Editor/ControlMRU.cpp | 10 ++-- Code/Editor/CrtDebug.cpp | 2 +- Code/Editor/CryEdit.cpp | 76 ++++++++++++------------- Code/Editor/CryEdit.h | 24 ++++---- Code/Editor/CryEditDoc.cpp | 66 ++++++++++----------- Code/Editor/CryEditDoc.h | 10 ++-- Code/Editor/CryEditPy.cpp | 2 +- Code/Editor/CustomAspectRatioDlg.cpp | 2 +- Code/Editor/CustomResolutionDlg.cpp | 8 +-- Code/Editor/CustomizeKeyboardDialog.cpp | 4 +- Code/Editor/EditorDefs.h | 7 +-- Code/Editor/EditorFileMonitor.cpp | 2 +- Code/Editor/EditorFileMonitor.h | 2 +- Code/Editor/EditorPanelUtils.cpp | 46 +++++++-------- Code/Editor/EditorPreferencesDialog.cpp | 2 +- Code/Editor/ErrorReport.cpp | 4 +- Code/Editor/ErrorReportDialog.cpp | 16 +++--- Code/Editor/ErrorReportTableModel.cpp | 2 +- Code/Editor/GameEngine.cpp | 32 +++++------ Code/Editor/GameExporter.cpp | 4 +- Code/Editor/GenericSelectItemDialog.cpp | 2 +- Code/Editor/IEditor.h | 4 +- Code/Editor/IEditorImpl.cpp | 28 ++++----- Code/Editor/IEditorImpl.h | 8 +-- Code/Editor/IconManager.cpp | 10 ++-- Code/Editor/LayoutConfigDialog.cpp | 2 +- Code/Editor/LayoutWnd.cpp | 4 +- 35 files changed, 248 insertions(+), 249 deletions(-) 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 d557a8635c..6e146faacb 100644 --- a/Code/Editor/AnimationContext.cpp +++ b/Code/Editor/AnimationContext.cpp @@ -28,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) { @@ -48,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; @@ -69,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; } @@ -103,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; @@ -221,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()); @@ -337,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/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 ae03b03af5..8cede89f8a 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -266,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(); @@ -286,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] == '\"') { @@ -311,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) { @@ -324,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); } ////////////////////////////////////////////////////////////////////////////// @@ -460,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) @@ -653,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(); @@ -801,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(); @@ -847,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(); @@ -1055,7 +1055,7 @@ AZ::Outcome CCryEditApp::InitGameSystem(HWND hwndForInputSy } ///////////////////////////////////////////////////////////////////////////// -BOOL CCryEditApp::CheckIfAlreadyRunning() +bool CCryEditApp::CheckIfAlreadyRunning() { bool bForceNewInstance = false; @@ -1299,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()) @@ -1431,7 +1431,7 @@ struct CCryEditApp::PythonOutputHandler AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusConnect(); } - virtual ~PythonOutputHandler() + ~PythonOutputHandler() override { AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); } @@ -1463,7 +1463,7 @@ struct PythonTestOutputHandler final : public CCryEditApp::PythonOutputHandler { PythonTestOutputHandler() = default; - virtual ~PythonTestOutputHandler() = default; + ~PythonTestOutputHandler() override = default; void OnTraceMessage(AZStd::string_view message) override { @@ -1589,7 +1589,7 @@ void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo) ///////////////////////////////////////////////////////////////////////////// // CCryEditApp initialization -BOOL CCryEditApp::InitInstance() +bool CCryEditApp::InitInstance() { QElapsedTimer startupTimer; startupTimer.start(); @@ -1616,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... @@ -1759,7 +1759,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(); @@ -1844,8 +1844,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) { @@ -1858,7 +1858,7 @@ void CCryEditApp::UnregisterEventLoopHook(IEventLoopHook* pHookToRemove) m_pEventLoopHook = pHookToRemove->pNextHook; } - pHookToRemove->pNextHook = 0; + pHookToRemove->pNextHook = nullptr; return; } } @@ -1881,7 +1881,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); @@ -1922,7 +1922,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" ); } @@ -2259,7 +2259,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) { @@ -2267,7 +2267,7 @@ BOOL CCryEditApp::OnIdle([[maybe_unused]] LONG lCount) } else { - return 0; + return false; } } @@ -3142,7 +3142,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()); @@ -3230,11 +3230,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); @@ -3759,7 +3759,7 @@ bool CCryEditApp::IsInRegularEditorMode() void CCryEditApp::OnOpenQuickAccessBar() { - if (m_pQuickAccessBar == NULL) + if (m_pQuickAccessBar == nullptr) { return; } @@ -4107,7 +4107,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 56b617969e..e372baf365 100644 --- a/Code/Editor/CryEditDoc.cpp +++ b/Code/Editor/CryEditDoc.cpp @@ -97,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; } @@ -263,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(); @@ -305,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); @@ -483,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); } } } @@ -667,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 @@ -676,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() @@ -735,7 +735,7 @@ bool CCryEditDoc::OnOpenDocument(const QString& lpszPathName) TOpenDocContext context; if (!BeforeOpenDocument(lpszPathName, context)) { - return FALSE; + return false; } return DoOpenDocument(context); } @@ -778,7 +778,7 @@ bool CCryEditDoc::BeforeOpenDocument(const QString& lpszPathName, TOpenDocContex context.absoluteLevelPath = absolutePath; context.absoluteSlicePath = ""; } - return TRUE; + return true; } bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) @@ -815,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)) @@ -827,7 +827,7 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) if (m_bLoadFailed) { - return FALSE; + return false; } // Load AZ entities for the editor. @@ -848,7 +848,7 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) if (m_bLoadFailed) { - return FALSE; + return false; } StartStreamingLoad(); @@ -865,7 +865,7 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) // level. SetLevelExported(true); - return TRUE; + return true; } bool CCryEditDoc::OnNewDocument() @@ -961,7 +961,7 @@ bool CCryEditDoc::BeforeSaveDocument(const QString& lpszPathName, TSaveDocContex bool bSaved(true); context.bSaved = bSaved; - return TRUE; + return true; } bool CCryEditDoc::HasLayerNameConflicts() const @@ -1046,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(); } @@ -1598,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); @@ -1608,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); @@ -1984,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) { @@ -2002,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(); @@ -2065,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); @@ -2079,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; } @@ -2103,7 +2103,7 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) XmlNodeRef groupNode = node->getChild(nGroup); - if (groupNode == NULL) + if (groupNode == nullptr) { return; } @@ -2114,7 +2114,7 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) } XmlNodeRef childNode = groupNode->getChild(nChild); - if (childNode == NULL) + if (childNode == nullptr) { return; } @@ -2141,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(); @@ -2150,7 +2150,7 @@ BOOL CCryEditDoc::LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& CXmlArchive* pXmlAr = new CXmlArchive(); if (!pXmlAr) { - return FALSE; + return false; } CXmlArchive& xmlAr = *pXmlAr; @@ -2161,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; @@ -2169,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/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/GameEngine.cpp b/Code/Editor/GameEngine.cpp index 23966c1049..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) { @@ -866,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; } } From bb88f1f9df98592129460f322cab9b661803606c Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Mon, 9 Aug 2021 11:24:25 -0700 Subject: [PATCH 199/251] Fix input not working in Ctrl-G mode after UI Editor is opened (#2948) * Fix input not working in Ctrl-G mode after UI Editor is opened Signed-off-by: abrmich * Delete environment variable Signed-off-by: abrmich --- .../Keyboard/InputDeviceKeyboard_Windows.cpp | 22 ++++++++++++--- .../Mouse/InputDeviceMouse_Windows.cpp | 28 ++++++++++++++----- 2 files changed, 39 insertions(+), 11 deletions(-) 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); } } From c7397fe4a2eea9cdb2ff3a5f59fc91f67e20ea29 Mon Sep 17 00:00:00 2001 From: Junbo Liang <68558268+junbo75@users.noreply.github.com> Date: Mon, 9 Aug 2021 13:00:43 -0700 Subject: [PATCH 200/251] Fix AWSTests.periodic failing on Linux due to a File Not Found error Signed-off-by: junbo --- AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt | 5 +++++ 1 file changed, 5 insertions(+) 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 From cb52418a92d083dd3e0de3e2edc538f08760fd15 Mon Sep 17 00:00:00 2001 From: lsemp3d <58790905+lsemp3d@users.noreply.github.com> Date: Mon, 9 Aug 2021 13:05:23 -0700 Subject: [PATCH 201/251] Open the EMFX editor even if no asset is specified Signed-off-by: lsemp3d <58790905+lsemp3d@users.noreply.github.com> --- .../Editor/Components/EditorAnimGraphComponent.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorAnimGraphComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorAnimGraphComponent.cpp index eef41bc919..8721acbf3d 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorAnimGraphComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorAnimGraphComponent.cpp @@ -117,16 +117,16 @@ namespace EMotionFX void EditorAnimGraphComponent::LaunchAnimationEditor(const AZ::Data::AssetId& assetId, [[maybe_unused]] const AZ::Data::AssetType& assetType) { + // call to open must be done before LoadCharacter + const char* panelName = EMStudio::MainWindow::GetEMotionFXPaneName(); + EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, OpenViewPane, panelName); + if (assetId.IsValid()) { AZ::Data::AssetId actorAssetId; actorAssetId.SetInvalid(); EditorActorComponentRequestBus::EventResult(actorAssetId, GetEntityId(), &EditorActorComponentRequestBus::Events::GetActorAssetId); - // call to open must be done before LoadCharacter - const char* panelName = EMStudio::MainWindow::GetEMotionFXPaneName(); - EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, OpenViewPane, panelName); - EMStudio::MainWindow* mainWindow = EMStudio::GetMainWindow(); if (mainWindow) { From 89602aaa63a7dba0b1aea611750c4f5e2058fda4 Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Mon, 9 Aug 2021 13:06:28 -0700 Subject: [PATCH 202/251] [SPEC-7931] Filter list_buckets results based on region during import (#2950) Filter s3 list_buckets results based on region correctly to improve resource import. Signed-off-by: onecent1101 --- .../tests/unit/utils/test_aws_utils.py | 44 +++++++++++++++++-- .../ResourceMappingTool/utils/aws_utils.py | 12 ++++- 2 files changed, 51 insertions(+), 5 deletions(-) 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/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 From cf7681df2741188679fbb397487d3bc46ad30d86 Mon Sep 17 00:00:00 2001 From: Nicholas Lawson <70027408+lawsonamzn@users.noreply.github.com> Date: Mon, 9 Aug 2021 13:16:24 -0700 Subject: [PATCH 203/251] Updates the zlib that O3DE uses to the one in 3p-package-source (#2861) * Updates o3de to use the new zlib packages. Packages were uploaded for every supported platform. Signed-off-by: lawsonamzn <70027408+lawsonamzn@users.noreply.github.com> --- cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake | 2 +- cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake | 4 +++- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) 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) From c1a0b5c686823fe8a8fc45ded52ef1020df84eec Mon Sep 17 00:00:00 2001 From: Cynthia Lin <15116870+synicalsyntax@users.noreply.github.com> Date: Mon, 9 Aug 2021 14:57:52 -0700 Subject: [PATCH 204/251] performance benchmarks: Aggregate and report CPU frame times. (#2939) * Add CaptureCpuFrameTime method to ProfilingCaptureSystemComponent for monitoring CPU performance. Signed-off-by: Cynthia Lin * ly_test_tools: Refactor benchmark data aggregator in preparation for CPU frame times. Signed-off-by: Cynthia Lin * performance benchmarks: Aggregate and report CPU frame times based on JSON data. Signed-off-by: Cynthia Lin * AutomatedTesting: Capture CPU frame time in AtomFeatureIntegrationBenchmark. Signed-off-by: Cynthia Lin --- ...GPUTest_AtomFeatureIntegrationBenchmark.py | 1 + .../atom_utils/benchmark_utils.py | 19 +++ .../atom_renderer/test_Atom_GPUTests.py | 2 + .../Atom/Feature/Utils/ProfilingCaptureBus.h | 8 + .../ProfilingCaptureSystemComponent.cpp | 110 ++++++++++++- .../Source/ProfilingCaptureSystemComponent.h | 2 + .../benchmark/data_aggregator.py | 149 ++++++++++++------ 7 files changed, 245 insertions(+), 46 deletions(-) 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/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..03f522ba44 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,6 +22,9 @@ 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; @@ -44,6 +47,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..1e2d549e7a 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 @@ -34,6 +37,7 @@ namespace AZ public: AZ_EBUS_BEHAVIOR_BINDER(ProfilingCaptureNotificationBusHandler, "{E45E4F37-EC1F-4010-994B-4F80998BEF15}", AZ::SystemAllocator, OnCaptureQueryTimestampFinished, + OnCaptureCpuFrameTimeFinished, OnCaptureQueryPipelineStatisticsFinished, OnCaptureCpuProfilingStatisticsFinished, OnCaptureBenchmarkMetadataFinished @@ -44,6 +48,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 +104,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 { @@ -248,6 +270,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) @@ -408,6 +448,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 +458,7 @@ namespace AZ } TimestampSerializer::Reflect(context); + CpuFrameTimeSerializer::Reflect(context); PipelineStatisticsSerializer::Reflect(context); CpuProfilingStatisticsSerializer::Reflect(context); BenchmarkMetadataSerializer::Reflect(context); @@ -484,6 +526,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. @@ -666,12 +773,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..c401d27f30 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h +++ b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h @@ -68,6 +68,7 @@ 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 CaptureBenchmarkMetadata(const AZStd::string& benchmarkName, const AZStd::string& outputFilePath) override; @@ -81,6 +82,7 @@ namespace AZ AZStd::vector FindPasses(AZStd::vector&& passHierarchy) const; DelayedQueryCaptureHelper m_timestampCapture; + DelayedQueryCaptureHelper m_cpuFrameTimeStatisticsCapture; DelayedQueryCaptureHelper m_pipelineStatisticsCapture; DelayedQueryCaptureHelper m_cpuProfilingStatisticsCapture; DelayedQueryCaptureHelper m_benchmarkMetadataCapture; diff --git a/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py b/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py index 12681450de..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('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( From 9afbd07a88be54c62515c8a368b6327f4367d141 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 9 Aug 2021 16:58:19 -0500 Subject: [PATCH 205/251] Added new feature to the register command to auto detect manifest file based on input path (#2967) * Added new feature to the register command to auto detect the correct o3de manifest file to write to based on the supplied registration path Updated the create-gem command to register the gem on creation. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Added new feature to the register command to auto detect the correct o3de manifest file to write to based on the supplied registration path Updated the create-gem command to register the gem on creation. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Fix incorrect variable reference in register_project_path Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Fixed o3de python package unit test The enable_gem, register and engine template test have been updated to account for the logic to register a gem after creation Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Added a --no-register arg to engine-template.py This allows registration of gems/projects using the create-project and create-gem commands to be skipped Prevented registration of a gems and projects in the engine_template command test Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Wrapped first parameter to find_ancestor_dir_containing_file with pathlib.PurePath Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- scripts/o3de/o3de/engine_template.py | 18 ++- scripts/o3de/o3de/register.py | 29 +++- scripts/o3de/o3de/utils.py | 51 ++++++- scripts/o3de/tests/unit_test_enable_gem.py | 2 +- .../o3de/tests/unit_test_engine_template.py | 7 +- scripts/o3de/tests/unit_test_register.py | 136 ++++++++++++++++++ 6 files changed, 233 insertions(+), 10 deletions(-) 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', [])) From 8571e71d93f574254a8ead1a24ce4dc09b40414a Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Mon, 9 Aug 2021 15:42:55 -0700 Subject: [PATCH 206/251] Add JSON serializer support for the Lua component properties Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- .gitignore | 1 + .../AzCore/AzCore/Script/ScriptProperty.cpp | 50 ---------- .../AzCore/AzCore/Script/ScriptProperty.h | 28 ------ .../Script/ScriptPropertySerializer.cpp | 99 +++++++++++++++++++ .../AzCore/Script/ScriptPropertySerializer.h | 37 +++++++ .../AzCore/Script/ScriptSystemComponent.cpp | 19 ++-- .../DynamicSerializableField.cpp | 6 +- .../Serialization/DynamicSerializableField.h | 7 +- .../AzCore/AzCore/Slice/SliceComponent.h | 1 - .../AzCore/AzCore/azcore_files.cmake | 2 + .../ToolsComponents/ScriptEditorComponent.cpp | 10 -- .../Internal/VersionedProperty.cpp | 1 - 12 files changed, 160 insertions(+), 101 deletions(-) create mode 100644 Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.cpp create mode 100644 Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.h 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/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/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/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/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 From c6fdb76aedf74a760f314f8074a05743560e7927 Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Mon, 9 Aug 2021 16:33:54 -0700 Subject: [PATCH 207/251] Bump version number on LuaBuilderComponent Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- .../Code/Source/Builders/LuaBuilder/LuaBuilderComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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(); From 1837d0516968fa9373f5ff5c079effb1a208da0a Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 9 Aug 2021 14:09:45 -0700 Subject: [PATCH 208/251] Rename EMotionFX class members to follow the `m_` naming convention Signed-off-by: Chris Burel --- .../EMotionFXAtom/Code/Source/ActorAsset.cpp | 4 +- .../Code/Source/AtomActorInstance.cpp | 6 +- .../CommandSystem/Source/ActorCommands.cpp | 102 +-- .../CommandSystem/Source/ActorCommands.h | 38 +- .../Source/ActorInstanceCommands.cpp | 82 +- .../Source/ActorInstanceCommands.h | 34 +- .../Source/AnimGraphCommands.cpp | 96 +- .../CommandSystem/Source/AnimGraphCommands.h | 20 +- .../Source/AnimGraphConnectionCommands.cpp | 186 ++-- .../Source/AnimGraphConnectionCommands.h | 94 +- .../AnimGraphGroupParameterCommands.cpp | 68 +- .../Source/AnimGraphGroupParameterCommands.h | 20 +- .../Source/AnimGraphNodeCommands.cpp | 178 ++-- .../Source/AnimGraphNodeCommands.h | 68 +- .../Source/AnimGraphNodeGroupCommands.cpp | 30 +- .../Source/AnimGraphNodeGroupCommands.h | 14 +- .../Source/AnimGraphParameterCommands.cpp | 100 +- .../Source/AnimGraphParameterCommands.h | 46 +- .../CommandSystem/Source/CommandManager.cpp | 4 +- .../CommandSystem/Source/CommandManager.h | 18 +- .../CommandSystem/Source/ImporterCommands.cpp | 40 +- .../CommandSystem/Source/ImporterCommands.h | 12 +- .../CommandSystem/Source/MetaData.cpp | 2 +- .../Source/MorphTargetCommands.cpp | 24 +- .../Source/MorphTargetCommands.h | 12 +- .../CommandSystem/Source/MotionCommands.cpp | 168 ++-- .../CommandSystem/Source/MotionCommands.h | 30 +- .../Source/MotionEventCommands.cpp | 20 +- .../Source/MotionEventCommands.h | 10 +- .../Source/MotionSetCommands.cpp | 82 +- .../CommandSystem/Source/MotionSetCommands.h | 26 +- .../Source/NodeGroupCommands.cpp | 22 +- .../CommandSystem/Source/NodeGroupCommands.h | 6 +- .../CommandSystem/Source/RagdollCommands.cpp | 4 +- .../Source/SelectionCommands.cpp | 18 +- .../CommandSystem/Source/SelectionCommands.h | 2 +- .../CommandSystem/Source/SelectionList.cpp | 80 +- .../CommandSystem/Source/SelectionList.h | 96 +- .../ExporterLib/Exporter/EndianConversion.cpp | 124 +-- .../ExporterLib/Exporter/ExporterActor.cpp | 18 +- .../ExporterLib/Exporter/FileHeaderExport.cpp | 91 +- .../ExporterLib/Exporter/MaterialExport.cpp | 298 ------ .../ExporterLib/Exporter/MeshExport.cpp | 270 ------ .../Exporter/MorphTargetExport.cpp | 68 +- .../Exporter/MotionEventExport.cpp | 6 +- .../ExporterLib/Exporter/NodeExport.cpp | 110 +-- .../Exporter/SkeletalMotionExport.cpp | 6 +- .../ExporterLib/Exporter/SkinExport.cpp | 186 ---- .../EMotionFX/Rendering/Common/Camera.cpp | 42 +- .../Code/EMotionFX/Rendering/Common/Camera.h | 40 +- .../EMotionFX/Rendering/Common/Camera.inl | 42 +- .../Rendering/Common/FirstPersonCamera.cpp | 26 +- .../Rendering/Common/FirstPersonCamera.h | 18 +- .../Rendering/Common/LookAtCamera.cpp | 8 +- .../EMotionFX/Rendering/Common/LookAtCamera.h | 12 +- .../Rendering/Common/OrbitCamera.cpp | 176 ++-- .../EMotionFX/Rendering/Common/OrbitCamera.h | 56 +- .../Rendering/Common/OrthographicCamera.cpp | 192 ++-- .../Rendering/Common/OrthographicCamera.h | 40 +- .../EMotionFX/Rendering/Common/RenderUtil.cpp | 545 ++++++----- .../EMotionFX/Rendering/Common/RenderUtil.h | 228 +++-- .../Rendering/Common/RotateManipulator.cpp | 371 ++++---- .../Rendering/Common/RotateManipulator.h | 54 +- .../Rendering/Common/ScaleManipulator.cpp | 294 +++--- .../Rendering/Common/ScaleManipulator.h | 44 +- .../Common/TransformationManipulator.h | 110 +-- .../Rendering/Common/TranslateManipulator.cpp | 256 +++--- .../Rendering/Common/TranslateManipulator.h | 32 +- .../Rendering/OpenGL2/Source/GBuffer.cpp | 147 ++- .../Rendering/OpenGL2/Source/GBuffer.h | 36 +- .../Rendering/OpenGL2/Source/GLActor.cpp | 230 ++--- .../Rendering/OpenGL2/Source/GLExtensions.cpp | 2 +- .../Rendering/OpenGL2/Source/GLExtensions.h | 2 +- .../Rendering/OpenGL2/Source/GLRenderUtil.cpp | 282 +++--- .../Rendering/OpenGL2/Source/GLRenderUtil.h | 48 +- .../Rendering/OpenGL2/Source/GLSLShader.cpp | 184 ++-- .../Rendering/OpenGL2/Source/GLSLShader.h | 34 +- .../OpenGL2/Source/GraphicsManager.cpp | 233 ++--- .../OpenGL2/Source/GraphicsManager.h | 218 ++--- .../Rendering/OpenGL2/Source/IndexBuffer.cpp | 26 +- .../Rendering/OpenGL2/Source/IndexBuffer.h | 8 +- .../Rendering/OpenGL2/Source/Material.cpp | 4 +- .../Rendering/OpenGL2/Source/Material.h | 48 +- .../OpenGL2/Source/PostProcessShader.cpp | 14 +- .../OpenGL2/Source/PostProcessShader.h | 2 +- .../OpenGL2/Source/RenderTexture.cpp | 66 +- .../Rendering/OpenGL2/Source/RenderTexture.h | 14 +- .../Rendering/OpenGL2/Source/ShaderCache.cpp | 22 +- .../OpenGL2/Source/StandardMaterial.cpp | 176 ++-- .../OpenGL2/Source/StandardMaterial.h | 18 +- .../Rendering/OpenGL2/Source/TextureCache.cpp | 60 +- .../Rendering/OpenGL2/Source/TextureCache.h | 26 +- .../Rendering/OpenGL2/Source/VertexBuffer.cpp | 26 +- .../Rendering/OpenGL2/Source/VertexBuffer.h | 8 +- .../Rendering/OpenGL2/Source/glactor.h | 42 +- .../Rendering/OpenGL2/Source/shadercache.h | 6 +- .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 651 +++++++------ Gems/EMotionFX/Code/EMotionFX/Source/Actor.h | 110 +-- .../Code/EMotionFX/Source/ActorInstance.cpp | 482 +++++----- .../Code/EMotionFX/Source/ActorInstance.h | 100 +- .../Code/EMotionFX/Source/ActorManager.cpp | 78 +- .../Code/EMotionFX/Source/ActorManager.h | 18 +- .../EMotionFX/Source/ActorUpdateScheduler.h | 12 +- .../Code/EMotionFX/Source/AnimGraph.cpp | 168 ++-- .../Code/EMotionFX/Source/AnimGraph.h | 32 +- .../Source/AnimGraphAttributeTypes.h | 32 +- .../Source/AnimGraphBindPoseNode.cpp | 2 +- .../EMotionFX/Source/AnimGraphEntryNode.cpp | 2 +- .../EMotionFX/Source/AnimGraphEventBuffer.cpp | 18 +- .../EMotionFX/Source/AnimGraphExitNode.cpp | 8 +- .../Source/AnimGraphGameControllerSettings.h | 12 +- .../EMotionFX/Source/AnimGraphHubNode.cpp | 2 +- .../EMotionFX/Source/AnimGraphInstance.cpp | 228 ++--- .../Code/EMotionFX/Source/AnimGraphInstance.h | 74 +- .../EMotionFX/Source/AnimGraphManager.cpp | 100 +- .../Code/EMotionFX/Source/AnimGraphManager.h | 20 +- .../Source/AnimGraphMotionCondition.cpp | 12 +- .../Source/AnimGraphMotionCondition.h | 2 +- .../EMotionFX/Source/AnimGraphMotionNode.cpp | 180 ++-- .../EMotionFX/Source/AnimGraphMotionNode.h | 8 +- .../Code/EMotionFX/Source/AnimGraphNode.cpp | 516 +++++------ .../Code/EMotionFX/Source/AnimGraphNode.h | 194 ++-- .../EMotionFX/Source/AnimGraphNodeData.cpp | 58 +- .../Code/EMotionFX/Source/AnimGraphNodeData.h | 90 +- .../EMotionFX/Source/AnimGraphNodeGroup.cpp | 58 +- .../EMotionFX/Source/AnimGraphNodeGroup.h | 8 +- .../Code/EMotionFX/Source/AnimGraphObject.cpp | 26 +- .../Code/EMotionFX/Source/AnimGraphObject.h | 12 +- .../EMotionFX/Source/AnimGraphObjectData.cpp | 6 +- .../EMotionFX/Source/AnimGraphObjectData.h | 30 +- .../Source/AnimGraphParameterAction.cpp | 12 +- .../Source/AnimGraphParameterCondition.cpp | 16 +- .../Source/AnimGraphPlayTimeCondition.cpp | 4 +- .../Code/EMotionFX/Source/AnimGraphPose.cpp | 14 +- .../Code/EMotionFX/Source/AnimGraphPose.h | 20 +- .../EMotionFX/Source/AnimGraphPosePool.cpp | 41 +- .../Code/EMotionFX/Source/AnimGraphPosePool.h | 16 +- .../Source/AnimGraphRefCountedData.h | 28 +- .../Source/AnimGraphRefCountedDataPool.cpp | 40 +- .../Source/AnimGraphRefCountedDataPool.h | 16 +- .../Source/AnimGraphReferenceNode.cpp | 58 +- .../EMotionFX/Source/AnimGraphSnapshot.cpp | 2 +- .../Source/AnimGraphStateCondition.cpp | 40 +- .../Source/AnimGraphStateCondition.h | 10 +- .../Source/AnimGraphStateMachine.cpp | 216 ++--- .../EMotionFX/Source/AnimGraphStateMachine.h | 18 +- .../Source/AnimGraphStateTransition.cpp | 174 ++-- .../Source/AnimGraphStateTransition.h | 32 +- .../EMotionFX/Source/AnimGraphSyncTrack.cpp | 2 +- .../Source/AnimGraphTagCondition.cpp | 2 +- .../Source/AnimGraphTimeCondition.cpp | 16 +- .../EMotionFX/Source/AnimGraphTimeCondition.h | 4 +- .../Source/AnimGraphTransitionCondition.cpp | 4 +- .../Source/AnimGraphTriggerAction.cpp | 4 +- .../Source/AnimGraphVector2Condition.cpp | 8 +- .../EMotionFX/Source/BlendSpace1DNode.cpp | 32 +- .../EMotionFX/Source/BlendSpace2DNode.cpp | 44 +- .../Code/EMotionFX/Source/BlendSpaceNode.cpp | 6 +- .../Code/EMotionFX/Source/BlendSpaceNode.h | 6 +- .../Source/BlendSpaceParamEvaluator.cpp | 40 +- .../Code/EMotionFX/Source/BlendTree.cpp | 26 +- .../Code/EMotionFX/Source/BlendTree.h | 4 +- .../Source/BlendTreeAccumTransformNode.cpp | 54 +- .../Source/BlendTreeAccumTransformNode.h | 6 +- .../Source/BlendTreeBlend2AdditiveNode.cpp | 32 +- .../Source/BlendTreeBlend2LegacyNode.cpp | 36 +- .../EMotionFX/Source/BlendTreeBlend2Node.cpp | 32 +- .../Source/BlendTreeBlend2NodeBase.cpp | 20 +- .../Source/BlendTreeBlend2NodeBase.h | 4 +- .../EMotionFX/Source/BlendTreeBlendNNode.cpp | 72 +- .../EMotionFX/Source/BlendTreeBlendNNode.h | 4 +- .../Source/BlendTreeBoolLogicNode.cpp | 12 +- .../EMotionFX/Source/BlendTreeConnection.cpp | 16 +- .../EMotionFX/Source/BlendTreeConnection.h | 18 +- .../Source/BlendTreeDirectionToWeightNode.cpp | 4 +- .../EMotionFX/Source/BlendTreeFinalNode.cpp | 8 +- .../Source/BlendTreeFloatConditionNode.cpp | 10 +- .../Source/BlendTreeFloatMath1Node.cpp | 8 +- .../Source/BlendTreeFloatMath2Node.cpp | 12 +- .../Source/BlendTreeFloatSwitchNode.cpp | 4 +- .../EMotionFX/Source/BlendTreeFootIKNode.cpp | 102 +-- .../Source/BlendTreeGetTransformNode.cpp | 12 +- .../EMotionFX/Source/BlendTreeLookAtNode.cpp | 62 +- .../EMotionFX/Source/BlendTreeLookAtNode.h | 8 +- .../Source/BlendTreeMaskLegacyNode.cpp | 40 +- .../Source/BlendTreeMaskLegacyNode.h | 6 +- .../EMotionFX/Source/BlendTreeMaskNode.cpp | 14 +- .../Source/BlendTreeMirrorPoseNode.cpp | 18 +- .../Source/BlendTreeMorphTargetNode.cpp | 12 +- .../Source/BlendTreeMotionFrameNode.cpp | 34 +- .../Source/BlendTreeMotionFrameNode.h | 8 +- .../Source/BlendTreeParameterNode.cpp | 36 +- .../Source/BlendTreePoseSubtractNode.cpp | 20 +- .../Source/BlendTreePoseSwitchNode.cpp | 34 +- .../Source/BlendTreePoseSwitchNode.h | 2 +- .../EMotionFX/Source/BlendTreeRagdollNode.cpp | 38 +- .../BlendTreeRagdollStrengthModifierNode.cpp | 8 +- .../Source/BlendTreeRangeRemapperNode.cpp | 6 +- .../EMotionFX/Source/BlendTreeRaycastNode.cpp | 2 +- .../Source/BlendTreeRotationLimitNode.cpp | 6 +- .../Source/BlendTreeRotationMath2Node.cpp | 12 +- .../Source/BlendTreeSetTransformNode.cpp | 16 +- .../Source/BlendTreeSimulatedObjectNode.cpp | 24 +- .../Source/BlendTreeSmoothingNode.cpp | 22 +- .../EMotionFX/Source/BlendTreeSmoothingNode.h | 4 +- .../Source/BlendTreeTransformNode.cpp | 28 +- .../EMotionFX/Source/BlendTreeTransformNode.h | 2 +- .../Source/BlendTreeTwoLinkIKNode.cpp | 120 +-- .../EMotionFX/Source/BlendTreeTwoLinkIKNode.h | 12 +- .../Source/BlendTreeVector3Math1Node.cpp | 4 +- .../Source/BlendTreeVector3Math2Node.cpp | 6 +- .../Source/BlendTreeVector4DecomposeNode.cpp | 2 +- .../EMotionFX/Source/CompressedKeyFrames.h | 40 +- .../EMotionFX/Source/ConstraintTransform.h | 10 +- .../ConstraintTransformRotationAngles.cpp | 60 +- .../ConstraintTransformRotationAngles.h | 10 +- .../Code/EMotionFX/Source/DebugDraw.cpp | 4 +- .../EMotionFX/Source/DualQuatSkinDeformer.cpp | 38 +- .../EMotionFX/Source/DualQuatSkinDeformer.h | 10 +- .../EMotionFX/Source/EMotionFXManager.cpp | 173 ++-- .../Code/EMotionFX/Source/EMotionFXManager.h | 79 +- .../Code/EMotionFX/Source/EventHandler.h | 14 +- .../Code/EMotionFX/Source/EventInfo.h | 28 +- .../Code/EMotionFX/Source/EventManager.cpp | 14 +- .../Code/EMotionFX/Source/EventManager.h | 54 +- .../Source/Importer/ActorFileFormat.h | 134 +-- .../Source/Importer/ChunkProcessors.cpp | 853 +++++++++--------- .../Source/Importer/ChunkProcessors.h | 26 +- .../EMotionFX/Source/Importer/Importer.cpp | 150 +-- .../Code/EMotionFX/Source/Importer/Importer.h | 66 +- .../Source/Importer/MotionFileFormat.h | 120 +-- .../Source/Importer/NodeMapFileFormat.h | 12 +- .../Source/Importer/SharedFileFormatStructs.h | 64 +- .../Code/EMotionFX/Source/KeyFrame.h | 4 +- .../Code/EMotionFX/Source/KeyFrame.inl | 22 +- .../EMotionFX/Source/KeyTrackLinearDynamic.h | 2 +- .../Source/KeyTrackLinearDynamic.inl | 137 ++- .../Code/EMotionFX/Source/LayerPass.h | 4 +- .../Code/EMotionFX/Source/Material.cpp | 6 +- .../Code/EMotionFX/Source/Material.h | 2 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp | 329 +++---- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h | 28 +- Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl | 31 +- .../Code/EMotionFX/Source/MeshDeformer.cpp | 8 +- .../Code/EMotionFX/Source/MeshDeformer.h | 4 +- .../EMotionFX/Source/MeshDeformerStack.cpp | 52 +- .../Code/EMotionFX/Source/MeshDeformerStack.h | 4 +- .../EMotionFX/Source/MorphMeshDeformer.cpp | 84 +- .../Code/EMotionFX/Source/MorphMeshDeformer.h | 14 +- .../Code/EMotionFX/Source/MorphSetup.cpp | 46 +- .../Code/EMotionFX/Source/MorphSetup.h | 6 +- .../EMotionFX/Source/MorphSetupInstance.cpp | 10 +- .../EMotionFX/Source/MorphSetupInstance.h | 32 +- .../Code/EMotionFX/Source/MorphTarget.cpp | 48 +- .../Code/EMotionFX/Source/MorphTarget.h | 10 +- .../EMotionFX/Source/MorphTargetStandard.cpp | 178 ++-- .../EMotionFX/Source/MorphTargetStandard.h | 34 +- .../Code/EMotionFX/Source/Motion.cpp | 66 +- Gems/EMotionFX/Code/EMotionFX/Source/Motion.h | 22 +- .../Source/MotionData/MotionData.cpp | 42 +- .../MotionData/NonUniformMotionData.cpp | 82 +- .../Source/MotionData/UniformMotionData.cpp | 70 +- .../EMotionFX/Source/MotionEventTrack.cpp | 24 +- .../Code/EMotionFX/Source/MotionEventTrack.h | 6 +- .../Code/EMotionFX/Source/MotionInstance.cpp | 78 +- .../Code/EMotionFX/Source/MotionInstance.h | 10 +- .../EMotionFX/Source/MotionInstancePool.cpp | 206 +++-- .../EMotionFX/Source/MotionInstancePool.h | 28 +- .../EMotionFX/Source/MotionLayerSystem.cpp | 100 +- .../Code/EMotionFX/Source/MotionLayerSystem.h | 4 +- .../Code/EMotionFX/Source/MotionManager.cpp | 122 +-- .../Code/EMotionFX/Source/MotionManager.h | 16 +- .../Code/EMotionFX/Source/MotionQueue.cpp | 34 +- .../Code/EMotionFX/Source/MotionQueue.h | 16 +- .../Code/EMotionFX/Source/MotionSystem.cpp | 91 +- .../Code/EMotionFX/Source/MotionSystem.h | 6 +- .../EMotionFX/Source/MultiThreadScheduler.cpp | 100 +- .../EMotionFX/Source/MultiThreadScheduler.h | 14 +- Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp | 152 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Node.h | 38 +- .../Code/EMotionFX/Source/NodeGroup.cpp | 46 +- .../Code/EMotionFX/Source/NodeGroup.h | 6 +- .../Code/EMotionFX/Source/NodeMap.cpp | 90 +- .../EMotionFX/Code/EMotionFX/Source/NodeMap.h | 10 +- .../Code/EMotionFX/Source/PhysicsSetup.cpp | 6 +- .../Code/EMotionFX/Source/PlayBackInfo.h | 142 +-- Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp | 519 +++++------ Gems/EMotionFX/Code/EMotionFX/Source/Pose.h | 58 +- .../Code/EMotionFX/Source/PoseDataRagdoll.cpp | 8 +- .../Code/EMotionFX/Source/RagdollInstance.cpp | 24 +- .../Code/EMotionFX/Source/Recorder.cpp | 570 ++++++------ .../Code/EMotionFX/Source/Recorder.h | 286 +++--- .../Source/RepositioningLayerPass.cpp | 10 +- .../EMotionFX/Source/RepositioningLayerPass.h | 4 +- .../Source/SingleThreadScheduler.cpp | 12 +- .../SkinningInfoVertexAttributeLayer.cpp | 30 +- .../Source/SkinningInfoVertexAttributeLayer.h | 38 +- .../EMotionFX/Source/SoftSkinDeformer.cpp | 56 +- .../Code/EMotionFX/Source/SoftSkinDeformer.h | 16 +- .../Code/EMotionFX/Source/SoftSkinManager.h | 2 - .../Code/EMotionFX/Source/SpringSolver.cpp | 36 +- .../EMotionFX/Source/StandardMaterial.cpp | 212 ++--- .../Code/EMotionFX/Source/StandardMaterial.h | 40 +- .../Code/EMotionFX/Source/SubMesh.cpp | 78 +- .../EMotionFX/Code/EMotionFX/Source/SubMesh.h | 28 +- .../Code/EMotionFX/Source/ThreadData.cpp | 8 +- .../Code/EMotionFX/Source/ThreadData.h | 14 +- .../Code/EMotionFX/Source/Transform.cpp | 290 +++--- .../Code/EMotionFX/Source/Transform.h | 6 +- .../Code/EMotionFX/Source/TransformData.cpp | 60 +- .../Code/EMotionFX/Source/TransformData.h | 30 +- .../EMotionFX/Source/VertexAttributeLayer.cpp | 14 +- .../EMotionFX/Source/VertexAttributeLayer.h | 10 +- .../VertexAttributeLayerAbstractData.cpp | 76 +- .../Source/VertexAttributeLayerAbstractData.h | 26 +- .../EMStudioSDK/Source/DockWidgetPlugin.cpp | 34 +- .../EMStudioSDK/Source/DockWidgetPlugin.h | 4 +- .../EMStudioSDK/Source/EMStudioManager.cpp | 110 +-- .../EMStudioSDK/Source/EMStudioManager.h | 60 +- .../EMStudioSDK/Source/EMStudioPlugin.h | 16 +- .../EMStudioSDK/Source/FileManager.cpp | 38 +- .../EMStudioSDK/Source/FileManager.h | 12 +- .../Source/KeyboardShortcutsWindow.cpp | 188 ++-- .../Source/KeyboardShortcutsWindow.h | 30 +- .../EMStudioSDK/Source/LayoutManager.cpp | 101 +-- .../EMStudioSDK/Source/LayoutManager.h | 32 +- .../Source/LoadActorSettingsWindow.cpp | 166 ++-- .../Source/LoadActorSettingsWindow.h | 44 +- .../EMStudioSDK/Source/MainWindow.cpp | 552 ++++++------ .../EMStudioSDK/Source/MainWindow.h | 94 +- .../Source/MainWindowEventFilter.h | 4 +- .../Source/MorphTargetSelectionWindow.cpp | 50 +- .../Source/MorphTargetSelectionWindow.h | 8 +- .../Source/MotionEventPresetManager.cpp | 60 +- .../Source/MotionEventPresetManager.h | 22 +- .../Source/MotionSetHierarchyWidget.cpp | 96 +- .../Source/MotionSetHierarchyWidget.h | 20 +- .../Source/MotionSetSelectionWindow.cpp | 34 +- .../Source/MotionSetSelectionWindow.h | 12 +- .../Source/NodeHierarchyWidget.cpp | 153 ++-- .../EMStudioSDK/Source/NodeHierarchyWidget.h | 44 +- .../Source/NodeSelectionWindow.cpp | 26 +- .../EMStudioSDK/Source/NodeSelectionWindow.h | 22 +- .../EMStudioSDK/Source/NotificationWindow.cpp | 56 +- .../EMStudioSDK/Source/NotificationWindow.h | 8 +- .../Source/NotificationWindowManager.cpp | 14 +- .../Source/NotificationWindowManager.h | 14 +- .../EMStudioSDK/Source/PluginManager.cpp | 46 +- .../EMStudioSDK/Source/PluginManager.h | 14 +- .../EMStudioSDK/Source/RecoverFilesWindow.cpp | 70 +- .../EMStudioSDK/Source/RecoverFilesWindow.h | 4 +- .../Source/RemovePluginOnCloseDockWidget.cpp | 4 +- .../Source/RemovePluginOnCloseDockWidget.h | 2 +- .../RenderPlugin/ManipulatorCallbacks.cpp | 54 +- .../Source/RenderPlugin/RenderOptions.cpp | 14 +- .../Source/RenderPlugin/RenderOptions.h | 4 +- .../Source/RenderPlugin/RenderPlugin.cpp | 393 ++++---- .../Source/RenderPlugin/RenderPlugin.h | 98 +- .../RenderPlugin/RenderUpdateCallback.cpp | 72 +- .../RenderPlugin/RenderUpdateCallback.h | 4 +- .../Source/RenderPlugin/RenderViewWidget.cpp | 104 +-- .../Source/RenderPlugin/RenderViewWidget.h | 42 +- .../Source/RenderPlugin/RenderWidget.cpp | 442 +++++---- .../Source/RenderPlugin/RenderWidget.h | 100 +- .../Source/SaveChangedFilesManager.cpp | 117 ++- .../Source/SaveChangedFilesManager.h | 32 +- .../EMStudioSDK/Source/ToolBarPlugin.cpp | 36 +- .../EMStudioSDK/Source/ToolBarPlugin.h | 4 +- .../EMStudioSDK/Source/UnitScaleWindow.cpp | 28 +- .../EMStudioSDK/Source/UnitScaleWindow.h | 10 +- .../EMStudioSDK/Source/Workspace.cpp | 24 +- .../EMStudioSDK/Source/Workspace.h | 10 +- .../Source/OpenGLRender/GLWidget.cpp | 106 +-- .../Source/OpenGLRender/GLWidget.h | 12 +- .../OpenGLRender/OpenGLRenderPlugin.cpp | 12 +- .../Source/OpenGLRender/OpenGLRenderPlugin.h | 4 +- .../ActionHistory/ActionHistoryCallback.cpp | 96 +- .../ActionHistory/ActionHistoryCallback.h | 18 +- .../ActionHistory/ActionHistoryPlugin.cpp | 46 +- .../ActionHistory/ActionHistoryPlugin.h | 4 +- .../AnimGraph/AnimGraphActionManager.cpp | 4 +- .../Source/AnimGraph/AnimGraphEditor.cpp | 12 +- .../Source/AnimGraph/AnimGraphEditor.h | 4 +- .../AnimGraph/AnimGraphHierarchyWidget.h | 8 +- .../AnimGraph/AnimGraphModelCallbacks.cpp | 18 +- .../Source/AnimGraph/AnimGraphPlugin.cpp | 323 ++++--- .../Source/AnimGraph/AnimGraphPlugin.h | 98 +- .../Source/AnimGraph/AnimGraphVisualNode.cpp | 74 +- .../Source/AnimGraph/AnimGraphVisualNode.h | 12 +- .../Source/AnimGraph/AttributesWindow.cpp | 80 +- .../Source/AnimGraph/AttributesWindow.h | 18 +- .../Source/AnimGraph/BlendGraphViewWidget.cpp | 6 +- .../Source/AnimGraph/BlendGraphViewWidget.h | 2 +- .../Source/AnimGraph/BlendGraphWidget.cpp | 98 +- .../Source/AnimGraph/BlendGraphWidget.h | 6 +- .../AnimGraph/BlendNodeSelectionWindow.cpp | 26 +- .../AnimGraph/BlendNodeSelectionWindow.h | 16 +- .../Source/AnimGraph/BlendTreeVisualNode.cpp | 153 ++-- .../Source/AnimGraph/ContextMenu.cpp | 6 +- .../Source/AnimGraph/GameController.cpp | 285 +++--- .../Source/AnimGraph/GameController.h | 76 +- .../Source/AnimGraph/GameControllerWindow.cpp | 564 ++++++------ .../Source/AnimGraph/GameControllerWindow.h | 82 +- .../Source/AnimGraph/GraphNode.cpp | 493 +++++----- .../Source/AnimGraph/GraphNode.h | 270 +++--- .../Source/AnimGraph/GraphWidgetCallback.h | 4 +- .../Source/AnimGraph/NodeConnection.cpp | 101 +-- .../Source/AnimGraph/NodeConnection.h | 86 +- .../Source/AnimGraph/NodeGraph.cpp | 292 +++--- .../Source/AnimGraph/NodeGraph.h | 146 +-- .../Source/AnimGraph/NodeGraphWidget.cpp | 579 ++++++------ .../Source/AnimGraph/NodeGraphWidget.h | 68 +- .../Source/AnimGraph/NodeGroupWindow.cpp | 231 +++-- .../Source/AnimGraph/NodeGroupWindow.h | 28 +- .../Source/AnimGraph/NodePaletteWidget.cpp | 90 +- .../Source/AnimGraph/NodePaletteWidget.h | 16 +- .../AnimGraph/ParameterCreateEditDialog.cpp | 4 +- .../AnimGraph/ParameterCreateEditDialog.h | 2 +- .../ParameterEditor/ColorParameterEditor.cpp | 2 +- .../AnimGraph/ParameterSelectionWindow.cpp | 26 +- .../AnimGraph/ParameterSelectionWindow.h | 20 +- .../Source/AnimGraph/ParameterWidget.cpp | 88 +- .../Source/AnimGraph/ParameterWidget.h | 14 +- .../Source/AnimGraph/ParameterWindow.cpp | 208 ++--- .../Source/AnimGraph/ParameterWindow.h | 34 +- .../AnimGraph/StateFilterSelectionWindow.cpp | 72 +- .../AnimGraph/StateFilterSelectionWindow.h | 20 +- .../Source/AnimGraph/StateGraphNode.cpp | 135 ++- .../Source/AnimGraph/StateGraphNode.h | 4 +- .../Attachments/AttachmentNodesWindow.cpp | 148 +-- .../Attachments/AttachmentNodesWindow.h | 16 +- .../AttachmentsHierarchyWindow.cpp | 40 +- .../Attachments/AttachmentsHierarchyWindow.h | 2 +- .../Source/Attachments/AttachmentsPlugin.cpp | 126 +-- .../Source/Attachments/AttachmentsPlugin.h | 30 +- .../Source/Attachments/AttachmentsWindow.cpp | 359 ++++---- .../Source/Attachments/AttachmentsWindow.h | 46 +- .../Source/CommandBar/CommandBarPlugin.cpp | 14 +- .../CommandBrowser/CommandBrowserPlugin.cpp | 280 ------ .../CommandBrowser/CommandBrowserPlugin.h | 59 -- .../Source/LogWindow/LogWindowCallback.cpp | 38 +- .../Source/LogWindow/LogWindowCallback.h | 10 +- .../Source/LogWindow/LogWindowPlugin.cpp | 30 +- .../Source/LogWindow/LogWindowPlugin.h | 4 +- .../MorphTargetEditWindow.cpp | 76 +- .../MorphTargetEditWindow.h | 12 +- .../MorphTargetGroupWidget.cpp | 168 ++-- .../MorphTargetGroupWidget.h | 22 +- .../MorphTargetsWindowPlugin.cpp | 70 +- .../MorphTargetsWindowPlugin.h | 14 +- .../PhonemeSelectionWindow.cpp | 214 ++--- .../PhonemeSelectionWindow.h | 48 +- .../MotionEvents/MotionEventPresetsWidget.cpp | 78 +- .../MotionEvents/MotionEventPresetsWidget.h | 6 +- .../MotionEvents/MotionEventsPlugin.cpp | 133 ++- .../Source/MotionEvents/MotionEventsPlugin.h | 34 +- .../MotionSetManagementWindow.cpp | 138 ++- .../MotionSetManagementWindow.h | 13 +- .../MotionSetsWindow/MotionSetWindow.cpp | 328 ++++--- .../Source/MotionSetsWindow/MotionSetWindow.h | 38 +- .../MotionSetsWindowPlugin.cpp | 139 ++- .../MotionSetsWindow/MotionSetsWindowPlugin.h | 27 +- .../MotionWindow/MotionExtractionWindow.cpp | 162 ++-- .../MotionWindow/MotionExtractionWindow.h | 28 +- .../Source/MotionWindow/MotionListWindow.cpp | 152 ++-- .../Source/MotionWindow/MotionListWindow.h | 14 +- .../MotionWindow/MotionRetargetingWindow.cpp | 37 +- .../MotionWindow/MotionRetargetingWindow.h | 11 +- .../MotionWindow/MotionWindowPlugin.cpp | 198 ++-- .../Source/MotionWindow/MotionWindowPlugin.h | 36 +- .../NodeGroups/NodeGroupManagementWidget.cpp | 231 +++-- .../NodeGroups/NodeGroupManagementWidget.h | 22 +- .../Source/NodeGroups/NodeGroupWidget.cpp | 174 ++-- .../Source/NodeGroups/NodeGroupWidget.h | 20 +- .../Source/NodeGroups/NodeGroupsPlugin.cpp | 114 +-- .../Source/NodeGroups/NodeGroupsPlugin.h | 22 +- .../Source/NodeWindow/NodeInfo.cpp | 10 +- .../Source/NodeWindow/NodeWindowPlugin.cpp | 54 +- .../Source/NodeWindow/NodeWindowPlugin.h | 8 +- .../SceneManager/ActorPropertiesWindow.cpp | 92 +- .../SceneManager/ActorPropertiesWindow.h | 12 +- .../Source/SceneManager/MirrorSetupWindow.cpp | 403 ++++----- .../Source/SceneManager/MirrorSetupWindow.h | 34 +- .../SceneManager/SceneManagerPlugin.cpp | 164 ++-- .../Source/SceneManager/SceneManagerPlugin.h | 38 +- .../Source/TimeView/PlaybackOptionsGroup.cpp | 14 +- .../Source/TimeView/TimeInfoWidget.cpp | 80 +- .../Source/TimeView/TimeInfoWidget.h | 28 +- .../Source/TimeView/TimeTrack.cpp | 80 +- .../Source/TimeView/TimeTrack.h | 74 +- .../Source/TimeView/TimeTrackElement.cpp | 120 +-- .../Source/TimeView/TimeTrackElement.h | 102 +-- .../Source/TimeView/TimeViewPlugin.cpp | 621 ++++++------- .../Source/TimeView/TimeViewPlugin.h | 132 +-- .../Source/TimeView/TimeViewToolBar.cpp | 100 +- .../Source/TimeView/TimeViewToolBar.h | 2 +- .../Source/TimeView/TrackDataHeaderWidget.cpp | 334 ++++--- .../Source/TimeView/TrackDataHeaderWidget.h | 36 +- .../Source/TimeView/TrackDataWidget.cpp | 842 +++++++++-------- .../Source/TimeView/TrackDataWidget.h | 88 +- .../Source/TimeView/TrackHeaderWidget.cpp | 256 +++--- .../Source/TimeView/TrackHeaderWidget.h | 40 +- .../standardplugins_files.cmake | 2 - .../Source/MainWindowEventFilter_Windows.cpp | 2 +- Gems/EMotionFX/Code/MCore/Source/AABB.h | 94 +- .../Code/MCore/Source/AlignedArray.h | 256 +++--- Gems/EMotionFX/Code/MCore/Source/Array2D.h | 42 +- Gems/EMotionFX/Code/MCore/Source/Array2D.inl | 102 +-- .../EMotionFX/Code/MCore/Source/Attribute.cpp | 2 +- Gems/EMotionFX/Code/MCore/Source/Attribute.h | 4 +- .../Code/MCore/Source/AttributeBool.cpp | 6 +- .../Code/MCore/Source/AttributeBool.h | 18 +- .../Code/MCore/Source/AttributeColor.h | 20 +- .../Code/MCore/Source/AttributeFactory.cpp | 20 +- .../Code/MCore/Source/AttributeFactory.h | 6 +- .../Code/MCore/Source/AttributeFloat.cpp | 6 +- .../Code/MCore/Source/AttributeFloat.h | 18 +- .../Code/MCore/Source/AttributeInt32.cpp | 6 +- .../Code/MCore/Source/AttributeInt32.h | 18 +- .../Code/MCore/Source/AttributePointer.h | 14 +- .../Code/MCore/Source/AttributeQuaternion.h | 20 +- .../Code/MCore/Source/AttributeString.h | 26 +- .../Code/MCore/Source/AttributeVector2.h | 20 +- .../Code/MCore/Source/AttributeVector3.h | 20 +- .../Code/MCore/Source/AttributeVector4.h | 21 +- .../Code/MCore/Source/AzCoreConversions.h | 6 +- .../Code/MCore/Source/BoundingSphere.cpp | 36 +- .../Code/MCore/Source/BoundingSphere.h | 50 +- Gems/EMotionFX/Code/MCore/Source/Color.cpp | 2 +- Gems/EMotionFX/Code/MCore/Source/Color.h | 142 +-- Gems/EMotionFX/Code/MCore/Source/Command.cpp | 30 +- Gems/EMotionFX/Code/MCore/Source/Command.h | 30 +- .../Code/MCore/Source/CommandGroup.cpp | 66 +- .../Code/MCore/Source/CommandGroup.h | 16 +- .../Code/MCore/Source/CommandLine.cpp | 54 +- .../EMotionFX/Code/MCore/Source/CommandLine.h | 4 +- .../Code/MCore/Source/CommandSyntax.cpp | 52 +- .../Code/MCore/Source/CommandSyntax.h | 12 +- .../Code/MCore/Source/CompressedFloat.h | 2 +- .../Code/MCore/Source/CompressedFloat.inl | 10 +- .../Code/MCore/Source/CompressedQuaternion.h | 2 +- .../MCore/Source/CompressedQuaternion.inl | 40 +- .../Code/MCore/Source/CompressedVector.h | 8 +- .../Code/MCore/Source/CompressedVector.inl | 14 +- Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp | 58 +- Gems/EMotionFX/Code/MCore/Source/DiskFile.h | 6 +- Gems/EMotionFX/Code/MCore/Source/Distance.cpp | 6 +- Gems/EMotionFX/Code/MCore/Source/Distance.h | 100 +- .../Code/MCore/Source/DualQuaternion.cpp | 60 +- .../Code/MCore/Source/DualQuaternion.h | 51 +- .../Code/MCore/Source/DualQuaternion.inl | 18 +- .../Code/MCore/Source/FileSystem.cpp | 8 +- Gems/EMotionFX/Code/MCore/Source/FileSystem.h | 2 +- .../Code/MCore/Source/IDGenerator.cpp | 4 +- .../EMotionFX/Code/MCore/Source/IDGenerator.h | 2 +- .../Code/MCore/Source/LogManager.cpp | 62 +- Gems/EMotionFX/Code/MCore/Source/LogManager.h | 14 +- .../Code/MCore/Source/MCoreCommandManager.cpp | 260 +++--- .../Code/MCore/Source/MCoreCommandManager.h | 30 +- .../Code/MCore/Source/MCoreSystem.cpp | 126 +-- .../EMotionFX/Code/MCore/Source/MCoreSystem.h | 56 +- Gems/EMotionFX/Code/MCore/Source/Matrix4.cpp | 44 +- Gems/EMotionFX/Code/MCore/Source/Matrix4.h | 6 +- Gems/EMotionFX/Code/MCore/Source/Matrix4.inl | 6 +- .../Code/MCore/Source/MemoryFile.cpp | 87 +- Gems/EMotionFX/Code/MCore/Source/MemoryFile.h | 24 +- .../Code/MCore/Source/MemoryObject.cpp | 16 +- .../Code/MCore/Source/MemoryObject.h | 2 +- .../Code/MCore/Source/MemoryTracker.cpp | 280 +++--- .../Code/MCore/Source/MemoryTracker.h | 54 +- .../Code/MCore/Source/MultiThreadManager.h | 92 +- Gems/EMotionFX/Code/MCore/Source/PlaneEq.h | 42 +- Gems/EMotionFX/Code/MCore/Source/PlaneEq.inl | 16 +- Gems/EMotionFX/Code/MCore/Source/Random.cpp | 128 +-- Gems/EMotionFX/Code/MCore/Source/Random.h | 32 +- Gems/EMotionFX/Code/MCore/Source/Ray.cpp | 60 +- Gems/EMotionFX/Code/MCore/Source/Ray.h | 32 +- Gems/EMotionFX/Code/MCore/Source/SmallArray.h | 129 ++- .../Code/MCore/Source/StringIdPool.cpp | 24 +- .../Code/MCore/Source/StringIdPool.h | 6 +- .../Code/MysticQt/Source/DialogStack.cpp | 236 ++--- .../Code/MysticQt/Source/DialogStack.h | 32 +- .../Code/MysticQt/Source/MysticQtManager.cpp | 22 +- .../Code/MysticQt/Source/MysticQtManager.h | 32 +- .../Code/MysticQt/Source/RecentFiles.cpp | 6 +- .../MCore/Source/DiskFile_FileOffsetType.cpp | 20 +- .../WinAPI/MCore/Source/DiskFile_WinAPI.cpp | 20 +- .../Source/Editor/ColliderContainerWidget.cpp | 6 +- .../Code/Source/Editor/ObjectEditor.cpp | 4 +- .../Code/Source/Editor/ObjectEditor.h | 2 +- .../Cloth/ClothJointInspectorPlugin.cpp | 4 +- .../HitDetectionJointInspectorPlugin.cpp | 4 +- .../Ragdoll/RagdollNodeInspectorPlugin.cpp | 16 +- .../SimulatedObjectSelectionWindow.cpp | 6 +- .../SimulatedObjectSelectionWindow.h | 2 +- .../SimulatedObject/SimulatedObjectWidget.cpp | 12 +- .../SkeletonOutlinerPlugin.cpp | 4 +- .../PropertyWidgets/ActorGoalNodeHandler.cpp | 2 +- .../PropertyWidgets/AnimGraphNodeHandler.cpp | 2 +- .../BlendNParamWeightsHandler.cpp | 6 +- .../PropertyWidgets/LODSceneGraphWidget.h | 2 +- .../Source/Integration/Assets/ActorAsset.cpp | 2 +- .../Integration/Components/ActorComponent.cpp | 28 +- .../Components/SimpleMotionComponent.cpp | 24 +- .../Integration/System/PipelineComponent.cpp | 12 +- .../Integration/System/PipelineComponent.h | 2 +- .../Integration/System/SystemComponent.cpp | 26 +- .../Code/Tests/AnimGraphDeferredInitTests.cpp | 2 +- .../Code/Tests/AnimGraphMotionNodeTests.cpp | 184 ++-- .../Tests/AnimGraphNodeEventFilterTests.cpp | 24 +- ...AnimGraphStateMachineInterruptionTests.cpp | 148 +-- .../Tests/AnimGraphStateMachineSyncTests.cpp | 16 +- .../Code/Tests/AnimGraphSyncTrackTests.cpp | 86 +- .../AnimGraphTransitionConditionTests.cpp | 48 +- .../Tests/BlendTreeFloatMath1NodeTests.cpp | 2 +- .../Code/Tests/BlendTreeFootIKNodeTests.cpp | 6 +- .../Code/Tests/BlendTreeMaskNodeTests.cpp | 4 +- .../Tests/BlendTreeMirrorPoseNodeTests.cpp | 36 +- .../Tests/BlendTreeMotionFrameNodeTests.cpp | 6 +- .../Tests/BlendTreeRotationLimitNodeTests.cpp | 8 +- .../Tests/BlendTreeRotationMath2NodeTests.cpp | 16 +- .../BlendTreeSimulatedObjectNodeTests.cpp | 6 +- .../Tests/BlendTreeTransformNodeTests.cpp | 4 +- .../Tests/BlendTreeTwoLinkIKNodeTests.cpp | 138 +-- .../Code/Tests/BoolLogicNodeTests.cpp | 6 +- ...DeletionAndRestoreBlendTreeConnections.cpp | 4 +- .../Code/Tests/EmotionFXMathLibTests.cpp | 10 +- .../Tests/Integration/PoseComparisonFixture.h | 10 +- .../Tests/Integration/PoseComparisonTests.cpp | 42 +- Gems/EMotionFX/Code/Tests/Matchers.h | 42 +- .../Code/Tests/MorphTargetRuntimeTests.cpp | 2 +- .../Code/Tests/MotionEventTrackTests.cpp | 40 +- .../Code/Tests/MotionExtractionBusTests.cpp | 2 +- .../Code/Tests/MotionExtractionTests.cpp | 58 +- .../Code/Tests/MotionLayerSystemTests.cpp | 28 +- .../Code/Tests/MultiThreadSchedulerTests.cpp | 8 +- .../Code/Tests/NonUniformMotionDataTests.cpp | 36 +- Gems/EMotionFX/Code/Tests/PoseTests.cpp | 46 +- Gems/EMotionFX/Code/Tests/Printers.cpp | 6 +- .../Code/Tests/RandomMotionSelectionTests.cpp | 4 +- .../Code/Tests/SimulatedObjectSetupTests.cpp | 8 +- .../Code/Tests/SyncingSystemTests.cpp | 32 +- .../Code/Tests/TestAssetCode/SimpleActors.cpp | 6 +- .../Code/Tests/TransformUnitTests.cpp | 142 +-- .../Code/Tests/UI/CanMorphManyShapes.cpp | 8 +- .../Code/Tests/UI/ModalPopupHandler.cpp | 4 +- .../Code/Tests/UI/ModalPopupHandler.h | 2 +- .../Code/Tests/UniformMotionDataTests.cpp | 36 +- .../ClothComponentMesh/ActorClothSkinning.cpp | 2 +- 649 files changed, 20255 insertions(+), 21983 deletions(-) delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MeshExport.cpp delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkinExport.cpp delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.cpp delete mode 100644 Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.h diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp index ece2c2aca7..8d247eaf45 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp @@ -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]); } } } diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp index c8a09ddaf8..d5a48b900d 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp @@ -151,10 +151,10 @@ namespace AZ 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); } @@ -615,7 +615,7 @@ namespace AZ { // 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp index 85d9c699e1..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); @@ -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$") @@ -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,7 +119,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("attachmentNodes")) { // Store old attachment nodes for undo. - mOldAttachmentNodes = ""; + m_oldAttachmentNodes = ""; const size_t numNodes = actor->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { @@ -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 += ";"; } } @@ -198,7 +198,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("nodesExcludedFromBounds")) { // Store old nodes for undo. - mOldExcludedFromBoundsNodes = ""; + m_oldExcludedFromBoundsNodes = ""; const size_t numNodes = actor->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { @@ -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 += ";"; } } @@ -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); @@ -308,8 +308,8 @@ namespace CommandSystem 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()); } } @@ -318,7 +318,7 @@ namespace CommandSystem } } - mOldDirtyFlag = actor->GetDirtyFlag(); + m_oldDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); return true; } @@ -338,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)) { @@ -372,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)) { @@ -382,7 +382,7 @@ namespace CommandSystem } // Set the dirty flag back to the old value. - actor->SetDirtyFlag(mOldDirtyFlag); + actor->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -479,18 +479,18 @@ namespace CommandSystem EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); // Store the old nodes for the undo. - mOldNodeList = ""; + 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(); } } @@ -517,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. @@ -542,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; } @@ -686,7 +686,7 @@ namespace CommandSystem CommandRemoveActor::CommandRemoveActor(MCore::Command* orgCommand) : MCore::Command("RemoveActor", orgCommand) { - mPreviouslyUsedID = MCORE_INVALIDINDEX32; + m_previouslyUsedId = MCORE_INVALIDINDEX32; } @@ -725,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())); @@ -747,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; @@ -761,7 +761,7 @@ namespace CommandSystem } // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return true; } @@ -973,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; } @@ -1020,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 { @@ -1083,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 94c6e0ff42..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) - size_t mOldMotionExtractionNodeIndex; - size_t mOldRetargetRootNodeIndex; - size_t mOldTrajectoryNodeIndex; - AZStd::string mOldAttachmentNodes; - AZStd::string mOldExcludedFromBoundsNodes; - AZStd::string mOldName; - AZStd::vector 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,21 +50,21 @@ 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 ////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp index 45603b298e..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)); @@ -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 %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 diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h index 69509822fe..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; - size_t 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; - size_t 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 1458107bcf..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; } @@ -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; } @@ -334,7 +334,7 @@ namespace CommandSystem if (someAnimGraphRemoved) { - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); } @@ -388,7 +388,7 @@ namespace CommandSystem } // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); return true; @@ -414,7 +414,7 @@ namespace CommandSystem } // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -440,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() @@ -509,7 +509,7 @@ 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(); @@ -533,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) @@ -566,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) @@ -585,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; @@ -598,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); } @@ -616,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; } } @@ -683,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(); @@ -702,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(); @@ -713,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); 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 7707d8fa8b..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); + 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 == InvalidIndex) + 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 >= sourceNode->GetOutputPorts().size()) + 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 >= targetNode->GetInputPorts().size()) + 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) @@ -348,9 +348,9 @@ namespace CommandSystem 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 @@ -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 = InvalidIndex; - mTargetPort = InvalidIndex; - 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,34 +591,34 @@ 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 %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)) @@ -631,18 +631,18 @@ namespace CommandSystem return false; } - mTargetNodeId.SetInvalid(); - mSourceNodeId.SetInvalid(); + m_targetNodeId.SetInvalid(); + m_sourceNodeId.SetInvalid(); m_connectionId.SetInvalid(); - mSourcePort = InvalidIndex; - mTargetPort = InvalidIndex; - 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; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h index d0ef5549e0..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; - size_t mSourcePort; - size_t 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; } - size_t GetSourcePort() const { return mSourcePort; } - size_t 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; - size_t mSourcePort; - size_t 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; } - size_t GetSourcePort() const { return mSourcePort; } - size_t 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 6142fe151e..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 @@ -397,21 +397,21 @@ 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) @@ -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,7 +737,7 @@ 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 //-------------------------- @@ -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,13 +836,13 @@ 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); } @@ -857,15 +857,15 @@ 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) @@ -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(); 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 a11af1399d..0f04bb0e79 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp @@ -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; } @@ -413,16 +413,16 @@ namespace CommandSystem // 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; } 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 b0c03e4df2..571b6c5e97 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp @@ -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(); @@ -320,7 +320,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; @@ -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)) @@ -525,7 +525,7 @@ namespace CommandSystem { EMotionFX::AnimGraphInstance* animGraphInstance = animGraph->GetAnimGraphInstance(i); // reinit the modified parameters - if (mOldType != azrtti_typeid()) + if (m_oldType != azrtti_typeid()) { animGraphInstance->ReInitParameterValue(valueParameterIndex.GetValue()); } @@ -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(); @@ -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; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h index f93a93d0f9..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,18 +59,18 @@ namespace CommandSystem struct COMMANDSYSTEM_API ParameterConnectionItem { - 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); } + 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); } - 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); 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 aade6e8358..9a0913a5db 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp @@ -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(); 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 677b4ec5ff..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); } } @@ -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"); \ @@ -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,9 +614,6 @@ 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 size_t numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances(); @@ -716,9 +713,6 @@ 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 size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); for (size_t i = 0; i < numActorInstances; ++i) @@ -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; } @@ -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; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h index 2e68d7b2cc..2a87b11627 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h @@ -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; - size_t 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 b1d896ccd4..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 = InvalidIndex; + 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, m_eventDatas.value_or(EMotionFX::EventDataSet())); + m_motionEventNr = eventTrack->AddEvent(m_startTime, m_endTime, m_eventDatas.value_or(EMotionFX::EventDataSet())); - if (mMotionEventNr == InvalidIndex) + 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); } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h index 629e1e72c5..54dce0fca6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h @@ -60,8 +60,8 @@ namespace CommandSystem }; 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 diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp index 051a0e0797..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,14 +145,14 @@ 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. @@ -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); } @@ -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; @@ -719,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")) { @@ -782,7 +782,7 @@ 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()); } } @@ -833,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); @@ -869,7 +869,7 @@ namespace CommandSystem CommandLoadMotionSet::CommandLoadMotionSet(MCore::Command* orgCommand) : MCore::Command("LoadMotionSet", orgCommand) { - mOldMotionSetID = MCORE_INVALIDINDEX32; + m_oldMotionSetId = MCORE_INVALIDINDEX32; } @@ -910,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); @@ -924,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. @@ -938,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; } @@ -952,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; } 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 72c7338512..bcc9769c44 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp @@ -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 0c1fad6588..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); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp index 5910ae84f7..e115c24221 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp @@ -27,39 +27,39 @@ namespace CommandSystem size_t SelectionList::GetNumTotalItems() const { - return 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,7 +106,7 @@ namespace CommandSystem { if (!CheckIfHasAnimGraph(animGraph)) { - mSelectedAnimGraphs.emplace_back(animGraph); + m_selectedAnimGraphs.emplace_back(animGraph); } } @@ -209,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 { @@ -263,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 { @@ -294,7 +294,7 @@ namespace CommandSystem return nullptr; } - return mSelectedActors[0]; + return m_selectedActors[0]; } @@ -313,7 +313,7 @@ namespace CommandSystem return nullptr; } - EMotionFX::ActorInstance* actorInstance = mSelectedActorInstances[0]; + EMotionFX::ActorInstance* actorInstance = m_selectedActorInstances[0]; if (!actorInstance) { return nullptr; @@ -324,7 +324,7 @@ namespace CommandSystem return nullptr; } - return mSelectedActorInstances[0]; + return m_selectedActorInstances[0]; } @@ -341,7 +341,7 @@ namespace CommandSystem return nullptr; } - EMotionFX::Motion* motion = mSelectedMotions[0]; + EMotionFX::Motion* motion = m_selectedMotions[0]; if (!motion) { return nullptr; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h index 6dd1d2d4e2..ce53a1378f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h @@ -45,36 +45,36 @@ namespace CommandSystem * Get the number of selected nodes. * @return The number of selected nodes. */ - MCORE_INLINE size_t GetNumSelectedNodes() const { return mSelectedNodes.size(); } + MCORE_INLINE size_t GetNumSelectedNodes() const { return m_selectedNodes.size(); } /** * Get the number of selected actors */ - MCORE_INLINE size_t GetNumSelectedActors() const { return 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 size_t GetNumSelectedActorInstances() const { return 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 size_t GetNumSelectedMotionInstances() const { return 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 size_t GetNumSelectedMotions() const { return 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 size_t GetNumSelectedAnimGraphs() const { return mSelectedAnimGraphs.size(); } + MCORE_INLINE size_t GetNumSelectedAnimGraphs() const { return m_selectedAnimGraphs.size(); } /** * Get the total number of selected 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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(size_t 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/Exporters/ExporterLib/Exporter/EndianConversion.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp index 153ec6e701..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; } @@ -114,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/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 bafc899d4e..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)); @@ -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 = aznumeric_caster(numLODLevels); - infoChunk.mMotionExtractionNodeIndex = aznumeric_caster(motionExtractionNodeIndex); - infoChunk.mRetargetRootNodeIndex = aznumeric_caster(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 8bd005af6c..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, AZStd::vector& materials, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) - { - // get the number of materials - const uint32 numMaterials = materials.size(); - - // 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 - AZStd::vector 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.emplace_back(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 723669d3f1..5205dcbc97 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp @@ -32,11 +32,11 @@ namespace ExporterLib // copy over the information to the chunk EMotionFX::FileFormat::Actor_MorphTarget morphTargetChunk; - morphTargetChunk.mLOD = aznumeric_caster(lodLevel); - morphTargetChunk.mNumTransformations = aznumeric_caster(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)); @@ -63,34 +63,34 @@ namespace ExporterLib 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 = aznumeric_caster(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)); @@ -175,9 +175,9 @@ namespace ExporterLib // fill in the chunk header EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS; - chunkHeader.mSizeInBytes = aznumeric_caster(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); @@ -185,16 +185,16 @@ namespace ExporterLib // fill in the chunk header EMotionFX::FileFormat::Actor_MorphTargets morphTargetsChunk; - morphTargetsChunk.mNumMorphTargets = aznumeric_caster(numSavedMorphTargets); - morphTargetsChunk.mLOD = aznumeric_caster(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 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 e7f0fa011e..91727b2113 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp @@ -29,11 +29,11 @@ namespace ExporterLib 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 @@ -42,12 +42,12 @@ namespace ExporterLib 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.mNumChilds = aznumeric_caster(numChilds); - nodeChunk.mParentIndex = aznumeric_caster(parentIndex); + nodeChunk.m_numChilds = aznumeric_caster(numChilds); + nodeChunk.m_parentIndex = aznumeric_caster(parentIndex); // calculate and copy over the skeletal LODs uint32 skeletalLODs = 0; @@ -58,26 +58,26 @@ namespace ExporterLib 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; } // log the node chunk information @@ -90,15 +90,15 @@ 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 @@ -111,12 +111,12 @@ 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); + 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_Node2)); @@ -136,14 +136,14 @@ namespace ExporterLib // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODES; - chunkHeader.mVersion = 2; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_NODES; + chunkHeader.m_version = 2; // get the nodes chunk size - chunkHeader.mSizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_Nodes2) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node2)); + 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 @@ -152,12 +152,12 @@ namespace ExporterLib // nodes chunk EMotionFX::FileFormat::Actor_Nodes2 nodesChunk; - nodesChunk.mNumNodes = aznumeric_caster(numNodes); - nodesChunk.mNumRootNodes = aznumeric_caster(actor->GetSkeleton()->GetNumRootNodes()); + 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); + ConvertUnsignedInt(&nodesChunk.m_numNodes, targetEndianType); + ConvertUnsignedInt(&nodesChunk.m_numRootNodes, targetEndianType); file->Write(&nodesChunk, sizeof(EMotionFX::FileFormat::Actor_Nodes2)); @@ -182,12 +182,12 @@ namespace ExporterLib 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 (size_t i = 0; i < numNodes; ++i) { @@ -197,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)); @@ -240,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); + chunkHeader.m_sizeInBytes = sizeof(uint16); for (const EMotionFX::NodeGroup* nodeGroup : nodeGroups) { - chunkHeader.mSizeInBytes += sizeof(EMotionFX::FileFormat::Actor_NodeGroup); - chunkHeader.mSizeInBytes += GetStringChunkSize(nodeGroup->GetNameString()); - chunkHeader.mSizeInBytes += sizeof(uint16) * nodeGroup->GetNumNodes(); + chunkHeader.m_sizeInBytes += sizeof(EMotionFX::FileFormat::Actor_NodeGroup); + chunkHeader.m_sizeInBytes += GetStringChunkSize(nodeGroup->GetNameString()); + chunkHeader.m_sizeInBytes += sizeof(uint16) * nodeGroup->GetNumNodes(); } // endian conversion @@ -309,9 +309,9 @@ namespace ExporterLib // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODEMOTIONSOURCES; - chunkHeader.mSizeInBytes = aznumeric_caster(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); @@ -320,10 +320,10 @@ namespace ExporterLib // the node motion sources chunk data EMotionFX::FileFormat::Actor_NodeMotionSources2 nodeMotionSourcesChunk; - nodeMotionSourcesChunk.mNumNodes = aznumeric_caster(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)); @@ -336,7 +336,7 @@ namespace ExporterLib for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos) { // get the motion node source - uint16 nodeMotionSource = nodeMirrorInfo.mSourceNode; + uint16 nodeMotionSource = nodeMirrorInfo.m_sourceNode; // convert endian and save to the file ConvertUnsignedShort(&nodeMotionSource, targetEndianType); @@ -346,14 +346,14 @@ namespace ExporterLib // write all axes for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos) { - uint8 axis = static_cast(nodeMirrorInfo.mAxis); + uint8 axis = static_cast(nodeMirrorInfo.m_axis); file->Write(&axis, sizeof(uint8)); } // write all flags for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos) { - uint8 flags = static_cast(nodeMirrorInfo.mFlags); + uint8 flags = static_cast(nodeMirrorInfo.m_flags); file->Write(&flags, sizeof(uint8)); } } @@ -398,9 +398,9 @@ namespace ExporterLib // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_ATTACHMENTNODES; - chunkHeader.mSizeInBytes = aznumeric_caster(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); @@ -409,10 +409,10 @@ namespace ExporterLib // the attachment nodes chunk data EMotionFX::FileFormat::Actor_AttachmentNodes attachmentNodesChunk; - attachmentNodesChunk.mNumNodes = aznumeric_caster(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 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/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 6a95621b0d..46b81a9d25 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h @@ -148,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. @@ -261,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 34dba922ca..183d56a07f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -22,51 +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); + 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(); } @@ -74,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; } @@ -89,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; } @@ -104,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.empty()) + if (m_triangleVertices.empty()) { return; } // render the triangles and clear the array - RenderTriangles(mTriangleVertices); - mTriangleVertices.clear(); + RenderTriangles(m_triangleVertices); + m_triangleVertices.clear(); } @@ -302,12 +302,12 @@ namespace MCommon // constructor RenderUtil::AABBRenderSettings::AABBRenderSettings() { - mNodeBasedAABB = true; - mMeshBasedAABB = true; - mStaticBasedAABB = true; - mStaticBasedColor = MCore::RGBAColor(0.0f, 0.7f, 0.7f); - mNodeBasedColor = MCore::RGBAColor(1.0f, 0.0f, 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); } @@ -317,7 +317,7 @@ namespace MCommon const size_t lodLevel = actorInstance->GetLODLevel(); // handle the node based AABB - if (renderSettings.mNodeBasedAABB) + if (renderSettings.m_nodeBasedAabb) { // calculate the node based AABB AZ::Aabb box; @@ -326,12 +326,12 @@ namespace MCommon // render the aabb 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 AZ::Aabb box; @@ -340,11 +340,11 @@ namespace MCommon // render the aabb if (box.IsValid()) { - RenderAabb(box, renderSettings.mMeshBasedColor); + RenderAabb(box, renderSettings.m_meshBasedColor); } } - if (renderSettings.mStaticBasedAABB) + if (renderSettings.m_staticBasedAabb) { // calculate the static based AABB AZ::Aabb box; @@ -353,7 +353,7 @@ namespace MCommon // render the aabb if (box.IsValid()) { - RenderAabb(box, renderSettings.mStaticBasedColor); + RenderAabb(box, renderSettings.m_staticBasedColor); } } @@ -382,14 +382,14 @@ namespace MCommon 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 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); } @@ -434,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) { @@ -496,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(); @@ -524,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); } @@ -578,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); } } @@ -601,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]); } } @@ -636,11 +636,11 @@ namespace MCommon const size_t nodeIndex = node->GetNodeIndex(); const size_t parentIndex = node->GetParentIndex(); - const AZ::Vector3 nodeWorldPos = pose->GetWorldSpaceTransform(nodeIndex).mPosition; + const AZ::Vector3 nodeWorldPos = pose->GetWorldSpaceTransform(nodeIndex).m_position; 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); @@ -686,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); @@ -740,24 +740,24 @@ namespace MCommon 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); } } @@ -783,8 +783,8 @@ namespace MCommon // 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() @@ -792,8 +792,8 @@ namespace MCommon 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); } } @@ -821,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; @@ -837,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(); } } @@ -863,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); } } @@ -897,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; @@ -913,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 @@ -995,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 @@ -1016,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; } @@ -1139,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(); @@ -1219,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 @@ -1234,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; @@ -1273,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; @@ -1350,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); } @@ -1393,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); @@ -1401,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); } @@ -1421,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); @@ -1430,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); } @@ -1450,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); @@ -1700,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) @@ -1709,7 +1709,7 @@ namespace MCommon } // fast access to the trajectory trace particles - const AZStd::vector& traceParticles = trajectoryPath->mTraceParticles; + const AZStd::vector& traceParticles = trajectoryPath->m_traceParticles; const size_t numTraceParticles = traceParticles.size(); if (traceParticles.empty()) { @@ -1728,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(); @@ -1787,17 +1787,17 @@ namespace MCommon 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); @@ -1832,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); @@ -1856,7 +1856,7 @@ namespace MCommon } // remove all particles while keeping the data in memory - trajectoryPath->mTraceParticles.clear(); + trajectoryPath->m_traceParticles.clear(); } @@ -1895,7 +1895,7 @@ namespace MCommon { const EMotionFX::Node* joint = skeleton->GetNode(actorInstance->GetEnabledNode(i)); const size_t jointIndex = joint->GetNodeIndex(); - const AZ::Vector3 worldPos = pose->GetWorldSpaceTransform(jointIndex).mPosition; + 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() || @@ -1961,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; @@ -1997,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; @@ -2341,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); @@ -2427,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); } @@ -2445,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; } @@ -2458,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); } } } @@ -2487,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; @@ -2511,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 6e870c870e..c21c18fd07 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h @@ -33,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; }; @@ -149,12 +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 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 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. */ }; /** @@ -239,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. @@ -255,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. @@ -265,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. @@ -302,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. @@ -336,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. */ }; /** @@ -372,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. */ }; /** @@ -384,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(); } @@ -416,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. */ }; /** @@ -433,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(); } @@ -489,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. */ }; /** @@ -500,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) {} }; /** @@ -530,51 +530,33 @@ 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.emplace_back(TriangleVertex(posA, normalA, color)); - mTriangleVertices.emplace_back(TriangleVertex(posB, normalB, color)); - mTriangleVertices.emplace_back(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.size() + 2 >= mNumMaxTriangleVertices) + if (m_triangleVertices.size() + 2 >= s_numMaxTriangleVertices) { RenderTriangles(); } @@ -604,20 +586,20 @@ namespace MCommon struct TrajectoryPathParticle { - EMotionFX::Transform mWorldTM; + EMotionFX::Transform m_worldTm; }; struct TrajectoryTracePath { - AZStd::vector 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; } }; @@ -637,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. @@ -750,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 @@ -780,39 +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 - AZStd::vector 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 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 5443bad219..4a664b1526 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h @@ -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 6d2f167893..affee9622c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.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 7bc0bacfe0..4b916f43b7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.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 3e2a25fe80..297bf01638 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.cpp @@ -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 f7f21629a3..15be9676c1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp @@ -23,12 +23,12 @@ namespace RenderGL // constructor GLActor::GLActor() { - mEnableGPUSkinning = true; - mActor = nullptr; - mEnableGPUSkinning = true; + m_enableGpuSkinning = true; + m_actor = nullptr; + m_enableGpuSkinning = true; - 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); } @@ -57,14 +57,14 @@ namespace RenderGL void GLActor::Cleanup() { // get rid of all index and vertex buffers - for (AZStd::vector& vertexBuffers : mVertexBuffers) + for (AZStd::vector& vertexBuffers : m_vertexBuffers) { for (VertexBuffer* vertexBuffer : vertexBuffers) { delete vertexBuffer; } } - for (AZStd::vector& indexBuffers : mIndexBuffers) + for (AZStd::vector& indexBuffers : m_indexBuffers) { for (IndexBuffer* indexBuffer : indexBuffers) { @@ -73,11 +73,11 @@ namespace RenderGL } // delete all materials - for (AZStd::vector& materialsPerLod : mMaterials) + for (AZStd::vector& materialsPerLod : m_materials) { for (MaterialPrimitives* materialPrimitives : materialsPerLod) { - delete materialPrimitives->mMaterial; + delete materialPrimitives->m_material; delete materialPrimitives; } } @@ -88,7 +88,7 @@ namespace RenderGL 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); } @@ -102,35 +102,35 @@ 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 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 (AZStd::vector& vertexBuffers : mVertexBuffers) + for (AZStd::vector& vertexBuffers : m_vertexBuffers) { vertexBuffers.resize(numGeometryLODLevels); AZStd::fill(begin(vertexBuffers), end(vertexBuffers), nullptr); } - for (AZStd::vector& indexBuffers : mIndexBuffers) + for (AZStd::vector& indexBuffers : m_indexBuffers) { indexBuffers.resize(numGeometryLODLevels); AZStd::fill(begin(indexBuffers), end(indexBuffers), nullptr); } - for (MCore::Array2D& primitives : mPrimitives) + 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(); @@ -174,27 +174,27 @@ namespace RenderGL // 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].emplace_back(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(); } @@ -202,7 +202,7 @@ 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()); } } @@ -210,11 +210,11 @@ namespace RenderGL 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) @@ -228,11 +228,11 @@ namespace RenderGL 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) @@ -246,11 +246,11 @@ namespace RenderGL 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) @@ -344,7 +344,7 @@ 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; } } @@ -354,12 +354,12 @@ namespace RenderGL void GLActor::InitMaterials(size_t lodLevel) { // get the number of materials and iterate through them - const size_t numMaterials = mActor->GetNumMaterials(lodLevel); + 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].emplace_back( new MaterialPrimitives(material) ); + m_materials[lodLevel].emplace_back( new MaterialPrimitives(material) ); } } @@ -367,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); @@ -398,36 +398,36 @@ namespace RenderGL void GLActor::RenderMeshes(EMotionFX::ActorInstance* actorInstance, EMotionFX::Mesh::EMeshType meshType, uint32 renderFlags) { const size_t lodLevel = actorInstance->GetLODLevel(); - const size_t numMaterials = mMaterials[lodLevel].size(); + 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 (const MaterialPrimitives* materialPrims : mMaterials[lodLevel]) + for (const MaterialPrimitives* materialPrims : m_materials[lodLevel]) { - if (materialPrims->mPrimitives[meshType].empty()) + if (materialPrims->m_primitives[meshType].empty()) { continue; } - Material* material = materialPrims->mMaterial; + Material* material = materialPrims->m_material; if (material == nullptr) { continue; @@ -443,7 +443,7 @@ namespace RenderGL material->Activate(activationFlags); // render all primitives - for (const Primitive& primitive : materialPrims->mPrimitives[meshType]) + for (const Primitive& primitive : materialPrims->m_primitives[meshType]) { material->Render(actorInstance, &primitive); } @@ -458,19 +458,19 @@ namespace RenderGL { // get the number of dynamic nodes const size_t lodLevel = actorInstance->GetLODLevel(); - const size_t numNodes = mDynamicNodes.GetNumElements(lodLevel); + 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; @@ -483,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, 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) @@ -503,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++; } } @@ -514,17 +514,17 @@ 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(); } @@ -537,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; @@ -567,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 size_t numNodes = mActor->GetNumNodes(); + 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; @@ -662,15 +662,15 @@ 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(); } } @@ -678,22 +678,22 @@ namespace RenderGL // fill the static vertex buffer 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 size_t 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; @@ -709,7 +709,7 @@ namespace RenderGL 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; @@ -739,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++; } } @@ -751,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(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 size_t 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; @@ -799,7 +799,7 @@ namespace RenderGL 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; @@ -845,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); @@ -857,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(); + skinnedVertices[globalVert].m_weights[i] = influence->GetWeight(); const size_t boneIndex = subMesh->FindBoneIndex(influence->GetNodeNr()); - skinnedVertices[globalVert].mBoneIndices[i] = static_cast(boneIndex); + 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++; @@ -876,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 d53a7b0f72..734b57e96b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp @@ -26,61 +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; + m_currentLineVb = 0; // initialize the vertex buffers and the shader used for line rendering - for (VertexBuffer*& lineVertexBuffer : mLineVertexBuffers) + for (VertexBuffer*& lineVertexBuffer : m_lineVertexBuffers) { lineVertexBuffer = new VertexBuffer(); - if (lineVertexBuffer->Init(sizeof(LineVertex), mNumMaxLineVertices, USAGE_DYNAMIC) == false) + 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(); @@ -88,21 +88,21 @@ 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 } @@ -121,59 +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 (VertexBuffer*& lineVertexBuffer : mLineVertexBuffers) + for (VertexBuffer*& lineVertexBuffer : m_lineVertexBuffers) { 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 - for (TextEntry* textEntry : mTextEntries) + for (TextEntry* textEntry : m_textEntries) { 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(); } @@ -183,7 +183,7 @@ namespace RenderGL // render textures void GLRenderUtil::RenderTextures() { - if (mNumTextures == 0) + if (m_numTextures == 0) { return; } @@ -216,41 +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(); - 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(); @@ -265,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; } } @@ -311,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(); @@ -350,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); @@ -372,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(); } @@ -441,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); @@ -450,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()); @@ -483,66 +483,66 @@ namespace RenderGL // get the number of vertices to render const uint32 numVertices = aznumeric_caster(triangleVertices.size()); - MCORE_ASSERT(numVertices <= mNumMaxTriangleVertices); + 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.emplace_back(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); } @@ -550,16 +550,16 @@ namespace RenderGL { static AZ::Debug::Timer timer; const float timeDelta = static_cast(timer.StampAndGetDeltaTimeInSeconds()); - for (uint32 i = 0; i < mTextEntries.size(); ) + 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.erase(AZStd::next(begin(mTextEntries), 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 0f323ab00c..aa64581449 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h @@ -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; }; - AZStd::vector 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 b1a5c4699d..72a28a5d11 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp @@ -20,39 +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; + 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); } @@ -66,32 +66,32 @@ namespace RenderGL // Deactivate void GLSLShader::Deactivate() { - for (const size_t index : mActivatedAttribs) + for (const size_t index : m_activatedAttribs) { - glDisableVertexAttribArray(mAttributes[index].mLocation); + glDisableVertexAttribArray(m_attributes[index].m_location); } - for (const size_t index : mActivatedTextures) + for (const size_t index : m_activatedTextures) { - 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(); - mActivatedTextures.clear(); + 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; @@ -114,14 +114,14 @@ namespace RenderGL return false; } - mFileName = filename; + m_fileName = filename; AZStd::string text; text.reserve(4096); text = "#version 120\n"; // build define string - for (const AZStd::string& define : mDefines) + for (const AZStd::string& define : m_defines) { text += AZStd::string::format("#define %s\n", define.c_str()); } @@ -171,10 +171,10 @@ namespace RenderGL AZStd::invoke(func, static_cast(this), object, logLen, &logWritten, text.data()); // if there are any defines, print that out too - if (!mDefines.empty()) + if (!m_defines.empty()) { AZStd::string dStr; - for (const AZStd::string& define : mDefines) + for (const AZStd::string& define : m_defines) { if (!dStr.empty()) { @@ -183,11 +183,11 @@ namespace RenderGL 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()); @@ -204,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; } @@ -258,35 +258,35 @@ namespace RenderGL return nullptr; } - return &mAttributes[index]; + return &m_attributes[index]; } // FindAttributeIndex size_t GLSLShader::FindAttributeIndex(const char* name) { - const auto foundAttribute = AZStd::find_if(begin(mAttributes), end(mAttributes), [name](const auto& attribute) + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [name](const auto& attribute) { - return AzFramework::StringFunc::Equal(attribute.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 - attribute.mLocation >= 0; + attribute.m_location >= 0; }); - if (foundAttribute != end(mAttributes)) + if (foundAttribute != end(m_attributes)) { - return AZStd::distance(begin(mAttributes), foundAttribute); + return AZStd::distance(begin(m_attributes), foundAttribute); } // the parameter wasn't cached, try to retrieve it - const GLint loc = glGetAttribLocation(mProgram, name); - mAttributes.emplace_back(name, loc, true); + const GLint loc = glGetAttribLocation(m_program, name); + m_attributes.emplace_back(name, loc, true); if (loc < 0) { return InvalidIndex; } - return mAttributes.size() - 1; + return m_attributes.size() - 1; } @@ -299,7 +299,7 @@ namespace RenderGL return InvalidIndex; } - return p->mLocation; + return p->m_location; } @@ -312,33 +312,33 @@ namespace RenderGL return nullptr; } - return &mUniforms[index]; + return &m_uniforms[index]; } // FindUniformIndex size_t GLSLShader::FindUniformIndex(const char* name) { - const auto foundUniform = AZStd::find_if(begin(mUniforms), end(mUniforms), [name](const auto& uniform) + const auto foundUniform = AZStd::find_if(begin(m_uniforms), end(m_uniforms), [name](const auto& uniform) { - return AzFramework::StringFunc::Equal(uniform.mName.c_str(), name, false /* no case */) && - uniform.mLocation >= 0; + return AzFramework::StringFunc::Equal(uniform.m_name.c_str(), name, false /* no case */) && + uniform.m_location >= 0; }); - if (foundUniform != end(mUniforms)) + if (foundUniform != end(m_uniforms)) { - return AZStd::distance(begin(mUniforms), foundUniform); + return AZStd::distance(begin(m_uniforms), foundUniform); } // the parameter wasn't cached, try to retrieve it - const GLint loc = glGetUniformLocation(mProgram, name); - mUniforms.emplace_back(name, loc, false); + const GLint loc = glGetUniformLocation(m_program, name); + m_uniforms.emplace_back(name, loc, false); if (loc < 0) { return InvalidIndex; } - return mUniforms.size() - 1; + return m_uniforms.size() - 1; } @@ -351,12 +351,12 @@ namespace RenderGL 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.emplace_back(index); + m_activatedAttribs.emplace_back(index); } @@ -369,7 +369,7 @@ namespace RenderGL return; } - glUniform1f(param->mLocation, value); + glUniform1f(param->m_location, value); } @@ -382,7 +382,7 @@ namespace RenderGL return; } - glUniform1f(param->mLocation, (float)value); + glUniform1f(param->m_location, (float)value); } @@ -395,7 +395,7 @@ namespace RenderGL return; } - glUniform4fv(param->mLocation, 1, (float*)&color); + glUniform4fv(param->m_location, 1, (float*)&color); } @@ -408,7 +408,7 @@ namespace RenderGL return; } - glUniform2fv(param->mLocation, 1, (float*)&vector); + glUniform2fv(param->m_location, 1, (float*)&vector); } @@ -421,7 +421,7 @@ namespace RenderGL return; } - glUniform3fv(param->mLocation, 1, (float*)&vector); + glUniform3fv(param->m_location, 1, (float*)&vector); } @@ -434,7 +434,7 @@ namespace RenderGL return; } - glUniform4fv(param->mLocation, 1, (float*)&vector); + glUniform4fv(param->m_location, 1, (float*)&vector); } @@ -454,7 +454,7 @@ namespace RenderGL return; } - glUniformMatrix4fv(param->mLocation, 1, !transpose, (float*)&matrix); + glUniformMatrix4fv(param->m_location, 1, !transpose, (float*)&matrix); } @@ -467,7 +467,7 @@ namespace RenderGL return; } - glUniformMatrix4fv(param->mLocation, count, GL_FALSE, (float*)matrices); + glUniformMatrix4fv(param->m_location, count, GL_FALSE, (float*)matrices); } @@ -480,7 +480,7 @@ namespace RenderGL } // update the value - glUniform1fv(param->mLocation, numFloats, values); + glUniform1fv(param->m_location, numFloats, values); } @@ -493,13 +493,13 @@ namespace RenderGL 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) @@ -507,11 +507,11 @@ 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.emplace_back(index); + m_activatedTextures.emplace_back(index); } @@ -524,13 +524,13 @@ namespace RenderGL 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) @@ -538,11 +538,11 @@ 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.emplace_back(index); + m_activatedTextures.emplace_back(index); } @@ -550,7 +550,7 @@ namespace RenderGL bool GLSLShader::CheckIfIsDefined(const char* attributeName) const { // get the number of defines and iterate through them - return AZStd::any_of(begin(mDefines), end(mDefines), [attributeName](const AZStd::string& define) + return AZStd::any_of(begin(m_defines), end(m_defines), [attributeName](const AZStd::string& define) { 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 0db7948e8f..5975470f86 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h @@ -39,7 +39,7 @@ namespace RenderGL size_t FindAttributeLocation(const char* name); uint32 GetType() const override; - MCORE_INLINE unsigned int GetProgram() const { return mProgram; } + 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, AZStd::vector& defines); @@ -65,12 +65,12 @@ 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; }; size_t FindAttributeIndex(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; - AZStd::vector mActivatedAttribs; - AZStd::vector mActivatedTextures; - AZStd::vector mUniforms; - AZStd::vector mAttributes; - AZStd::vector 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 4802477e08..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; } @@ -411,8 +376,8 @@ namespace RenderGL // LoadShader 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(); @@ -422,7 +387,7 @@ namespace RenderGL } // 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; @@ -436,7 +401,7 @@ namespace RenderGL return nullptr; } - mShaderCache.AddShader(cacheLookupStr, shader); + m_shaderCache.AddShader(cacheLookupStr, shader); return shader; } @@ -463,7 +428,7 @@ namespace RenderGL // SetShader void GraphicsManager::SetShader(Shader* shader) { - if (mActiveShader == shader) + if (m_activeShader == shader) { return; } @@ -471,7 +436,7 @@ namespace RenderGL if (shader == nullptr) { glUseProgram(0); - mActiveShader = nullptr; + m_activeShader = nullptr; return; } @@ -481,7 +446,7 @@ namespace RenderGL glUseProgram(g->GetProgram()); } - mActiveShader = shader; + m_activeShader = shader; } @@ -529,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 e13e643938..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, 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 9c0522a6da..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 = InvalidIndex; - mMaterialIndex = MCORE_INVALIDINDEX32; + m_nodeIndex = InvalidIndex; + m_materialIndex = MCORE_INVALIDINDEX32; } - size_t 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. */ - AZStd::vector 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 84c369bcbc..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,8 +73,8 @@ namespace RenderGL { GLSLShader::Deactivate(); - mRT->Deactivate(); - mRT = nullptr; + m_rt->Deactivate(); + m_rt = nullptr; } @@ -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 b02ab99505..4d25017831 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp @@ -15,7 +15,7 @@ namespace RenderGL // constructor ShaderCache::ShaderCache() { - mEntries.reserve(128); + m_entries.reserve(128); } @@ -30,41 +30,41 @@ namespace RenderGL void ShaderCache::Release() { // delete all shaders - for (Entry& entry : mEntries) + for (Entry& entry : m_entries) { - entry.mName.clear(); - delete entry.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.emplace_back(Entry{filename, 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 auto foundShader = AZStd::find_if(begin(mEntries), end(mEntries), [filename](const Entry& entry) + const auto foundShader = AZStd::find_if(begin(m_entries), end(m_entries), [filename](const Entry& entry) { - return AzFramework::StringFunc::Equal(entry.mName, filename, false /* no case */); + return AzFramework::StringFunc::Equal(entry.m_name, filename, false /* no case */); }); - return foundShader != end(mEntries) ? foundShader->mShader : nullptr; + 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 { - return AZStd::any_of(begin(mEntries), end(mEntries), [shader](const Entry& entry) + return AZStd::any_of(begin(m_entries), end(m_entries), [shader](const Entry& entry) { - return entry.mShader == shader; + 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 18281f286b..c2537e4948 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp @@ -20,13 +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(); + m_diffuseMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); + m_specularMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); + m_normalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); SetAttribute(LIGHTING, true); SetAttribute(SKINNING, false); @@ -48,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; } @@ -58,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); } @@ -162,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(); } @@ -176,7 +172,7 @@ namespace RenderGL bool StandardMaterial::Init(EMotionFX::Material* material) { initializeOpenGLFunctions(); - mMaterial = material; + m_material = material; if (material->GetType() == EMotionFX::StandardMaterial::TYPE_ID) { @@ -191,34 +187,34 @@ namespace RenderGL { 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; } @@ -232,10 +228,10 @@ namespace RenderGL // void StandardMaterial::SetAttribute(EAttribute attribute, bool enabled) { - if (mAttributes[attribute] != enabled) + if (m_attributes[attribute] != enabled) { - mAttributes[attribute] = enabled; - mAttributesUpdated = true; + m_attributes[attribute] = enabled; + m_attributesUpdated = true; } } @@ -244,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; } @@ -257,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 size_t numBones = primitive->mBoneNodeIndices.size(); + const size_t numBones = primitive->m_boneNodeIndices.size(); for (size_t i = 0; i < numBones; ++i) { - const size_t 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, aznumeric_caster(numBones)); + m_activeShader->SetUniform("matBones", m_boneMatrices, aznumeric_caster(numBones)); } const MCommon::Camera* camera = GetGraphicsManager()->GetCamera(); @@ -280,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); } @@ -294,16 +290,16 @@ 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 - for (GLSLShader* shader : mShaders) + for (GLSLShader* shader : m_shaders) { if (shader == nullptr) { @@ -314,7 +310,7 @@ namespace RenderGL bool match = true; for (uint32 n = 0; n < NUM_ATTRIBUTES; ++n) { - if (mAttributes[n]) + if (m_attributes[n]) { if (shader->CheckIfIsDefined(AttributeToString((EAttribute)n)) == false) { @@ -335,13 +331,13 @@ namespace RenderGL // in case we have found a matching shader update the active shader if (match) { - mActiveShader = shader; + 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! @@ -349,17 +345,17 @@ namespace RenderGL AZStd::vector defines; for (uint32 n = 0; n < NUM_ATTRIBUTES; ++n) { - if (mAttributes[n]) + if (m_attributes[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.emplace_back(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 d9eb23b50a..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; - AZStd::vector 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 dfdce36284..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,26 +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.reserve(128); + m_entries.reserve(128); } @@ -73,27 +73,27 @@ namespace RenderGL void TextureCache::Release() { // delete all textures - for (Entry& entry : mEntries) + for (Entry& entry : m_entries) { - delete entry.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.emplace_back(Entry{filename, texture}); + m_entries.emplace_back(Entry{filename, texture}); } @@ -101,11 +101,11 @@ namespace RenderGL Texture* TextureCache::FindTexture(const char* filename) const { // get the number of entries and iterate through them - const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [filename](const Entry& entry) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [filename](const Entry& entry) { - return AzFramework::StringFunc::Equal(entry.mName.c_str(), filename, false /* no case */); + return AzFramework::StringFunc::Equal(entry.m_name.c_str(), filename, false /* no case */); }); - return foundEntry != end(mEntries) ? foundEntry->mTexture : nullptr; + return foundEntry != end(m_entries) ? foundEntry->m_texture : nullptr; } @@ -113,9 +113,9 @@ namespace RenderGL bool TextureCache::CheckIfHasTexture(Texture* texture) const { // get the number of entries and iterate through them - return AZStd::any_of(begin(mEntries), end(mEntries), [texture](const Entry& entry) + return AZStd::any_of(begin(m_entries), end(m_entries), [texture](const Entry& entry) { - return entry.mTexture == texture; + return entry.m_texture == texture; }); } @@ -123,15 +123,15 @@ namespace RenderGL // remove an item from the cache void TextureCache::RemoveTexture(Texture* texture) { - const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [texture](const Entry& entry) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [texture](const Entry& entry) { - return entry.mTexture == texture; + return entry.m_texture == texture; }); - if (foundEntry != end(mEntries)) + if (foundEntry != end(m_entries)) { - delete foundEntry->mTexture; - mEntries.erase(foundEntry); + delete foundEntry->m_texture; + m_entries.erase(foundEntry); } } @@ -156,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; } @@ -182,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 43d0f1a635..4350cd67c7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h @@ -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; }; - AZStd::vector 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 0b87477114..36158306a1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h @@ -47,29 +47,29 @@ 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; - AZStd::vector 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(); @@ -85,14 +85,14 @@ namespace RenderGL EMotionFX::Mesh::EMeshType ClassifyMeshType(EMotionFX::Node* node, EMotionFX::Mesh* mesh, size_t lodLevel); - AZStd::vector< AZStd::vector > mMaterials; - MCore::Array2D mDynamicNodes; - MCore::Array2D mPrimitives[3]; - AZStd::vector mHomoMaterials; - AZStd::vector mVertexBuffers[3]; - AZStd::vector 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 08bf9dfa58..d33cfcfd7d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h @@ -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; }; // - AZStd::vector 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 6f1293e1a3..df039b7186 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -57,14 +57,14 @@ namespace EMotionFX 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); } //---------------------------------------------------- @@ -73,33 +73,33 @@ namespace EMotionFX { SetName(name); - mSkeleton = Skeleton::Create(); + m_skeleton = Skeleton::Create(); - mMotionExtractionNode = InvalidIndex; - mRetargetRootNode = InvalidIndex; - mThreadIndex = 0; - mCustomData = nullptr; - mID = aznumeric_caster(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.emplace_back(); - mMorphSetups.emplace_back(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); @@ -110,15 +110,15 @@ namespace EMotionFX ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnActorDestroyed, this); GetEventManager().OnDeleteActor(this); - mNodeMirrorInfos.clear(); + 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). @@ -130,41 +130,41 @@ namespace EMotionFX result->SetFileName(GetFileName()); // copy the actor attributes - result->mMotionExtractionNode = mMotionExtractionNode; - result->mUnitType = mUnitType; - result->mFileUnitType = mFileUnitType; + result->m_motionExtractionNode = m_motionExtractionNode; + result->m_unitType = m_unitType; + result->m_fileUnitType = m_fileUnitType; result->m_staticAabb = m_staticAabb; - result->mRetargetRootNode = mRetargetRootNode; - result->mInvBindPoseTransforms = mInvBindPoseTransforms; + 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.size()); - for (size_t i = 0; i < mMaterials.size(); ++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 - result->mMaterials[i].reserve(mMaterials[i].size()); - for (const Material* material : mMaterials[i]) + result->m_materials[i].reserve(m_materials[i].size()); + for (const Material* material : m_materials[i]) { 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 - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); const size_t numLodLevels = m_meshLodData.m_lodLevels.size(); MeshLODData& resultMeshLodData = result->m_meshLodData; @@ -172,26 +172,26 @@ namespace EMotionFX result->SetNumLODLevels(static_cast(numLodLevels)); for (size_t lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) { - const AZStd::vector& nodeInfos = m_meshLodData.m_lodLevels[lodLevel].mNodeInfos; - AZStd::vector& 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 (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.size()); - for (size_t i = 0; i < mMorphSetups.size(); ++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 { @@ -200,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())); @@ -222,37 +222,37 @@ namespace EMotionFX // init node mirror info void Actor::AllocateNodeMirrorInfos() { - const size_t numNodes = mSkeleton->GetNumNodes(); - mNodeMirrorInfos.resize(numNodes); + const size_t numNodes = m_skeleton->GetNumNodes(); + m_nodeMirrorInfos.resize(numNodes); // init the data 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(); - mNodeMirrorInfos.shrink_to_fit(); + m_nodeMirrorInfos.clear(); + m_nodeMirrorInfos.shrink_to_fit(); } // check if we have our axes detected bool Actor::GetHasMirrorAxesDetected() const { - if (mNodeMirrorInfos.empty()) + if (m_nodeMirrorInfos.empty()) { return false; } - return AZStd::all_of(begin(mNodeMirrorInfos), end(mNodeMirrorInfos), [](const NodeMirrorInfo& nodeMirrorInfo) + return AZStd::all_of(begin(m_nodeMirrorInfos), end(m_nodeMirrorInfos), [](const NodeMirrorInfo& nodeMirrorInfo) { - return nodeMirrorInfo.mAxis != MCORE_INVALIDINDEX8; + return nodeMirrorInfo.m_axis != MCORE_INVALIDINDEX8; }); } @@ -261,7 +261,7 @@ namespace EMotionFX void Actor::RemoveAllMaterials() { // for all LODs - for (AZStd::vector& materials : mMaterials) + for (AZStd::vector& materials : m_materials) { // delete all materials for (Material* material : materials) @@ -270,7 +270,7 @@ namespace EMotionFX } } - mMaterials.clear(); + m_materials.clear(); } @@ -281,8 +281,8 @@ namespace EMotionFX lodLevels.emplace_back(); LODLevel& newLOD = lodLevels.back(); - const size_t numNodes = mSkeleton->GetNumNodes(); - 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; @@ -290,25 +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(lodLevels.size()); + m_materials.resize(lodLevels.size()); // create an empty morph setup for the new LOD level - mMorphSetups.emplace_back(nullptr); + m_morphSetups.emplace_back(nullptr); // copy data from the previous LOD level if wanted if (copyFromLastLODLevel && numLODs > 0) @@ -325,22 +325,22 @@ namespace EMotionFX lodLevels.emplace(lodLevels.begin()+insertAt); LODLevel& newLOD = lodLevels[insertAt]; const size_t lodIndex = insertAt; - const size_t numNodes = mSkeleton->GetNumNodes(); - newLOD.mNodeInfos.resize(numNodes); + 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 (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.emplace(AZStd::next(begin(mMaterials), insertAt)); + m_materials.emplace(AZStd::next(begin(m_materials), insertAt)); // create an empty morph setup for the new LOD level - mMorphSetups.emplace(AZStd::next(begin(mMorphSetups), insertAt), nullptr); + m_morphSetups.emplace(AZStd::next(begin(m_morphSetups), insertAt), nullptr); } // replace existing LOD level with the current actor @@ -352,10 +352,10 @@ namespace EMotionFX const LODLevel& sourceLOD = copyLodLevels[copyLODLevel]; LODLevel& targetLOD = lodLevels[replaceLODLevel]; - const size_t numNodes = mSkeleton->GetNumNodes(); + 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) @@ -363,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 @@ -397,30 +397,30 @@ namespace EMotionFX // copy the materials const size_t numMaterials = copyActor->GetNumMaterials(copyLODLevel); - for (Material* i : mMaterials[replaceLODLevel]) + for (Material* i : m_materials[replaceLODLevel]) { i->Destroy(); } - mMaterials[replaceLODLevel].clear(); - mMaterials[replaceLODLevel].reserve(numMaterials); + 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; } } @@ -430,30 +430,30 @@ namespace EMotionFX m_meshLodData.m_lodLevels.resize(numLODs); // reserve space for the materials - mMaterials.resize(numLODs); + m_materials.resize(numLODs); if (adjustMorphSetup) { - mMorphSetups.resize(numLODs); - AZStd::fill(begin(mMorphSetups), AZStd::next(begin(mMorphSetups), numLODs), 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 size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { 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; } } } @@ -465,7 +465,7 @@ namespace EMotionFX uint32 totalVerts = 0; uint32 totalIndices = 0; - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -503,7 +503,7 @@ namespace EMotionFX uint32 totalIndices = 0; // for all nodes - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -547,7 +547,7 @@ namespace EMotionFX uint32 totalIndices = 0; // for all nodes - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -588,7 +588,7 @@ namespace EMotionFX { size_t maxInfluences = 0; - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -608,7 +608,7 @@ namespace EMotionFX void Actor::VerifySkinning(AZStd::vector& conflictNodeFlags, size_t skeletalLODLevel, size_t geometryLODLevel) { // get the number of nodes - const size_t 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.size() != numNodes) @@ -623,7 +623,7 @@ namespace EMotionFX 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 @@ -696,7 +696,7 @@ namespace EMotionFX bool Actor::CheckIfHasMeshes(size_t lodLevel) const { // check if any of the nodes has a mesh - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { if (GetMesh(lodLevel, i)) @@ -712,7 +712,7 @@ namespace EMotionFX bool Actor::CheckIfHasSkinnedMeshes(size_t lodLevel) const { - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { const Mesh* mesh = GetMesh(lodLevel, i); @@ -749,7 +749,7 @@ namespace EMotionFX const size_t numLODs = GetNumLODLevels(); // for all LODs, get rid of all the morph setups for each geometry LOD - for (MorphSetup* morphSetup : mMorphSetups) + for (MorphSetup* morphSetup : m_morphSetups) { if (morphSetup) { @@ -763,7 +763,7 @@ namespace EMotionFX if (deleteMeshDeformers) { // for all nodes - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { // process all LOD levels @@ -818,7 +818,7 @@ namespace EMotionFX bool Actor::CheckIfIsMaterialUsed(size_t lodLevel, size_t index) const { // iterate through all nodes of the actor and check its meshes - const size_t numNodes = mSkeleton->GetNumNodes(); + 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 @@ -836,11 +836,11 @@ namespace EMotionFX // remove the given material and reassign all material numbers of the submeshes void Actor::RemoveMaterial(size_t lodLevel, size_t index) { - MCORE_ASSERT(lodLevel < mMaterials.size()); + MCORE_ASSERT(lodLevel < m_materials.size()); // first of all remove the given material - mMaterials[lodLevel][index]->Destroy(); - mMaterials[lodLevel].erase(AZStd::next(begin(mMaterials[lodLevel]), index)); + m_materials[lodLevel][index]->Destroy(); + m_materials[lodLevel].erase(AZStd::next(begin(m_materials[lodLevel]), index)); } @@ -854,11 +854,11 @@ namespace EMotionFX size_t maxNumChilds = 0; // traverse through all root nodes - const size_t numRootNodes = mSkeleton->GetNumRootNodes(); + 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 size_t numChildNodes = rootNode->GetNumChildNodesRecursive(); @@ -890,7 +890,7 @@ namespace EMotionFX outBoneList->clear(); // for all nodes - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t n = 0; n < numNodes; ++n) { Mesh* mesh = GetMesh(lodLevel, n); @@ -938,22 +938,22 @@ namespace EMotionFX for (size_t i = 0; i < numDependencies; ++i) { // add it to the actor instance - mDependencies.emplace_back(*actor->GetDependency(i)); + m_dependencies.emplace_back(*actor->GetDependency(i)); // recursive into the actor we are dependent on - RecursiveAddDependencies(actor->GetDependency(i)->mActor); + 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(); } @@ -966,11 +966,11 @@ namespace EMotionFX AZStd::string nameB; // search through all nodes to find the best match - const size_t numNodes = mSkeleton->GetNumNodes(); + 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)) @@ -1023,28 +1023,28 @@ namespace EMotionFX bool Actor::MapNodeMotionSource(const char* sourceNodeName, const char* destNodeName) { // find the source node index - const size_t sourceNodeIndex = mSkeleton->FindNodeByNameNoCase(sourceNodeName)->GetNodeIndex(); + const size_t sourceNodeIndex = m_skeleton->FindNodeByNameNoCase(sourceNodeName)->GetNodeIndex(); if (sourceNodeIndex == InvalidIndex) { return false; } // find the dest node index - const size_t destNodeIndex = mSkeleton->FindNodeByNameNoCase(destNodeName)->GetNodeIndex(); + const size_t destNodeIndex = m_skeleton->FindNodeByNameNoCase(destNodeName)->GetNodeIndex(); if (destNodeIndex == InvalidIndex) { return false; } // allocate the data if we haven't already - if (mNodeMirrorInfos.empty()) + 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; @@ -1055,14 +1055,14 @@ namespace EMotionFX bool Actor::MapNodeMotionSource(uint16 sourceNodeIndex, uint16 targetNodeIndex) { // allocate the data if we haven't already - if (mNodeMirrorInfos.empty()) + 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; @@ -1075,10 +1075,10 @@ namespace EMotionFX void Actor::MatchNodeMotionSources(const char* subStringA, const char* subStringB) { // try to map all nodes - const size_t numNodes = mSkeleton->GetNumNodes(); + 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); @@ -1086,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()); } } } @@ -1096,14 +1096,14 @@ 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; } @@ -1114,13 +1114,13 @@ namespace EMotionFX do { - curNodeIndex = mSkeleton->GetNode(curNodeIndex)->GetParentIndex(); + 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; } @@ -1140,10 +1140,10 @@ namespace EMotionFX for (size_t geomLod = 0; geomLod < numGeomLODs; ++geomLod) { // for all nodes - const size_t numNodes = mSkeleton->GetNumNodes(); + 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); @@ -1182,7 +1182,7 @@ 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 size_t newNodeIndex = FindFirstActiveParentBone(geomLod, influence->GetNodeNr()); @@ -1227,7 +1227,7 @@ namespace EMotionFX 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 @@ -1252,16 +1252,16 @@ namespace EMotionFX void Actor::SetMotionExtractionNodeIndex(size_t nodeIndex) { - mMotionExtractionNode = nodeIndex; + m_motionExtractionNode = nodeIndex; ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnMotionExtractionNodeChanged, this, GetMotionExtractionNode()); } Node* Actor::GetMotionExtractionNode() const { - if (mMotionExtractionNode != InvalidIndex && - mMotionExtractionNode < mSkeleton->GetNumNodes()) + if (m_motionExtractionNode != InvalidIndex && + m_motionExtractionNode < m_skeleton->GetNumNodes()) { - return mSkeleton->GetNode(mMotionExtractionNode); + return m_skeleton->GetNode(m_motionExtractionNode); } return nullptr; @@ -1270,10 +1270,10 @@ namespace EMotionFX void Actor::ReinitializeMeshDeformers() { const size_t numLODLevels = GetNumLODLevels(); - const size_t numNodes = mSkeleton->GetNumNodes(); + 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 (size_t lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) @@ -1291,18 +1291,18 @@ namespace EMotionFX // post init 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 size_t numNodes = mSkeleton->GetNumNodes(); - mInvBindPoseTransforms.resize(numNodes); + 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 @@ -1315,12 +1315,12 @@ namespace EMotionFX ReinitializeMeshDeformers(); // make sure our world space bind pose is updated too - if (mMorphSetups.size() > 0 && mMorphSetups[0]) + if (m_morphSetups.size() > 0 && m_morphSetups[0]) { - mSkeleton->GetBindPose()->ResizeNumMorphs(mMorphSetups[0]->GetNumMorphTargets()); + m_skeleton->GetBindPose()->ResizeNumMorphs(m_morphSetups[0]->GetNumMorphTargets()); } - mSkeleton->GetBindPose()->ForceUpdateFullModelSpacePose(); - mSkeleton->GetBindPose()->ZeroMorphWeights(); + m_skeleton->GetBindPose()->ForceUpdateFullModelSpacePose(); + m_skeleton->GetBindPose()->ZeroMorphWeights(); if (!GetHasMirrorInfo()) { @@ -1446,10 +1446,10 @@ namespace EMotionFX { // Optional, not all actors have morph targets. const size_t numLODLevels = m_meshAsset->GetLodAssets().size(); - mMorphSetups.resize(numLODLevels); + m_morphSetups.resize(numLODLevels); for (size_t i = 0; i < numLODLevels; ++i) { - mMorphSetups[i] = nullptr; + m_morphSetups[i] = nullptr; } } @@ -1466,7 +1466,7 @@ 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() { - ActorInstance* actorInstance = ActorInstance::Create(this, nullptr, mThreadIndex); + ActorInstance* actorInstance = ActorInstance::Create(this, nullptr, m_threadIndex); actorInstance->UpdateMeshDeformers(0.0f); actorInstance->UpdateStaticBasedAabbDimensions(); actorInstance->GetStaticBasedAabb(&m_staticAabb); @@ -1480,7 +1480,7 @@ namespace EMotionFX outPoints.clear(); const size_t geomLODLevel = 0; - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { @@ -1548,17 +1548,17 @@ namespace EMotionFX Pose pose; pose.LinkToActor(this); - const size_t numNodes = mNodeMirrorInfos.size(); + 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); @@ -1584,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; } @@ -1637,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; } @@ -1665,9 +1663,8 @@ 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; } } } @@ -1676,21 +1673,21 @@ namespace EMotionFX // get the array of node mirror infos const AZStd::vector& Actor::GetNodeMirrorInfos() const { - return mNodeMirrorInfos; + return m_nodeMirrorInfos; } // get the array of node mirror infos AZStd::vector& Actor::GetNodeMirrorInfos() { - return mNodeMirrorInfos; + return m_nodeMirrorInfos; } // set the node mirror infos directly void Actor::SetNodeMirrorInfos(const AZStd::vector& mirrorInfos) { - mNodeMirrorInfos = mirrorInfos; + m_nodeMirrorInfos = mirrorInfos; } @@ -1700,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); @@ -1721,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; } @@ -1734,7 +1729,7 @@ namespace EMotionFX uint16 result = MCORE_INVALIDINDEX16; // find nodes that have the mirrored transform - const size_t numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { const Transform& curNodeTransform = pose.GetModelSpaceTransform(i); @@ -1743,12 +1738,12 @@ namespace EMotionFX // 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++; @@ -1759,8 +1754,8 @@ namespace EMotionFX if (numMatches == 1) { - const size_t hierarchyDepth = mSkeleton->CalcHierarchyDepthForNode(nodeIndex); - const size_t 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; @@ -1776,7 +1771,7 @@ 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 size_t numMorphs = bindPose.GetNumMorphWeights(); @@ -1785,55 +1780,55 @@ namespace EMotionFX 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(size_t numNodes) { - mSkeleton->SetNumNodes(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 AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.emplace_back(); + 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(size_t nodeIndex, const char* name, size_t parentIndex) @@ -1855,37 +1850,37 @@ namespace EMotionFX void Actor::RemoveNode(size_t nr, bool delMem) { - mSkeleton->RemoveNode(nr, delMem); + m_skeleton->RemoveNode(nr, delMem); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.erase(AZStd::next(begin(lodLevel.mNodeInfos), nr)); + lodLevel.m_nodeInfos.erase(AZStd::next(begin(lodLevel.m_nodeInfos), nr)); } } void Actor::DeleteAllNodes() { - mSkeleton->RemoveAllNodes(); + m_skeleton->RemoveAllNodes(); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.clear(); + lodLevel.m_nodeInfos.clear(); } } void Actor::ReserveMaterials(size_t lodLevel, size_t numMaterials) { - mMaterials[lodLevel].reserve(numMaterials); + m_materials[lodLevel].reserve(numMaterials); } // get a material Material* Actor::GetMaterial(size_t lodLevel, size_t nr) const { - MCORE_ASSERT(lodLevel < mMaterials.size()); - MCORE_ASSERT(nr < mMaterials[lodLevel].size()); - return mMaterials[lodLevel][nr]; + MCORE_ASSERT(lodLevel < m_materials.size()); + MCORE_ASSERT(nr < m_materials[lodLevel].size()); + return m_materials[lodLevel][nr]; } @@ -1893,27 +1888,27 @@ namespace EMotionFX size_t Actor::FindMaterialIndexByName(size_t lodLevel, const char* name) const { // search through all materials - const auto foundMaterial = AZStd::find_if(mMaterials[lodLevel].begin(), mMaterials[lodLevel].end(), [name](const Material* material) + const auto foundMaterial = AZStd::find_if(m_materials[lodLevel].begin(), m_materials[lodLevel].end(), [name](const Material* material) { return material->GetNameString() == name; }); - return foundMaterial != mMaterials[lodLevel].end() ? AZStd::distance(mMaterials[lodLevel].begin(), foundMaterial) : InvalidIndex; + return foundMaterial != m_materials[lodLevel].end() ? AZStd::distance(m_materials[lodLevel].begin(), foundMaterial) : InvalidIndex; } // set a material void Actor::SetMaterial(size_t lodLevel, size_t nr, Material* mat) { - mMaterials[lodLevel][nr] = mat; + m_materials[lodLevel][nr] = mat; } void Actor::AddMaterial(size_t lodLevel, Material* mat) { - mMaterials[lodLevel].emplace_back(mat); + m_materials[lodLevel].emplace_back(mat); } size_t Actor::GetNumMaterials(size_t lodLevel) const { - return mMaterials[lodLevel].size(); + return m_materials[lodLevel].size(); } size_t Actor::GetNumLODLevels() const @@ -1924,67 +1919,67 @@ namespace EMotionFX 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.emplace_back(dependency); + m_dependencies.emplace_back(dependency); } 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); } @@ -1992,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; @@ -2012,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; } @@ -2028,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; } @@ -2044,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; @@ -2059,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; @@ -2073,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 @@ -2107,7 +2102,7 @@ namespace EMotionFX bool Actor::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return mIsOwnedByRuntime; + return m_isOwnedByRuntime; #else return true; #endif @@ -2128,20 +2123,20 @@ namespace EMotionFX 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(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(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; } @@ -2149,7 +2144,7 @@ namespace EMotionFX 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) @@ -2178,43 +2173,43 @@ namespace EMotionFX 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; } @@ -2233,7 +2228,7 @@ namespace EMotionFX 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(); @@ -2241,7 +2236,7 @@ namespace EMotionFX // calculate the inverse bind pose matrices for (size_t i = 0; i < numNodes; ++i) { - mInvBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); + m_invBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); } // update static aabb @@ -2283,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 != InvalidIndex); - if (mMotionExtractionNode == InvalidIndex) + 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); @@ -2338,13 +2333,13 @@ namespace EMotionFX void Actor::SetRetargetRootNodeIndex(size_t nodeIndex) { - mRetargetRootNode = nodeIndex; + m_retargetRootNode = nodeIndex; } void Actor::SetRetargetRootNode(Node* node) { - mRetargetRootNode = node ? node->GetNodeIndex() : InvalidIndex; + m_retargetRootNode = node ? node->GetNodeIndex() : InvalidIndex; } void Actor::InsertJointAndParents(size_t jointIndex, AZStd::unordered_set& includedJointIndices) @@ -2356,7 +2351,7 @@ namespace EMotionFX } // Add the parent. - const size_t parentIndex = mSkeleton->GetNode(jointIndex)->GetParentIndex(); + const size_t parentIndex = m_skeleton->GetNode(jointIndex)->GetParentIndex(); if (parentIndex != InvalidIndex) { InsertJointAndParents(parentIndex, includedJointIndices); @@ -2381,7 +2376,7 @@ namespace EMotionFX continue; } - const size_t numJoints = mSkeleton->GetNumNodes(); + const size_t numJoints = m_skeleton->GetNumNodes(); for (size_t jointIndex = 0; jointIndex < numJoints; ++jointIndex) { const Mesh* mesh = GetMesh(lod, jointIndex); @@ -2412,7 +2407,7 @@ namespace EMotionFX for (const AZStd::string& jointName : alwaysIncludeJoints) { size_t jointIndex = InvalidIndex; - if (!mSkeleton->FindNodeAndIndexByName(jointName, jointIndex)) + if (!m_skeleton->FindNodeAndIndexByName(jointName, jointIndex)) { if (!jointName.empty()) { @@ -2427,22 +2422,22 @@ namespace EMotionFX // Disable all joints first. 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 (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 (size_t 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 @@ -2455,10 +2450,10 @@ namespace EMotionFX for (size_t lod = 0; lod < numLODs; ++lod) { AZ_TracePrintf("EMotionFX", "[LOD %d]:", lod); - const size_t numJoints = mSkeleton->GetNumNodes(); + 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=%zu)", joint->GetName(), jointIndex); @@ -2485,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. - size_t numNodes = mSkeleton->GetNumNodes(); + size_t numNodes = m_skeleton->GetNumNodes(); AZStd::vector flags; AZStd::unordered_map childParentMap; flags.resize(numNodes); @@ -2494,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); @@ -2511,7 +2506,7 @@ namespace EMotionFX // Search the actor skeleton to find all the critical nodes. 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); @@ -2543,26 +2538,26 @@ namespace EMotionFX { 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 (size_t 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()); } @@ -2596,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() @@ -2610,18 +2605,18 @@ namespace EMotionFX lodLevels.clear(); SetNumLODLevels(numLODLevels, /*adjustMorphSetup=*/false); - const size_t numNodes = mSkeleton->GetNumNodes(); + 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(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); @@ -2635,13 +2630,13 @@ namespace EMotionFX } const size_t jointIndex = meshJoint->GetNodeIndex(); - NodeLODInfo& jointInfo = lodLevels[lodLevel].mNodeInfos[jointIndex]; + 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 @@ -2665,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)); } @@ -2685,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 @@ -2695,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; @@ -2714,7 +2709,7 @@ 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()); @@ -2734,14 +2729,14 @@ namespace EMotionFX const AZStd::array_view>& lodAssets = m_meshAsset->GetLodAssets(); const size_t numLODLevels = lodAssets.size(); - AZ_Assert(mMorphSetups.size() == 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; @@ -2756,21 +2751,21 @@ namespace EMotionFX } const size_t jointIndex = meshJoint->GetNodeIndex(); - NodeLODInfo& jointInfo = lodLevels[lodLevel].mNodeInfos[jointIndex]; - Mesh* mesh = jointInfo.mMesh; + 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 @@ -2809,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) { @@ -2822,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 efcfa52413..5c4a15e2d8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -68,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. */ }; // @@ -90,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 @@ -114,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. @@ -218,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 size_t GetMotionExtractionNodeIndex() const { return mMotionExtractionNode; } + MCORE_INLINE size_t GetMotionExtractionNodeIndex() const { return m_motionExtractionNode; } //--------------------------------------------------------------------- @@ -522,15 +522,15 @@ namespace EMotionFX * Get the number of dependencies. * @result The number of dependencies that this actor has on other actors. */ - MCORE_INLINE size_t GetNumDependencies() const { return mDependencies.size(); } + 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(size_t nr) { return &mDependencies[nr]; } - MCORE_INLINE const Dependency* GetDependency(size_t 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. @@ -546,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(size_t 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. @@ -649,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(size_t 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(size_t 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.size() != 0); } + MCORE_INLINE bool GetHasMirrorInfo() const { return (m_nodeMirrorInfos.size() != 0); } //--------------------------------------------------------------- @@ -754,16 +754,16 @@ namespace EMotionFX 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(size_t nodeIndex) const { return mInvBindPoseTransforms[nodeIndex]; } + MCORE_INLINE const Transform& GetInverseBindPoseTransform(size_t nodeIndex) const { return m_invBindPoseTransforms[nodeIndex]; } void ReleaseTransformData(); void ResizeTransformData(); @@ -773,8 +773,8 @@ namespace EMotionFX 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(size_t lodLevel, size_t nodeIndex) const; MeshDeformerStack* GetMeshDeformerStack(size_t lodLevel, size_t nodeIndex) const; @@ -787,8 +787,8 @@ namespace EMotionFX */ void FindMostInfluencedMeshPoints(const Node* node, AZStd::vector& outPoints) const; - MCORE_INLINE Skeleton* GetSkeleton() const { return mSkeleton; } - MCORE_INLINE size_t 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(size_t lodLevel, size_t nodeIndex, Mesh* mesh); void SetMeshDeformerStack(size_t lodLevel, size_t nodeIndex, MeshDeformerStack* stack); @@ -808,8 +808,8 @@ namespace EMotionFX EAxis FindBestMatchingMotionExtractionAxis() const; - MCORE_INLINE size_t GetRetargetRootNodeIndex() const { return mRetargetRootNode; } - MCORE_INLINE Node* GetRetargetRootNode() const { return (mRetargetRootNode != InvalidIndex) ? mSkeleton->GetNode(mRetargetRootNode) : nullptr; } + 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); @@ -857,8 +857,8 @@ namespace EMotionFX // data per node, per lod struct EMFX_API NodeLODInfo { - Mesh* mMesh; - MeshDeformerStack* mStack; + Mesh* m_mesh; + MeshDeformerStack* m_stack; NodeLODInfo(); NodeLODInfo(const NodeLODInfo&) = delete; @@ -868,10 +868,10 @@ namespace EMotionFX { return; } - mMesh = rhs.mMesh; - mStack = rhs.mStack; - rhs.mMesh = nullptr; - rhs.mStack = nullptr; + 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) @@ -880,10 +880,10 @@ namespace EMotionFX { return *this; } - mMesh = rhs.mMesh; - mStack = rhs.mStack; - rhs.mMesh = nullptr; - rhs.mStack = nullptr; + m_mesh = rhs.m_mesh; + m_stack = rhs.m_stack; + rhs.m_mesh = nullptr; + rhs.m_stack = nullptr; return *this; } ~NodeLODInfo(); @@ -892,7 +892,7 @@ namespace EMotionFX // a lod level struct EMFX_API LODLevel { - AZStd::vector mNodeInfos; + AZStd::vector m_nodeInfos; }; struct MeshLODData @@ -918,31 +918,31 @@ namespace EMotionFX Node* FindMeshJoint(const AZ::Data::Asset& lodModelAsset) const; - Skeleton* mSkeleton; /**< The skeleton, containing the nodes and bind pose. */ - AZStd::vector mDependencies; /**< The dependencies on other actors (shared meshes and transforms). */ - AZStd::string mName; /**< The name of the actor. */ - AZStd::string mFileName; /**< The filename of the actor. */ - AZStd::vector mNodeMirrorInfos; /**< The array of node mirror info. */ - AZStd::vector< AZStd::vector< Material* > > mMaterials; /**< A collection of materials (for each lod). */ - AZStd::vector< 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. */ - size_t 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. */ - size_t 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::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 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. */ + 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 f394dc4f5f..6097784e2f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -45,27 +45,27 @@ namespace EMotionFX { MCORE_ASSERT(actor); - 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 = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); - mVisualizeScale = 1.0f; - mMotionSamplingRate = 0.0f; - mMotionSamplingTimer = 0.0f; - - mTrajectoryDelta.IdentityWithZeroScale(); + 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; + + m_trajectoryDelta.IdentityWithZeroScale(); m_staticAabb = AZ::Aabb::CreateNull(); - mAnimGraphInstance = nullptr; + m_animGraphInstance = nullptr; // set the boolean defaults SetFlag(BOOL_ISVISIBLE, true); @@ -84,16 +84,16 @@ 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(); + Skeleton* skeleton = m_actor->GetSkeleton(); const size_t numNodes = skeleton->GetNumNodes(); for (size_t n = 0; n < numNodes; ++n) { @@ -104,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); @@ -133,7 +133,7 @@ namespace EMotionFX UpdateDependencies(); // update the static based AABB dimensions - m_staticAabb = mActor->GetStaticAabb(); + 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 @@ -141,7 +141,7 @@ namespace EMotionFX } // update the bounds - UpdateBounds(/*lodLevel=*/0, mBoundsUpdateType); + UpdateBounds(/*lodLevel=*/0, m_boundsUpdateType); // register it GetActorManager().RegisterActorInstance(this); @@ -156,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 size_t numAttachments = mAttachments.size(); + 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); @@ -181,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 @@ -223,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); } @@ -252,11 +252,11 @@ namespace EMotionFX // update the bounds when needed 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; } } @@ -270,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) { @@ -284,9 +284,9 @@ namespace EMotionFX } } } - else if (mMotionSystem) + else if (m_motionSystem) { - mMotionSystem->Update(timePassedInSeconds, (updateJointTransforms && sampleMotions)); + m_motionSystem->Update(timePassedInSeconds, (updateJointTransforms && sampleMotions)); } else { @@ -296,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(); @@ -312,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 { @@ -335,15 +335,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; } - mSelfAttachment->UpdateJointTransforms(*mTransformData->GetCurrentPose()); - mTransformData->GetCurrentPose()->ApplyMorphWeightsToActorInstance(); + m_selfAttachment->UpdateJointTransforms(*m_transformData->GetCurrentPose()); + m_transformData->GetCurrentPose()->ApplyMorphWeightsToActorInstance(); ApplyMorphSetup(); UpdateSkinningMatrices(); UpdateAttachments(); @@ -352,11 +352,11 @@ namespace EMotionFX // update the bounds when needed 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; } } } @@ -364,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 size_t numNodes = GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { const size_t nodeNumber = GetEnabledNode(i); - Transform skinningTransform = mActor->GetInverseBindPoseTransform(nodeNumber); + Transform skinningTransform = m_actor->GetInverseBindPoseTransform(nodeNumber); skinningTransform.Multiply(pose->GetModelSpaceTransform(nodeNumber)); skinningMatrices[nodeNumber] = AZ::Matrix3x4::CreateFromTransform(skinningTransform.ToAZTransform()); } @@ -391,11 +391,11 @@ namespace EMotionFX timePassedInSeconds *= GetEMotionFX().GetGlobalSimulationSpeed(); // Update the mesh deformers. - const Skeleton* skeleton = mActor->GetSkeleton(); - for (uint16 nodeNr : mEnabledNodes) + const Skeleton* skeleton = m_actor->GetSkeleton(); + for (uint16 nodeNr : m_enabledNodes) { 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); @@ -409,11 +409,11 @@ namespace EMotionFX timePassedInSeconds *= GetEMotionFX().GetGlobalSimulationSpeed(); // Update the mesh morph deformers. - const Skeleton* skeleton = mActor->GetSkeleton(); - for (uint16 nodeNr : mEnabledNodes) + const Skeleton* skeleton = m_actor->GetSkeleton(); + for (uint16 nodeNr : m_enabledNodes) { 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); @@ -440,7 +440,7 @@ namespace EMotionFX GetActorManager().GetScheduler()->RecursiveRemoveActorInstance(root); // add the attachment - mAttachments.emplace_back(attachment); + m_attachments.emplace_back(attachment); ActorInstance* attachmentActorInstance = attachment->GetAttachmentActorInstance(); if (attachmentActorInstance) { @@ -460,12 +460,12 @@ namespace EMotionFX size_t ActorInstance::FindAttachmentNr(ActorInstance* actorInstance) { // for all attachments - const auto foundAttachment = AZStd::find_if(mAttachments.begin(), mAttachments.end(), [actorInstance](const Attachment* attachment) + const auto foundAttachment = AZStd::find_if(m_attachments.begin(), m_attachments.end(), [actorInstance](const Attachment* attachment) { return attachment->GetAttachmentActorInstance() == actorInstance; }); - return foundAttachment != mAttachments.end() ? AZStd::distance(mAttachments.begin(), foundAttachment) : InvalidIndex; + return foundAttachment != m_attachments.end() ? AZStd::distance(m_attachments.begin(), foundAttachment) : InvalidIndex; } // remove an attachment by actor instance pointer @@ -486,14 +486,14 @@ namespace EMotionFX // remove an attachment void ActorInstance::RemoveAttachment(size_t nr, bool delFromMem) { - MCORE_ASSERT(nr < mAttachments.size()); + 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(); @@ -516,7 +516,7 @@ namespace EMotionFX } // remove it from the attachment list - mAttachments.erase(AZStd::next(begin(mAttachments), nr)); + m_attachments.erase(AZStd::next(begin(m_attachments), nr)); // and re-add the root to the scheduler GetActorManager().GetScheduler()->RecursiveInsertActorInstance(root, 0); @@ -532,9 +532,9 @@ namespace EMotionFX void ActorInstance::RemoveAllAttachments(bool delFromMem) { // keep removing the last attachment until there are none left - while (mAttachments.size()) + while (m_attachments.size()) { - RemoveAttachment(mAttachments.size() - 1, delFromMem); + RemoveAttachment(m_attachments.size() - 1, delFromMem); } } @@ -542,26 +542,26 @@ 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.emplace_back(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 size_t numDependencies = mActor->GetNumDependencies(); + const size_t numDependencies = m_actor->GetNumDependencies(); for (size_t i = 0; i < numDependencies; ++i) { - mDependencies.emplace_back(*mActor->GetDependency(i)); + m_dependencies.emplace_back(*m_actor->GetDependency(i)); } } // set the attachment matrices void ActorInstance::UpdateAttachments() { - for (Attachment* attachment : mAttachments) + for (Attachment* attachment : m_attachments) { attachment->Update(); } @@ -572,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); @@ -636,8 +636,8 @@ namespace EMotionFX { *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 size_t numNodes = GetNumEnabledNodes(); @@ -646,7 +646,7 @@ namespace EMotionFX const uint16 nodeNr = GetEnabledNode(i); if (skeleton->GetNode(nodeNr)->GetIncludeInBoundsCalc()) { - outResult->AddPoint(pose->GetWorldSpaceTransform(nodeNr).mPosition); + outResult->AddPoint(pose->GetWorldSpaceTransform(nodeNr).m_position); } } } @@ -656,8 +656,8 @@ namespace EMotionFX { *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 size_t numNodes = GetNumEnabledNodes(); @@ -667,7 +667,7 @@ namespace EMotionFX Node* node = skeleton->GetNode(nodeNr); // skip nodes without meshes - Mesh* mesh = mActor->GetMesh(geomLODLevel, nodeNr); + Mesh* mesh = m_actor->GetMesh(geomLODLevel, nodeNr); if (mesh == nullptr) { continue; @@ -692,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); } @@ -709,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; @@ -745,8 +745,8 @@ namespace EMotionFX // check intersection with a ray, but don't get the intersection point or closest intersecting node 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 size_t numNodes = GetNumEnabledNodes(); @@ -755,7 +755,7 @@ namespace EMotionFX 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; @@ -789,8 +789,8 @@ 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 const size_t numNodes = GetNumEnabledNodes(); @@ -798,7 +798,7 @@ namespace EMotionFX { 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; @@ -861,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) @@ -894,8 +894,8 @@ namespace EMotionFX // check intersection with a ray, but don't get the intersection point or closest intersecting node 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 const size_t numNodes = GetNumEnabledNodes(); @@ -905,7 +905,7 @@ namespace EMotionFX 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; @@ -953,8 +953,8 @@ 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 const size_t numNodes = GetNumEnabledNodes(); @@ -962,7 +962,7 @@ namespace EMotionFX { 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; @@ -1020,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) @@ -1058,12 +1058,12 @@ namespace EMotionFX void ActorInstance::EnableNode(uint16 nodeIndex) { // if this node already is at an enabled state, do nothing - if (AZStd::find(begin(mEnabledNodes), end(mEnabledNodes), nodeIndex) != end(mEnabledNodes)) + 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; @@ -1074,16 +1074,16 @@ namespace EMotionFX size_t parentIndex = skeleton->GetNode(curNode)->GetParentIndex(); if (parentIndex != InvalidIndex) { - const auto parentArrayIter = AZStd::find(begin(mEnabledNodes), end(mEnabledNodes), static_cast(parentIndex)); - if (parentArrayIter != end(mEnabledNodes)) + const auto parentArrayIter = AZStd::find(begin(m_enabledNodes), end(m_enabledNodes), static_cast(parentIndex)); + if (parentArrayIter != end(m_enabledNodes)) { - if (parentArrayIter + 1 == end(mEnabledNodes)) + if (parentArrayIter + 1 == end(m_enabledNodes)) { - mEnabledNodes.emplace_back(nodeIndex); + m_enabledNodes.emplace_back(nodeIndex); } else { - mEnabledNodes.emplace(parentArrayIter + 1, nodeIndex); + m_enabledNodes.emplace(parentArrayIter + 1, nodeIndex); } found = true; } @@ -1094,7 +1094,7 @@ namespace EMotionFX } else // if we're dealing with a root node, insert it in the front of the array { - mEnabledNodes.emplace(AZStd::next(begin(mEnabledNodes), 0), nodeIndex); + m_enabledNodes.emplace(AZStd::next(begin(m_enabledNodes), 0), nodeIndex); found = true; } } while (found == false); @@ -1104,24 +1104,24 @@ namespace EMotionFX void ActorInstance::DisableNode(uint16 nodeIndex) { // try to remove the node from the array - const auto it = AZStd::find(begin(mEnabledNodes), end(mEnabledNodes), nodeIndex); - if (it != end(mEnabledNodes)) + const auto it = AZStd::find(begin(m_enabledNodes), end(m_enabledNodes), nodeIndex); + if (it != end(m_enabledNodes)) { - mEnabledNodes.erase(it); + m_enabledNodes.erase(it); } } // enable all nodes void ActorInstance::EnableAllNodes() { - mEnabledNodes.resize(mActor->GetNumNodes()); - std::iota(mEnabledNodes.begin(), mEnabledNodes.end(), 0); + 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 @@ -1131,12 +1131,12 @@ namespace EMotionFX 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 size_t numNodes = GetNumNodes(); @@ -1145,7 +1145,7 @@ namespace EMotionFX 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 @@ -1171,13 +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); + m_lodLevel = MCore::Clamp(m_requestedLODLevel, 0, m_actor->GetNumLODLevels() - 1); } } @@ -1185,14 +1185,14 @@ namespace EMotionFX void ActorInstance::UpdateSkeletalLODFlags() { // change the state of all nodes that need state changes - Skeleton* skeleton = mActor->GetSkeleton(); + 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)); } @@ -1208,7 +1208,7 @@ namespace EMotionFX { uint32 numDisabledNodes = 0; - const Skeleton* skeleton = mActor->GetSkeleton(); + const Skeleton* skeleton = m_actor->GetSkeleton(); // get the number of nodes and iterate through them const size_t numNodes = GetNumNodes(); @@ -1259,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 @@ -1294,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); @@ -1311,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() != InvalidIndex); - 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); } @@ -1327,13 +1327,13 @@ namespace EMotionFX // Remove the trajectory transform from the motion extraction node to prevent double transformation. void ActorInstance::MotionExtractionCompensate(EMotionExtractionFlags motionExtractionFlags) { - const size_t motionExtractIndex = mActor->GetMotionExtractionNodeIndex(); + 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); @@ -1344,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; } @@ -1358,18 +1358,18 @@ namespace EMotionFX // Apply the motion extraction delta transform to the actor instance. void ActorInstance::ApplyMotionExtractionDelta(const Transform& trajectoryDelta) { - if (mActor->GetMotionExtractionNodeIndex() == InvalidIndex) + 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) @@ -1379,7 +1379,7 @@ namespace EMotionFX bool ActorInstance::GetMotionExtractionEnabled() const { - return (mBoolFlags & BOOL_MOTIONEXTRACTION) != 0; + return (m_boolFlags & BOOL_MOTIONEXTRACTION) != 0; } // update the static based aabb dimensions @@ -1393,7 +1393,7 @@ namespace EMotionFX UpdateMeshDeformers(0.0f); // calculate the aabb of this - if (mActor->CheckIfHasMeshes(0)) + if (m_actor->CheckIfHasMeshes(0)) { CalcMeshBasedAabb(0, &m_staticAabb); } @@ -1402,7 +1402,7 @@ namespace EMotionFX CalcNodeBasedAabb(&m_staticAabb); } - mLocalTransform = orgTransform; + m_localTransform = orgTransform; } // calculate the moved static based aabb @@ -1410,52 +1410,52 @@ namespace EMotionFX { if (GetIsSkinAttachment()) { - mSelfAttachment->GetAttachToActorInstance()->CalcStaticBasedAabb(outResult); + m_selfAttachment->GetAttachToActorInstance()->CalcStaticBasedAabb(outResult); return; } *outResult = m_staticAabb; EMFX_SCALECODE( - outResult->SetMin(m_staticAabb.GetMin() * mWorldTransform.mScale); - outResult->SetMax(m_staticAabb.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 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; } 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 @@ -1475,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) @@ -1551,52 +1551,52 @@ namespace EMotionFX size_t ActorInstance::GetNumAttachments() const { - return mAttachments.size(); + return m_attachments.size(); } 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; } size_t ActorInstance::GetNumDependencies() const { - return mDependencies.size(); + return m_dependencies.size(); } 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) @@ -1606,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) @@ -1616,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) @@ -1631,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 @@ -1639,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) @@ -1669,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; } } @@ -1741,7 +1741,7 @@ namespace EMotionFX SetIsVisible(isVisible); // recurse to all child attachments - for (Attachment* attachment : mAttachments) + for (Attachment* attachment : m_attachments) { attachment->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); } @@ -1750,9 +1750,9 @@ namespace EMotionFX void ActorInstance::RecursiveSetIsVisibleTowardsRoot(bool isVisible) { SetIsVisible(isVisible); - if (mSelfAttachment) + if (m_selfAttachment) { - mSelfAttachment->GetAttachToActorInstance()->RecursiveSetIsVisibleTowardsRoot(isVisible); + m_selfAttachment->GetAttachToActorInstance()->RecursiveSetIsVisibleTowardsRoot(isVisible); } } @@ -1764,7 +1764,7 @@ namespace EMotionFX // update the normal scale factor based on the bounds void ActorInstance::UpdateVisualizeScale() { - mVisualizeScale = 0.0f; + m_visualizeScale = 0.0f; UpdateMeshDeformers(0.0f); AZ::Aabb box = AZ::Aabb::CreateNull(); @@ -1773,29 +1773,29 @@ namespace EMotionFX if (box.IsValid()) { const float boxRadius = AZ::Vector3(box.GetMax() - box.GetMin()).GetLength() * 0.5f; - mVisualizeScale = MCore::Max(mVisualizeScale, boxRadius); + m_visualizeScale = MCore::Max(m_visualizeScale, boxRadius); } CalcMeshBasedAabb(0, &box); if (box.IsValid()) { const float boxRadius = AZ::Vector3(box.GetMax() - box.GetMin()).GetLength() * 0.5f; - mVisualizeScale = MCore::Max(mVisualizeScale, boxRadius); + 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h index 05a8136326..7ca134c0db 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h @@ -75,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. @@ -104,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. @@ -119,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. @@ -136,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. @@ -144,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. @@ -489,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 ( @@ -505,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; } ) /** @@ -520,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; } //------------------------------------------------------------------------------------------- @@ -788,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 AZStd::vector& 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 size_t GetNumEnabledNodes() const { return mEnabledNodes.size(); } + 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(size_t index) const { return mEnabledNodes[index]; } + MCORE_INLINE uint16 GetEnabledNode(size_t index) const { return m_enabledNodes[index]; } /** * Enable all nodes inside the actor instance. @@ -856,51 +856,51 @@ namespace EMotionFX float GetMotionSamplingTimer() const; float GetMotionSamplingRate() const; - MCORE_INLINE size_t 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. */ + 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 mLocalTransform = Transform::CreateIdentity(); - Transform mWorldTransform = Transform::CreateIdentity(); - Transform mWorldTransformInv = Transform::CreateIdentity(); - Transform mParentWorldTransform = Transform::CreateIdentity(); - Transform mTrajectoryDelta = Transform::CreateIdentityWithZeroScale(); - - AZStd::vector mAttachments; /**< The attachments linked to this actor instance. */ - AZStd::vector mDependencies; /**< The actor dependencies, which specify which Actor objects this instance is dependent on. */ - MorphSetupInstance* mMorphSetup; /**< The morph setup instance. */ - AZStd::vector 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. */ + 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 multi-thread 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. */ - size_t mLODLevel; /**< The current LOD level, where 0 is the highest detail. */ + 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 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 collision mesh based). */ + 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 mNumAttachmentRefs; /**< Specifies how many actor instances use this actor instance as attachment. */ - uint8 mBoolFlags; /**< Boolean flags. */ + 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp index b96a4b4962..681efb6039 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp @@ -25,15 +25,15 @@ namespace EMotionFX ActorManager::ActorManager() : BaseObject() { - mScheduler = nullptr; + 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); } @@ -41,7 +41,7 @@ namespace EMotionFX ActorManager::~ActorManager() { // delete the scheduler - mScheduler->Destroy(); + m_scheduler->Destroy(); } @@ -57,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(); @@ -75,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(); } @@ -91,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 size_t numActorInstances = mActorInstances.size(); + 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(); @@ -135,7 +135,7 @@ namespace EMotionFX { LockActorInstances(); - mActorInstances.emplace_back(actorInstance); + m_actorInstances.emplace_back(actorInstance); UpdateActorInstanceStatus(actorInstance, false); UnlockActorInstances(); @@ -209,7 +209,7 @@ namespace EMotionFX LockActorInstances(); // get the number of actor instances and iterate through them - const bool foundActor = AZStd::find(begin(mActorInstances), end(mActorInstances), actorInstance) != end(mActorInstances); + const bool foundActor = AZStd::find(begin(m_actorInstances), end(m_actorInstances), actorInstance) != end(m_actorInstances); UnlockActorInstances(); return foundActor; } @@ -218,19 +218,19 @@ namespace EMotionFX // find the given actor instance inside the actor manager and return its index size_t ActorManager::FindActorInstanceIndex(ActorInstance* actorInstance) const { - const auto foundActorInstance = AZStd::find(begin(mActorInstances), end(mActorInstances), actorInstance); - return foundActorInstance != end(mActorInstances) ? AZStd::distance(begin(mActorInstances), foundActorInstance) : InvalidIndex; + 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 { - const auto foundActorInstance = AZStd::find_if(begin(mActorInstances), end(mActorInstances), [id](const ActorInstance* actorInstance) + const auto foundActorInstance = AZStd::find_if(begin(m_actorInstances), end(m_actorInstances), [id](const ActorInstance* actorInstance) { return actorInstance->GetID() == id; }); - return foundActorInstance != end(mActorInstances) ? *foundActorInstance : nullptr; + return foundActorInstance != end(m_actorInstances) ? *foundActorInstance : nullptr; } @@ -259,7 +259,7 @@ namespace EMotionFX // unregister a given actor instance void ActorManager::UnregisterActorInstance(size_t nr) { - UnregisterActorInstance(mActorInstances[nr]); + UnregisterActorInstance(m_actorInstances[nr]); } @@ -284,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(); @@ -318,19 +318,19 @@ namespace EMotionFX if (actorInstance->GetAttachedTo() == nullptr) { // make sure it's in the root list - if (AZStd::find(begin(mRootActorInstances), end(mRootActorInstances), actorInstance) == end(mRootActorInstances)) + if (AZStd::find(begin(m_rootActorInstances), end(m_rootActorInstances), actorInstance) == end(m_rootActorInstances)) { - mRootActorInstances.emplace_back(actorInstance); + m_rootActorInstances.emplace_back(actorInstance); } } else // no root actor instance { // remove it from the root list - if (const auto it = AZStd::find(begin(mRootActorInstances), end(mRootActorInstances), actorInstance); it != end(mRootActorInstances)) + if (const auto it = AZStd::find(begin(m_rootActorInstances), end(m_rootActorInstances), actorInstance); it != end(m_rootActorInstances)) { - mRootActorInstances.erase(it); + m_rootActorInstances.erase(it); } - mScheduler->RecursiveRemoveActorInstance(actorInstance); + m_scheduler->RecursiveRemoveActorInstance(actorInstance); } if (lock) @@ -346,19 +346,19 @@ namespace EMotionFX LockActorInstances(); // remove the actor instance from the list - if (const auto it = AZStd::find(begin(mActorInstances), end(mActorInstances), instance); it != end(mActorInstances)) + if (const auto it = AZStd::find(begin(m_actorInstances), end(m_actorInstances), instance); it != end(m_actorInstances)) { - mActorInstances.erase(it); + m_actorInstances.erase(it); } // remove it from the list of roots, if it is in there - if (const auto it = AZStd::find(begin(mRootActorInstances), end(mRootActorInstances), instance); it != end(mRootActorInstances)) + if (const auto it = AZStd::find(begin(m_rootActorInstances), end(m_rootActorInstances), instance); it != end(m_rootActorInstances)) { - mRootActorInstances.erase(it); + m_rootActorInstances.erase(it); } // remove it from the schedule - mScheduler->RemoveActorInstance(instance); + m_scheduler->RemoveActorInstance(instance); UnlockActorInstances(); } @@ -366,25 +366,25 @@ 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(); } @@ -396,12 +396,12 @@ namespace EMotionFX 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 a7f12111ce..ff78250141 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h @@ -124,14 +124,14 @@ namespace EMotionFX * Get the number of actor instances that currently are registered. * @result The number of registered actor instances. */ - MCORE_INLINE size_t GetNumActorInstances() const { return mActorInstances.size(); } + 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(size_t nr) const { return mActorInstances[nr]; } + MCORE_INLINE ActorInstance* GetActorInstance(size_t nr) const { return m_actorInstances[nr]; } /** * Get the array of actor instances. @@ -201,7 +201,7 @@ namespace EMotionFX * horse is the root attachment instance. * @result Returns the number of root actor instances. */ - MCORE_INLINE size_t GetNumRootActorInstances() const { return mRootActorInstances.size(); } + 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(size_t 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: - AZStd::vector mActorInstances; /**< The registered actor instances. */ + AZStd::vector m_actorInstances; /**< The registered actor instances. */ AZStd::vector> m_actors; /**< The registered actors. */ - AZStd::vector 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 18fd7ff233..9ca73e423f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h @@ -80,14 +80,14 @@ namespace EMotionFX */ virtual size_t RemoveActorInstance(ActorInstance* actorInstance, size_t startStep = 0) = 0; - size_t GetNumUpdatedActorInstances() const { return mNumUpdated.GetValue(); } - size_t GetNumVisibleActorInstances() const { return mNumVisible.GetValue(); } - size_t 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::AtomicSizeT mNumUpdated; - MCore::AtomicSizeT mNumVisible; - MCore::AtomicSizeT 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 38fb6380e9..a9cfbc4379 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp @@ -35,21 +35,21 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(AnimGraph, AnimGraphAllocator, 0) AnimGraph::AnimGraph() - : mGameControllerSettings(aznew AnimGraphGameControllerSettings()) + : m_gameControllerSettings(aznew AnimGraphGameControllerSettings()) { - mID = aznumeric_caster(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); @@ -65,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; } @@ -106,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() @@ -307,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()) { @@ -365,7 +365,7 @@ namespace EMotionFX size_t AnimGraph::RecursiveCalcNumNodes() const { - return mRootStateMachine->RecursiveCalcNumNodes(); + return m_rootStateMachine->RecursiveCalcNumNodes(); } @@ -382,7 +382,7 @@ namespace EMotionFX void AnimGraph::RecursiveCalcStatistics(Statistics& outStatistics) const { - RecursiveCalcStatistics(outStatistics, mRootStateMachine); + RecursiveCalcStatistics(outStatistics, m_rootStateMachine); } @@ -425,35 +425,35 @@ namespace EMotionFX // recursively calculate the number of node connections 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 @@ -463,7 +463,7 @@ namespace EMotionFX bool AnimGraph::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return mIsOwnedByRuntime; + return m_isOwnedByRuntime; #else return true; #endif @@ -494,14 +494,14 @@ namespace EMotionFX // get a pointer to the given node group 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) @@ -517,18 +517,18 @@ namespace EMotionFX // find the node group index by name size_t AnimGraph::FindNodeGroupIndexByName(const char* groupName) const { - const auto foundNodeGroup = AZStd::find_if(begin(mNodeGroups), end(mNodeGroups), [groupName](const AnimGraphNodeGroup* nodeGroup) + const auto foundNodeGroup = AZStd::find_if(begin(m_nodeGroups), end(m_nodeGroups), [groupName](const AnimGraphNodeGroup* nodeGroup) { return nodeGroup->GetNameString() == groupName; }); - return foundNodeGroup != end(mNodeGroups) ? AZStd::distance(begin(mNodeGroups), foundNodeGroup) : InvalidIndex; + 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); } @@ -538,11 +538,11 @@ namespace EMotionFX // 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); } @@ -552,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 size_t AnimGraph::GetNumNodeGroups() const { - return 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())) @@ -618,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, 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 @@ -684,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) { @@ -696,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"); } } @@ -708,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(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.size()); - mNodes.emplace_back(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 @@ -733,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(); @@ -741,16 +741,16 @@ 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)) @@ -758,16 +758,16 @@ namespace EMotionFX AnimGraphNode* node = static_cast(object); const size_t nodeIndex = node->GetNodeIndex(); - const size_t numNodes = mNodes.size(); + 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.erase(AZStd::next(begin(mNodes), nodeIndex)); + m_nodes.erase(AZStd::next(begin(m_nodes), nodeIndex)); } } @@ -775,21 +775,21 @@ namespace EMotionFX // reserve space for a given amount of objects void AnimGraph::ReserveNumObjects(size_t numObjects) { - mObjects.reserve(numObjects); + m_objects.reserve(numObjects); } // reserve space for a given amount of nodes void AnimGraph::ReserveNumNodes(size_t numNodes) { - mNodes.reserve(numNodes); + m_nodes.reserve(numNodes); } // Calculate number of motion nodes in the graph size_t AnimGraph::CalcNumMotionNodes() const { - return AZStd::accumulate(begin(mNodes), end(mNodes), size_t{0}, [](size_t total, const AnimGraphNode* node) + return AZStd::accumulate(begin(m_nodes), end(m_nodes), size_t{0}, [](size_t total, const AnimGraphNode* node) { return total + azrtti_istypeof(node); }); @@ -806,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); } @@ -814,7 +814,7 @@ 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)); } @@ -822,7 +822,7 @@ namespace EMotionFX // decrease internal attribute indices by one, for values higher than the given parameter void AnimGraph::DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan) { - for (AnimGraphObject* object : mObjects) + for (AnimGraphObject* object : m_objects) { object->DecreaseInternalAttributeIndices(decreaseEverythingHigherThan); } @@ -831,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(); } @@ -904,7 +904,7 @@ namespace EMotionFX { for (AnimGraphInstance* animGraphInstance : m_animGraphInstances) { - animGraphInstance->SetRetargetingEnabled(mRetarget); + animGraphInstance->SetRetargetingEnabled(m_retarget); } } @@ -920,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) ; @@ -937,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) ; } @@ -1016,7 +1016,7 @@ namespace EMotionFX void AnimGraph::RemoveInvalidConnections(bool logWarnings) { // Iterate over all nodes - for (AnimGraphNode* node : mNodes) + for (AnimGraphNode* node : m_nodes) { for (size_t c = 0; c < node->GetNumConnections();) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h index a356b031aa..2a498f9f81 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h @@ -377,12 +377,12 @@ 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 - size_t GetNumObjects() const { return mObjects.size(); } - AnimGraphObject* GetObject(size_t index) const { return mObjects[index]; } + size_t GetNumObjects() const { return m_objects.size(); } + AnimGraphObject* GetObject(size_t index) const { return m_objects[index]; } void ReserveNumObjects(size_t numObjects); - size_t GetNumNodes() const { return mNodes.size(); } - AnimGraphNode* GetNode(size_t index) const { return mNodes[index]; } + 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; @@ -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; - AZStd::vector 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.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h index e0f6712145..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,7 +63,7 @@ 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 @@ -72,12 +72,12 @@ namespace EMotionFX 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,7 +111,7 @@ 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 @@ -120,12 +120,12 @@ namespace EMotionFX 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() {} }; 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 0403e277b6..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); } } 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.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h index d36a448be4..c4e123c0c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h @@ -96,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); 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 9ed0a0e527..d0c77721d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp @@ -37,24 +37,24 @@ 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; } m_eventHandlersByEventType.resize(EVENT_TYPE_ANIM_GRAPH_INSTANCE_LAST_EVENT - EVENT_TYPE_ANIM_GRAPH_INSTANCE_FIRST_EVENT + 1); @@ -71,7 +71,7 @@ namespace EMotionFX // create the parameter value objects CreateParameterValues(); - mAnimGraph->Unlock(); + m_animGraph->Unlock(); GetEventManager().OnCreateAnimGraphInstance(this); } @@ -92,7 +92,7 @@ namespace EMotionFX GetEventManager().OnDeleteAnimGraphInstance(this); // automatically unregister the anim graph instance - if (mAutoUnregister) + if (m_autoUnregister) { GetAnimGraphManager().RemoveAnimGraphInstance(this, false); } @@ -127,7 +127,7 @@ namespace EMotionFX m_leaderGraphs.clear(); // unregister from the animgraph - mAnimGraph->RemoveAnimGraphInstance(this); + m_animGraph->RemoveAnimGraphInstance(this); } @@ -143,7 +143,7 @@ namespace EMotionFX { if (delFromMem) { - for (MCore::Attribute* paramValue : mParamValues) + for (MCore::Attribute* paramValue : m_paramValues) { if (paramValue) { @@ -152,14 +152,14 @@ namespace EMotionFX } } - 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) { @@ -173,7 +173,7 @@ namespace EMotionFX size_t AnimGraphInstance::AddInternalAttribute(MCore::Attribute* attribute) { - MCore::LockGuard lock(mMutex); + MCore::LockGuard lock(m_mutex); m_internalAttributes.emplace_back(attribute); return m_internalAttributes.size() - 1; @@ -194,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]; @@ -219,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(); @@ -250,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); } } @@ -264,14 +264,14 @@ namespace EMotionFX { RemoveAllParameters(true); - const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - mParamValues.resize(valueParameters.size()); + const ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); + m_paramValues.resize(valueParameters.size()); // init the values - const size_t numParams = mParamValues.size(); + 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(); } } @@ -280,22 +280,22 @@ namespace EMotionFX void AnimGraphInstance::AddMissingParameterValues() { // check how many parameters we need to add - const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - const ptrdiff_t numToAdd = aznumeric_cast(valueParameters.size()) - mParamValues.size(); + 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(valueParameters.size()); + m_paramValues.reserve(valueParameters.size()); // add the remaining parameters - const size_t startIndex = mParamValues.size(); + const size_t startIndex = m_paramValues.size(); for (ptrdiff_t i = 0; i < numToAdd; ++i) { const size_t index = startIndex + i; - mParamValues.emplace_back(valueParameters[index]->ConstructDefaultValueAsAttribute()); + m_paramValues.emplace_back(valueParameters[index]->ConstructDefaultValueAsAttribute()); } } @@ -305,31 +305,31 @@ namespace EMotionFX { if (delFromMem) { - if (mParamValues[index]) + if (m_paramValues[index]) { - delete mParamValues[index]; + delete m_paramValues[index]; } } - mParamValues.erase(AZStd::next(begin(mParamValues), index)); + m_paramValues.erase(AZStd::next(begin(m_paramValues), index)); } // reinitialize the parameter 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 size_t parameterValueCount = mParamValues.size(); + const size_t parameterValueCount = m_paramValues.size(); for (size_t i = 0; i < parameterValueCount; ++i) { ReInitParameterValue(i); @@ -341,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; @@ -382,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; @@ -486,28 +486,28 @@ 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[paramIndex.GetValue()]; + return m_paramValues[paramIndex.GetValue()]; } // add the last anim graph parameter to this instance void AnimGraphInstance::AddParameterValue() { - mParamValues.emplace_back(nullptr); - ReInitParameterValue(mParamValues.size() - 1); + m_paramValues.emplace_back(nullptr); + ReInitParameterValue(m_paramValues.size() - 1); } // add the parameter of the animgraph, at a given index void AnimGraphInstance::InsertParameterValue(size_t index) { - mParamValues.emplace(AZStd::next(begin(mParamValues), index), nullptr); + m_paramValues.emplace(AZStd::next(begin(m_paramValues), index), nullptr); ReInitParameterValue(index); } @@ -515,7 +515,7 @@ namespace EMotionFX // move the parameter from old index to new index 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 @@ -524,18 +524,18 @@ namespace EMotionFX for (size_t paramIndex = oldIndex; paramIndex > newIndex; paramIndex--) { const size_t prevIndex = paramIndex - 1; - mParamValues[paramIndex] = mParamValues[prevIndex]; + m_paramValues[paramIndex] = m_paramValues[prevIndex]; } - mParamValues[newIndex] = oldAttribute; + m_paramValues[newIndex] = oldAttribute; } else { for (size_t paramIndex = oldIndex; paramIndex < newIndex; paramIndex++) { const size_t nexIndex = paramIndex + 1; - mParamValues[paramIndex] = mParamValues[nexIndex]; + m_paramValues[paramIndex] = m_paramValues[nexIndex]; } - mParamValues[newIndex] = oldAttribute; + m_paramValues[newIndex] = oldAttribute; } } @@ -566,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); @@ -576,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 @@ -599,7 +599,7 @@ namespace EMotionFX bool AnimGraphInstance::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return mIsOwnedByRuntime; + return m_isOwnedByRuntime; #else return true; #endif @@ -610,7 +610,7 @@ namespace EMotionFX 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; @@ -654,7 +654,7 @@ namespace EMotionFX void AnimGraphInstance::AddUniqueObjectData() { m_uniqueDatas.emplace_back(nullptr); - mObjectFlags.emplace_back(0); + m_objectFlags.emplace_back(0); } // remove the given unique data object @@ -672,7 +672,7 @@ namespace EMotionFX } m_uniqueDatas.erase(m_uniqueDatas.begin() + index); - mObjectFlags.erase(AZStd::next(begin(mObjectFlags), index)); + m_objectFlags.erase(AZStd::next(begin(m_objectFlags), index)); } @@ -680,7 +680,7 @@ namespace EMotionFX { AnimGraphObjectData* data = m_uniqueDatas[index]; m_uniqueDatas.erase(m_uniqueDatas.begin() + index); - mObjectFlags.erase(AZStd::next(begin(mObjectFlags), index)); + m_objectFlags.erase(AZStd::next(begin(m_objectFlags), index)); if (delFromMem && data) { data->Destroy(); @@ -703,7 +703,7 @@ namespace EMotionFX } m_uniqueDatas.clear(); - mObjectFlags.clear(); + m_objectFlags.clear(); } @@ -807,13 +807,13 @@ namespace EMotionFX // init the hashmap void AnimGraphInstance::InitUniqueDatas() { - const size_t numObjects = mAnimGraph->GetNumObjects(); + const size_t numObjects = m_animGraph->GetNumObjects(); m_uniqueDatas.resize(numObjects); - mObjectFlags.resize(numObjects); + m_objectFlags.resize(numObjects); for (size_t i = 0; i < numObjects; ++i) { m_uniqueDatas[i] = nullptr; - mObjectFlags[i] = 0; + m_objectFlags[i] = 0; } } @@ -821,7 +821,7 @@ namespace EMotionFX // get the root node AnimGraphNode* AnimGraphInstance::GetRootNode() const { - return mAnimGraph->GetRootStateMachine(); + return m_animGraph->GetRootStateMachine(); } @@ -832,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(); } @@ -855,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 @@ -876,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(); @@ -901,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(); @@ -923,14 +923,14 @@ 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) { - for (uint32& objectFlag : mObjectFlags) + for (uint32& objectFlag : m_objectFlags) { objectFlag &= ~flagsToDisable; } @@ -940,10 +940,10 @@ namespace EMotionFX // reset all node pose ref counts void AnimGraphInstance::ResetPoseRefCountsForAllNodes() { - const size_t numNodes = mAnimGraph->GetNumNodes(); + 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); } } @@ -951,10 +951,10 @@ namespace EMotionFX // reset all node pose ref counts void AnimGraphInstance::ResetRefDataRefCountsForAllNodes() { - const size_t numNodes = mAnimGraph->GetNumNodes(); + 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); } } @@ -962,7 +962,7 @@ namespace EMotionFX // reset all node flags void AnimGraphInstance::ResetFlagsForAllObjects() { - MCore::MemSet(mObjectFlags.data(), 0, sizeof(uint32) * mObjectFlags.size()); + MCore::MemSet(m_objectFlags.data(), 0, sizeof(uint32) * m_objectFlags.size()); for (AnimGraphInstance* childInstance : m_childAnimGraphInstances) { @@ -974,11 +974,11 @@ namespace EMotionFX // reset flags for all nodes void AnimGraphInstance::ResetFlagsForAllNodes(uint32 flagsToDisable) { - const size_t numNodes = mAnimGraph->GetNumNodes(); + 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()) { @@ -1009,14 +1009,14 @@ 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) @@ -1052,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 size_t numNodes = mAnimGraph->GetNumNodes(); + 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; } @@ -1172,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) @@ -1252,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 size_t numNodes = mAnimGraph->GetNumNodes(); + 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) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h index 9366fcff86..81bae83515 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h @@ -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; } @@ -118,7 +118,7 @@ namespace EMotionFX template 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(size_t 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; @@ -237,39 +237,39 @@ 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(size_t objectIndex) const { return mObjectFlags[objectIndex]; } - MCORE_INLINE void SetObjectFlags(size_t objectIndex, uint32 flags) { mObjectFlags[objectIndex] = flags; } - MCORE_INLINE void EnableObjectFlags(size_t objectIndex, uint32 flagsToEnable) { mObjectFlags[objectIndex] |= flagsToEnable; } - MCORE_INLINE void DisableObjectFlags(size_t objectIndex, uint32 flagsToDisable) { mObjectFlags[objectIndex] &= ~flagsToDisable; } + 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(size_t 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(size_t objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_OUTPUT_READY) != 0; } + 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(size_t objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_SYNCED) != 0; } + 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(size_t objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_RESYNC) != 0; } + 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(size_t objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_UPDATE_READY) != 0; } + 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(size_t objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_TOPDOWNUPDATE_READY) != 0; } + 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(size_t objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_POSTUPDATE_READY) != 0; } + 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; @@ -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. - AZStd::vector 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 - AZStd::vector 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 fc74d747c6..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,7 +125,7 @@ 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 size_t animGraphIndex = FindAnimGraphIndex(animGraph); @@ -141,18 +141,18 @@ 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. @@ -172,14 +172,14 @@ 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 size_t instanceIndex = FindAnimGraphInstanceIndex(animGraphInstance); @@ -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); @@ -220,30 +220,30 @@ namespace EMotionFX 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 InvalidIndex; } - const size_t index = iterator - mAnimGraphs.begin(); + const size_t index = iterator - m_animGraphs.begin(); return index; } 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 InvalidIndex; } - const size_t index = iterator - mAnimGraphInstances.begin(); + const size_t index = iterator - m_animGraphInstances.begin(); return index; } @@ -251,9 +251,9 @@ namespace EMotionFX // 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 55ee6599fd..acff1779bb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h @@ -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,8 +48,8 @@ namespace EMotionFX bool RemoveAnimGraph(AnimGraph* animGraph, bool delFromMemory = true); void RemoveAllAnimGraphs(bool delFromMemory = true); - MCORE_INLINE size_t GetNumAnimGraphs() const { MCore::LockGuardRecursive lock(mAnimGraphLock); return mAnimGraphs.size(); } - MCORE_INLINE AnimGraph* GetAnimGraph(size_t 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; size_t FindAnimGraphIndex(AnimGraph* animGraph) const; @@ -64,8 +64,8 @@ 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]; } size_t FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const; @@ -74,11 +74,11 @@ namespace EMotionFX 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 9303ea96c5..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. @@ -162,7 +162,7 @@ namespace EMotionFX 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 67c3f276cc..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(InvalidIndex) - , 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,16 +232,16 @@ 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 } @@ -259,23 +251,23 @@ namespace EMotionFX 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 size_t index = AZStd::distance(mChildNodes.begin(), iterator); + 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) { @@ -386,35 +378,35 @@ namespace EMotionFX // find a child node index by name size_t AnimGraphNode::FindChildNodeIndex(const char* name) const { - const auto foundChildNode = AZStd::find_if(begin(mChildNodes), end(mChildNodes), [name](const AnimGraphNode* childNode) + const auto foundChildNode = AZStd::find_if(begin(m_childNodes), end(m_childNodes), [name](const AnimGraphNode* childNode) { return childNode->GetNameString() == name; }); - return foundChildNode != end(mChildNodes) ? AZStd::distance(begin(mChildNodes), foundChildNode) : InvalidIndex; + return foundChildNode != end(m_childNodes) ? AZStd::distance(begin(m_childNodes), foundChildNode) : InvalidIndex; } // find a child node index size_t AnimGraphNode::FindChildNodeIndex(AnimGraphNode* node) const { - const auto foundChildNode = AZStd::find(mChildNodes.begin(), mChildNodes.end(), node); - return foundChildNode != end(mChildNodes) ? AZStd::distance(begin(mChildNodes), foundChildNode) : InvalidIndex; + 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 { - const auto foundChild = AZStd::find_if(begin(mChildNodes), end(mChildNodes), [nodeType](const AnimGraphNode* childNode) + const auto foundChild = AZStd::find_if(begin(m_childNodes), end(m_childNodes), [nodeType](const AnimGraphNode* childNode) { return azrtti_typeid(childNode) == nodeType; }); - return foundChild != end(mChildNodes) ? *foundChild : nullptr; + return foundChild != end(m_childNodes) ? *foundChild : nullptr; } bool AnimGraphNode::HasChildNodeOfType(const AZ::TypeId& nodeType) const { - return AZStd::any_of(begin(mChildNodes), end(mChildNodes), [nodeType](const AnimGraphNode* childNode) + return AZStd::any_of(begin(m_childNodes), end(m_childNodes), [nodeType](const AnimGraphNode* childNode) { return azrtti_typeid(childNode) == nodeType; }); @@ -424,7 +416,7 @@ namespace EMotionFX // does this node has a specific incoming connection? bool AnimGraphNode::GetHasConnection(AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) const { - return AZStd::any_of(begin(mConnections), end(mConnections), [sourceNode, sourcePort, targetPort](const BlendTreeConnection* connection) + return AZStd::any_of(begin(m_connections), end(m_connections), [sourceNode, sourcePort, targetPort](const BlendTreeConnection* connection) { return connection->GetSourceNode() == sourceNode && connection->GetSourcePort() == sourcePort && connection->GetTargetPort() == targetPort; }); @@ -433,16 +425,16 @@ namespace EMotionFX // 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; @@ -454,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) { @@ -467,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); } } @@ -496,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) { @@ -512,44 +504,44 @@ namespace EMotionFX // initialize the input ports void AnimGraphNode::InitInputPorts(size_t numPorts) { - mInputPorts.resize(numPorts); + m_inputPorts.resize(numPorts); } // initialize the output ports void AnimGraphNode::InitOutputPorts(size_t numPorts) { - mOutputPorts.resize(numPorts); + m_outputPorts.resize(numPorts); } // find a given output port number size_t AnimGraphNode::FindOutputPortIndex(const AZStd::string& name) const { - const auto foundPort = AZStd::find_if(begin(mOutputPorts), end(mOutputPorts), [&name](const Port& port) + const auto foundPort = AZStd::find_if(begin(m_outputPorts), end(m_outputPorts), [&name](const Port& port) { return port.GetNameString() == name; }); - return foundPort != end(mOutputPorts) ? AZStd::distance(begin(mOutputPorts), foundPort) : InvalidIndex; + return foundPort != end(m_outputPorts) ? AZStd::distance(begin(m_outputPorts), foundPort) : InvalidIndex; } // find a given input port number size_t AnimGraphNode::FindInputPortIndex(const AZStd::string& name) const { - const auto foundPort = AZStd::find_if(begin(mInputPorts), end(mInputPorts), [&name](const Port& port) + const auto foundPort = AZStd::find_if(begin(m_inputPorts), end(m_inputPorts), [&name](const Port& port) { return port.GetNameString() == name; }); - return foundPort != end(mInputPorts) ? AZStd::distance(begin(mInputPorts), foundPort) : InvalidIndex; + return foundPort != end(m_inputPorts) ? AZStd::distance(begin(m_inputPorts), foundPort) : InvalidIndex; } // add an output port and return its index size_t AnimGraphNode::AddOutputPort() { - const size_t currentSize = mOutputPorts.size(); - mOutputPorts.emplace_back(); + const size_t currentSize = m_outputPorts.size(); + m_outputPorts.emplace_back(); return currentSize; } @@ -557,8 +549,8 @@ namespace EMotionFX // add an input port, and return its index 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); } @@ -566,16 +558,16 @@ namespace EMotionFX // setup a port 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(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); } @@ -583,7 +575,7 @@ namespace EMotionFX size_t AnimGraphNode::RecursiveCalcNumNodes() const { size_t result = 0; - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCountChildNodes(result); } @@ -598,7 +590,7 @@ namespace EMotionFX // increase the counter numNodes++; - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCountChildNodes(numNodes); } @@ -620,7 +612,7 @@ namespace EMotionFX // add the connections to our counter numConnections += GetNumConnections(); - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCountNodeConnections(numConnections); } @@ -634,13 +626,13 @@ namespace EMotionFX 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; } @@ -651,13 +643,13 @@ namespace EMotionFX 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; } @@ -668,13 +660,13 @@ namespace EMotionFX 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, size_t inputPortNr, uint32 portID) @@ -698,13 +690,13 @@ namespace EMotionFX 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) @@ -714,15 +706,13 @@ namespace EMotionFX 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, size_t inputPortNr, uint32 portID) @@ -731,15 +721,15 @@ namespace EMotionFX 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 @@ -749,16 +739,13 @@ namespace EMotionFX 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; } @@ -766,7 +753,7 @@ namespace EMotionFX { ResetUniqueData(animGraphInstance); - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveResetUniqueDatas(animGraphInstance); } @@ -788,7 +775,7 @@ namespace EMotionFX { InvalidateUniqueData(animGraphInstance); - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveInvalidateUniqueDatas(animGraphInstance); } @@ -800,7 +787,7 @@ namespace EMotionFX 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 @@ -812,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); } @@ -996,7 +983,7 @@ namespace EMotionFX const size_t numChildNodes = GetNumChildNodes(); for (size_t i = 0; i < numChildNodes; ++i) { - mChildNodes[i]->RecursiveOnChangeMotionSet(animGraphInstance, newMotionSet); + m_childNodes[i]->RecursiveOnChangeMotionSet(animGraphInstance, newMotionSet); } } @@ -1158,19 +1145,19 @@ namespace EMotionFX 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); } @@ -1183,7 +1170,7 @@ namespace EMotionFX return true; } - return AZStd::any_of(begin(mChildNodes), end(mChildNodes), [node](const AnimGraphNode* childNode) + return AZStd::any_of(begin(m_childNodes), end(m_childNodes), [node](const AnimGraphNode* childNode) { return childNode->RecursiveIsChildNode(node); }); @@ -1204,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); } } } @@ -1226,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()) @@ -1243,7 +1230,7 @@ namespace EMotionFX // collect child nodes of the given type 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) @@ -1255,7 +1242,7 @@ namespace EMotionFX 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) { @@ -1272,7 +1259,7 @@ namespace EMotionFX outNodes->emplace_back(const_cast(this)); } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectNodesOfType(nodeType, outNodes); } @@ -1306,7 +1293,7 @@ namespace EMotionFX } } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectTransitionConditionsOfType(conditionType, outConditions); } @@ -1320,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); } @@ -1328,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); } @@ -1379,44 +1366,44 @@ namespace EMotionFX // find the input port, based on the port name AnimGraphNode::Port* AnimGraphNode::FindInputPortByName(const AZStd::string& portName) { - const auto foundPort = AZStd::find_if(begin(mInputPorts), end(mInputPorts), [&portName](const Port& port) + const auto foundPort = AZStd::find_if(begin(m_inputPorts), end(m_inputPorts), [&portName](const Port& port) { return port.GetNameString() == portName; }); - return foundPort != end(mInputPorts) ? foundPort : nullptr; + return foundPort != end(m_inputPorts) ? foundPort : nullptr; } // find the output port, based on the port name AnimGraphNode::Port* AnimGraphNode::FindOutputPortByName(const AZStd::string& portName) { - const auto foundPort = AZStd::find_if(begin(mOutputPorts), end(mOutputPorts), [&portName](const Port& port) + const auto foundPort = AZStd::find_if(begin(m_outputPorts), end(m_outputPorts), [&portName](const Port& port) { return port.GetNameString() == portName; }); - return foundPort != end(mOutputPorts) ? foundPort : nullptr; + return foundPort != end(m_outputPorts) ? foundPort : nullptr; } // find the input port index, based on the port id size_t AnimGraphNode::FindInputPortByID(uint32 portID) const { - const auto foundPort = AZStd::find_if(begin(mInputPorts), end(mInputPorts), [portID](const Port& port) + const auto foundPort = AZStd::find_if(begin(m_inputPorts), end(m_inputPorts), [portID](const Port& port) { - return port.mPortID == portID; + return port.m_portId == portID; }); - return foundPort != end(mInputPorts) ? AZStd::distance(begin(mInputPorts), foundPort) : InvalidIndex; + return foundPort != end(m_inputPorts) ? AZStd::distance(begin(m_inputPorts), foundPort) : InvalidIndex; } // find the output port index, based on the port id size_t AnimGraphNode::FindOutputPortByID(uint32 portID) const { - const auto foundPort = AZStd::find_if(begin(mOutputPorts), end(mOutputPorts), [portID](const Port& port) + const auto foundPort = AZStd::find_if(begin(m_outputPorts), end(m_outputPorts), [portID](const Port& port) { - return port.mPortID == portID; + return port.m_portId == portID; }); - return foundPort != end(mOutputPorts) ? AZStd::distance(begin(mOutputPorts), foundPort) : InvalidIndex; + return foundPort != end(m_outputPorts) ? AZStd::distance(begin(m_outputPorts), foundPort) : InvalidIndex; } @@ -1434,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) @@ -1463,12 +1450,12 @@ namespace EMotionFX { 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) @@ -1509,7 +1496,7 @@ namespace EMotionFX BlendTreeConnection* AnimGraphNode::FindConnectionById(AnimGraphConnectionId connectionId) const { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { if (connection->GetId() == connectionId) { @@ -1523,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); } @@ -1543,7 +1530,7 @@ namespace EMotionFX { outObjects.emplace_back(const_cast(this)); - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectObjects(outObjects); } @@ -1553,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); } @@ -1583,10 +1567,10 @@ namespace EMotionFX // iterate over all incoming connections bool syncTrackFound = false; size_t connectionIndex = InvalidIndex; - 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 @@ -1602,13 +1586,13 @@ namespace EMotionFX 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()); } } @@ -1616,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()); } @@ -1637,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); @@ -1650,7 +1634,7 @@ namespace EMotionFX { if (GetEMotionFX().GetIsInEditorMode()) { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { if (connection->GetSourceNode() == sourceNode) { @@ -1675,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) { @@ -1692,10 +1676,10 @@ namespace EMotionFX bool poseFound = false; 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 @@ -1709,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) @@ -1726,7 +1710,7 @@ namespace EMotionFX AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); if (poseFound && connectionIndex != InvalidIndex) { - const BlendTreeConnection* connection = mConnections[connectionIndex]; + const BlendTreeConnection* connection = m_connections[connectionIndex]; AnimGraphNode* sourceNode = connection->GetSourceNode(); AnimGraphRefCountedData* data = uniqueData->GetRefCountedData(); @@ -1740,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()); @@ -1764,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); } @@ -1918,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); @@ -1931,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())) { @@ -1953,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())) { @@ -1972,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()) { @@ -2008,10 +1992,10 @@ 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, i); MCORE_ASSERT(attribute->GetType() == AttributePose::TYPE_ID); @@ -2036,10 +2020,10 @@ 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, i); MCORE_ASSERT(attribute->GetType() == AttributePose::TYPE_ID); @@ -2055,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(); @@ -2070,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(); @@ -2125,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); } @@ -2141,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); @@ -2161,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); @@ -2182,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); @@ -2202,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(); @@ -2217,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(); @@ -2232,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(); @@ -2240,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 { @@ -2250,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 { @@ -2265,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) { @@ -2280,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); } @@ -2288,20 +2272,20 @@ namespace EMotionFX void AnimGraphNode::RemoveInternalAttributesForAllInstances() { // for all output ports - for (Port& port : mOutputPorts) + for (Port& port : m_outputPorts) { - const size_t internalAttributeIndex = port.mAttributeIndex; + 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 = InvalidIndex; + m_animGraph->DecreaseInternalAttributeIndices(internalAttributeIndex); + port.m_attributeIndex = InvalidIndex; } } } @@ -2310,11 +2294,11 @@ namespace EMotionFX // decrease values higher than a given param value void AnimGraphNode::DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan) { - for (Port& port : mOutputPorts) + for (Port& port : m_outputPorts) { - if (port.mAttributeIndex > decreaseEverythingHigherThan && port.mAttributeIndex != InvalidIndex) + if (port.m_attributeIndex > decreaseEverythingHigherThan && port.m_attributeIndex != InvalidIndex) { - port.mAttributeIndex--; + port.m_attributeIndex--; } } } @@ -2324,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(); } @@ -2357,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(size_t numChildNodes) { - mChildNodes.reserve(numChildNodes); + m_childNodes.reserve(numChildNodes); } @@ -2461,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); @@ -2470,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); @@ -2527,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 31d85b6f48..b515621c5b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h @@ -56,55 +56,55 @@ 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) - size_t 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 compatibleType : mCompatibleTypes) + 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 (compatibleType == 0) { return false; } - for (uint32 otherCompatibleTypeIndex : otherPort.mCompatibleTypes) + for (uint32 otherCompatibleTypeIndex : otherPort.m_compatibleTypes) { if (otherCompatibleTypeIndex == compatibleType) { @@ -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(InvalidIndex) { ClearCompatibleTypes(); } + : m_connection(nullptr) + , m_portId(MCORE_INVALIDINDEX32) + , m_nameId(MCORE_INVALIDINDEX32) + , m_attributeIndex(InvalidIndex) { ClearCompatibleTypes(); } virtual ~Port() { } }; @@ -448,7 +448,7 @@ namespace EMotionFX 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; @@ -458,7 +458,7 @@ namespace EMotionFX 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; @@ -648,114 +648,114 @@ namespace EMotionFX return static_cast(attrib); } - MCORE_INLINE MCore::Attribute* GetOutputAttribute(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { return mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance); } + 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, size_t inputPortNr, uint32 portID); @@ -797,10 +797,10 @@ 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; } + 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); @@ -810,19 +810,19 @@ namespace EMotionFX size_t AddOutputPort(); size_t AddInputPort(); virtual bool GetIsStateTransitionNode() const { return false; } - MCORE_INLINE MCore::Attribute* GetOutputValue(AnimGraphInstance* animGraphInstance, size_t portIndex) const { return animGraphInstance->GetInternalAttribute(mOutputPorts[portIndex].mAttributeIndex); } - MCORE_INLINE Port& GetInputPort(size_t index) { return mInputPorts[index]; } - MCORE_INLINE Port& GetOutputPort(size_t index) { return mOutputPorts[index]; } - MCORE_INLINE const Port& GetInputPort(size_t index) const { return mInputPorts[index]; } - MCORE_INLINE const Port& GetOutputPort(size_t 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 size_t GetNumConnections() const { return mConnections.size(); } - MCORE_INLINE BlendTreeConnection* GetConnection(size_t 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. @@ -880,9 +880,9 @@ namespace EMotionFX void CopyBaseNodeTo(AnimGraphNode* node) const; - MCORE_INLINE size_t GetNumChildNodes() const { return mChildNodes.size(); } - MCORE_INLINE AnimGraphNode* GetChildNode(size_t 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; @@ -924,8 +924,8 @@ namespace EMotionFX bool GetCanVisualize(AnimGraphInstance* animGraphInstance) const; - MCORE_INLINE size_t GetNodeIndex() const { return mNodeIndex; } - MCORE_INLINE void SetNodeIndex(size_t 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,23 +944,23 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); protected: - size_t 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp index a787dd25a2..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(InvalidIndex) - , 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 = InvalidIndex; - 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 68d49ca511..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(size_t syncIndex) { mSyncIndex = syncIndex; } - MCORE_INLINE size_t 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; - size_t 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 a14401d3c8..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,7 +26,7 @@ namespace EMotionFX AnimGraphNodeGroup::AnimGraphNodeGroup(const char* groupName) { SetName(groupName); - mIsVisible = true; + m_isVisible = true; } @@ -34,7 +34,7 @@ namespace EMotionFX { 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(size_t numNodes) { - mNodeIds.resize(numNodes); + m_nodeIds.resize(numNodes); } // get the number of nodes size_t AnimGraphNodeGroup::GetNumNodes() const { - return mNodeIds.size(); + return m_nodeIds.size(); } // set a given node to a given node number 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(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(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 611cfd6824..7e1fc909e5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h @@ -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 7b4afbd38a..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; } @@ -124,17 +124,17 @@ namespace EMotionFX 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() @@ -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 32905d66a7..ebc92964b0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h @@ -144,11 +144,11 @@ namespace EMotionFX virtual void RecursiveOnChangeMotionSet(AnimGraphInstance* animGraphInstance, MotionSet* newMotionSet) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(newMotionSet); } virtual void OnActorMotionExtractionNodeChanged() {} - MCORE_INLINE size_t GetObjectIndex() const { return mObjectIndex; } - MCORE_INLINE void SetObjectIndex(size_t index) { mObjectIndex = 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; } 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 @@ -166,8 +166,8 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); protected: - AnimGraph* mAnimGraph; - size_t 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 a2b21aec6a..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 size_t 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 f7f3a6c0bf..4d9d2ca999 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp @@ -16,10 +16,10 @@ namespace EMotionFX // constructor AnimGraphPosePool::AnimGraphPosePool() { - mPoses.reserve(12); - mFreePoses.reserve(12); + m_poses.reserve(12); + m_freePoses.reserve(12); Resize(8); - mMaxUsed = 0; + m_maxUsed = 0; } @@ -27,21 +27,21 @@ namespace EMotionFX AnimGraphPosePool::~AnimGraphPosePool() { // delete all poses - for (AnimGraphPose* pose : mPoses) + for (AnimGraphPose* pose : m_poses) { 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(size_t numPoses) { - const size_t numOldPoses = mPoses.size(); + const size_t numOldPoses = m_poses.size(); // if we will remove poses if (numPoses < numOldPoses) @@ -50,10 +50,10 @@ namespace EMotionFX const size_t numToRemove = numOldPoses - numPoses; for (size_t i = 0; i < numToRemove; ++i) { - AnimGraphPose* pose = mPoses.back(); - MCORE_ASSERT(AZStd::find(begin(mFreePoses), end(mFreePoses), pose) == end(mFreePoses)); // 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.erase(mFreePoses.end() - 1); + m_poses.erase(m_freePoses.end() - 1); } } else // we want to add new poses @@ -62,8 +62,8 @@ namespace EMotionFX for (size_t i = 0; i < numToAdd; ++i) { AnimGraphPose* newPose = new AnimGraphPose(); - mPoses.emplace_back(newPose); - mFreePoses.emplace_back(newPose); + m_poses.emplace_back(newPose); + m_freePoses.emplace_back(newPose); } } } @@ -73,22 +73,22 @@ namespace EMotionFX AnimGraphPose* AnimGraphPosePool::RequestPose(const ActorInstance* actorInstance) { // if we have no free poses left, allocate a new one - if (mFreePoses.empty()) + if (m_freePoses.empty()) { AnimGraphPose* newPose = new AnimGraphPose(); newPose->LinkToActorInstance(actorInstance); - mPoses.emplace_back(newPose); - mMaxUsed = AZStd::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.size() - 1]; + AnimGraphPose* pose = m_freePoses[m_freePoses.size() - 1]; //if (pose->GetActorInstance() != actorInstance) pose->LinkToActorInstance(actorInstance); - mFreePoses.pop_back(); // remove it from the list of free poses - mMaxUsed = AZStd::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; } @@ -97,8 +97,7 @@ namespace EMotionFX // free the pose again void AnimGraphPosePool::FreePose(AnimGraphPose* pose) { - //MCORE_ASSERT( mPoses.Contains(pose) ); - mFreePoses.emplace_back(pose); + m_freePoses.emplace_back(pose); pose->SetIsInUse(false); } @@ -106,7 +105,7 @@ namespace EMotionFX // free all poses void AnimGraphPosePool::FreeAllPoses() { - for (AnimGraphPose* curPose : mPoses) + for (AnimGraphPose* curPose : m_poses) { if (curPose->GetIsInUse()) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h index 8148d88926..a7244e2dc2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h @@ -41,15 +41,15 @@ namespace EMotionFX void FreeAllPoses(); - MCORE_INLINE size_t GetNumFreePoses() const { return mFreePoses.size(); } - MCORE_INLINE size_t GetNumPoses() const { return mPoses.size(); } - MCORE_INLINE size_t GetNumUsedPoses() const { return mPoses.size() - mFreePoses.size(); } - MCORE_INLINE size_t 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: - AZStd::vector mPoses; - AZStd::vector mFreePoses; - size_t 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 1a04f18375..4fdcaea7f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp @@ -17,10 +17,10 @@ namespace EMotionFX // constructor AnimGraphRefCountedDataPool::AnimGraphRefCountedDataPool() { - mItems.reserve(32); - mFreeItems.reserve(32); + m_items.reserve(32); + m_freeItems.reserve(32); Resize(16); - mMaxUsed = 0; + m_maxUsed = 0; } @@ -28,21 +28,21 @@ namespace EMotionFX AnimGraphRefCountedDataPool::~AnimGraphRefCountedDataPool() { // delete all items - for (AnimGraphRefCountedData*& item : mItems) + for (AnimGraphRefCountedData*& item : m_items) { 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(size_t numItems) { - const size_t numOldItems = mItems.size(); + const size_t numOldItems = m_items.size(); // if we will remove Items if (numItems < numOldItems) @@ -51,10 +51,10 @@ namespace EMotionFX const size_t numToRemove = numOldItems - numItems; for (size_t i = 0; i < numToRemove; ++i) { - AnimGraphRefCountedData* item = mItems.back(); - MCORE_ASSERT(AZStd::find(begin(mFreeItems), end(mFreeItems), item) != end(mFreeItems)); // 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.erase(mItems.end() - 1); + m_items.erase(m_items.end() - 1); } } else // we want to add new Items @@ -63,8 +63,8 @@ namespace EMotionFX for (size_t i = 0; i < numToAdd; ++i) { AnimGraphRefCountedData* newItem = new AnimGraphRefCountedData(); - mItems.emplace_back(newItem); - mFreeItems.emplace_back(newItem); + m_items.emplace_back(newItem); + m_freeItems.emplace_back(newItem); } } } @@ -74,18 +74,18 @@ namespace EMotionFX AnimGraphRefCountedData* AnimGraphRefCountedDataPool::RequestNew() { // if we have no free items left, allocate a new one - if (mFreeItems.empty()) + if (m_freeItems.empty()) { AnimGraphRefCountedData* newItem = new AnimGraphRefCountedData(); - mItems.emplace_back(newItem); - mMaxUsed = AZStd::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.size() - 1]; - mFreeItems.pop_back(); // remove it from the list of free Items - mMaxUsed = AZStd::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; } @@ -93,7 +93,7 @@ namespace EMotionFX // free the item again void AnimGraphRefCountedDataPool::Free(AnimGraphRefCountedData* item) { - MCORE_ASSERT(AZStd::find(begin(mItems), end(mItems), item) != end(mItems)); - mFreeItems.emplace_back(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 d05ea5b5a1..3a7c38ed00 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h @@ -34,15 +34,15 @@ namespace EMotionFX AnimGraphRefCountedData* RequestNew(); void Free(AnimGraphRefCountedData* item); - MCORE_INLINE size_t GetNumFreeItems() const { return mFreeItems.size(); } - MCORE_INLINE size_t GetNumItems() const { return mItems.size(); } - MCORE_INLINE size_t GetNumUsedItems() const { return mItems.size() - mFreeItems.size(); } - MCORE_INLINE size_t 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: - AZStd::vector mItems; - AZStd::vector mFreeItems; - size_t 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 a1f9af2935..605810c5cc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp @@ -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 @@ -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(); @@ -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/AnimGraphSnapshot.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp index 089f5a7df8..b0a7134043 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp @@ -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 3ad6ae8b8b..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(InvalidIndex) + , 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); } } @@ -205,7 +205,7 @@ namespace EMotionFX const bool isTransitioning = IsTransitioning(animGraphInstance); AnimGraphStateTransition* latestActiveTransition = GetLatestActiveTransition(uniqueData); - for (AnimGraphStateTransition* curTransition : mTransitions) + for (AnimGraphStateTransition* curTransition : m_transitions) { if (curTransition->GetIsDisabled()) { @@ -321,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()) @@ -369,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); } @@ -431,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. @@ -439,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)) @@ -479,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. @@ -507,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. @@ -519,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) { @@ -545,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)) { @@ -612,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) @@ -644,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. @@ -728,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(); } @@ -814,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 @@ -843,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()) @@ -875,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()) @@ -896,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); } @@ -910,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); } @@ -925,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; @@ -933,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()) @@ -949,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() @@ -960,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 != InvalidIndex && 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 { @@ -999,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); } @@ -1029,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) { @@ -1060,7 +1060,7 @@ namespace EMotionFX { ResetUniqueData(animGraphInstance); - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveResetUniqueDatas(animGraphInstance); } @@ -1070,7 +1070,7 @@ namespace EMotionFX { AnimGraphNode::RecursiveInvalidateUniqueDatas(animGraphInstance); - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { transition->RecursiveInvalidateUniqueDatas(animGraphInstance); } @@ -1081,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) == InvalidIndex) + if (m_currentState && stateMachine->FindChildNodeIndex(m_currentState) == InvalidIndex) { - mCurrentState = nullptr; + m_currentState = nullptr; } - if (mPreviousState && stateMachine->FindChildNodeIndex(mPreviousState) == InvalidIndex) + 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. @@ -1125,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. @@ -1158,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); @@ -1209,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() || @@ -1223,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) { @@ -1236,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) { @@ -1265,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,7 +1277,7 @@ namespace EMotionFX 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 } @@ -1348,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. @@ -1374,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); @@ -1420,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 @@ -1438,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; } @@ -1454,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; } @@ -1463,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); @@ -1478,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)); } @@ -1503,7 +1503,7 @@ namespace EMotionFX void AnimGraphStateMachine::ReserveTransitions(size_t numTransitions) { - mTransitions.reserve(numTransitions); + m_transitions.reserve(numTransitions); } void AnimGraphStateMachine::SetEntryStateId(AnimGraphNodeId entryStateId) @@ -1555,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 1f8d1eb591..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. @@ -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. */ - size_t 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 747188ead2..e90491b696 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp @@ -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() || @@ -665,7 +665,7 @@ namespace EMotionFX // add all sub objects void AnimGraphStateTransition::RecursiveCollectObjects(AZStd::vector& outObjects) const { - for (const AnimGraphTransitionCondition* condition : mConditions) + for (const AnimGraphTransitionCondition* condition : m_conditions) { condition->RecursiveCollectObjects(outObjects); } @@ -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 c9347111bb..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 @@ -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 c6ccf038dd..3c77beaa60 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp @@ -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/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 809a5d1c31..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); 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 ffbf38c48a..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 = InvalidIndex; + 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 d8ca76aaa8..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(); - size_t mNodeIndex = InvalidIndex; - 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 f16d2f6943..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 size_t 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp index 78fbd91dd1..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 size_t 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 size_t 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp index dfa7be26f8..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 size_t 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp index 2876605b0a..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.empty()) + 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 217e2a2e23..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 97d7d4baa0..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); @@ -274,12 +274,12 @@ namespace EMotionFX 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,7 +406,7 @@ 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; @@ -419,7 +419,7 @@ namespace EMotionFX 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. @@ -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(); } @@ -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(); @@ -928,7 +928,7 @@ namespace EMotionFX 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) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp index fd04a43251..b836188757 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp @@ -33,7 +33,7 @@ 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 = InvalidIndex; @@ -41,7 +41,7 @@ namespace EMotionFX 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); @@ -110,7 +110,7 @@ namespace EMotionFX } // 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(); @@ -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/BlendTreeLookAtNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.cpp index f904f35ba4..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 = InvalidIndex; + 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 size_t 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 @@ -208,8 +208,8 @@ namespace EMotionFX AZ::Quaternion bindRotationLocal; 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 4da3855dd1..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; - size_t mNodeIndex = InvalidIndex; - 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 88da8346d0..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(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 (size_t 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 (size_t 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,11 +135,11 @@ 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 nodeIndex : uniqueData->mMasks[i]) + for (size_t nodeIndex : uniqueData->m_masks[i]) { outputLocalPose.SetLocalSpaceTransform(nodeIndex, localPose.GetLocalSpaceTransform(nodeIndex)); } @@ -153,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); } } @@ -182,7 +182,7 @@ namespace EMotionFX void BlendTreeMaskLegacyNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // post update all incoming nodes - for (size_t 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); @@ -202,7 +202,7 @@ namespace EMotionFX data->ClearEventBuffer(); data->ZeroTrajectoryDelta(); - for (size_t 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); @@ -212,11 +212,11 @@ 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 nodeIndex : uniqueData->mMasks[i]) + for (size_t nodeIndex : uniqueData->m_masks[i]) { if (nodeIndex == animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex()) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.h index 0cddd9610a..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 d43ac3b033..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); size_t maskInstanceIndex = 0; m_motionExtractionInputPortNr.reset(); - const size_t 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(); @@ -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; @@ -192,7 +192,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputAnimGraphPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputAnimGraphPose->GetPose(), m_visualizeColor); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp index 04199c18ca..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(); @@ -173,11 +173,11 @@ namespace EMotionFX // 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 ad88909e29..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() @@ -146,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(); @@ -162,10 +162,10 @@ namespace EMotionFX } // Try to modify the morph target weight with the value we specified as input. - if (!mDisabled && uniqueData->m_morphTargetIndex != InvalidIndex) + 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); @@ -178,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/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 f62d569a16..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)) @@ -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/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 1f15333561..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,7 +99,7 @@ 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; } @@ -107,7 +107,7 @@ namespace EMotionFX // If both x and y inputs have connections AZ::Quaternion x = m_defaultValue; AZ::Quaternion y = x; - if (mConnections.size() == 2) + if (m_connections.size() == 2) { x = GetInputQuaternion(animGraphInstance, INPUTPORT_X)->GetValue(); @@ -116,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(); } } @@ -138,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 0817b95614..87bd31d942 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp @@ -32,10 +32,10 @@ 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 = InvalidIndex; @@ -112,7 +112,7 @@ namespace EMotionFX 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); @@ -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/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 07f3256a35..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 = InvalidIndex; + 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 1d337fa6a1..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: - size_t mNodeIndex = InvalidIndex; + 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 1054cef095..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 = InvalidIndex; - mNodeIndexB = InvalidIndex; - mNodeIndexC = InvalidIndex; - mAlignNodeIndex = InvalidIndex; - mBendDirNodeIndex = InvalidIndex; - mEndEffectorNodeIndex = InvalidIndex; + 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 == InvalidIndex) + m_nodeIndexB = jointC->GetParentIndex(); + if (m_nodeIndexB == InvalidIndex) { return; } // Get the third joint. - mNodeIndexA = skeleton->GetNode(mNodeIndexB)->GetParentIndex(); - if (mNodeIndexA == InvalidIndex) + 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,12 +260,12 @@ namespace EMotionFX } // get the node indices - const size_t nodeIndexA = uniqueData->mNodeIndexA; - const size_t nodeIndexB = uniqueData->mNodeIndexB; - const size_t nodeIndexC = uniqueData->mNodeIndexC; - const size_t bendDirIndex = uniqueData->mBendDirNodeIndex; - size_t alignNodeIndex = uniqueData->mAlignNodeIndex; - size_t 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 == InvalidIndex) @@ -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()) @@ -327,7 +327,7 @@ namespace EMotionFX } 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()) @@ -352,11 +352,11 @@ namespace EMotionFX { 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 @@ -393,7 +393,7 @@ namespace EMotionFX { 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 807eb4044e..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: - size_t mNodeIndexA = InvalidIndex; - size_t mNodeIndexB = InvalidIndex; - size_t mNodeIndexC = InvalidIndex; - size_t mEndEffectorNodeIndex = InvalidIndex; - size_t mAlignNodeIndex = InvalidIndex; - size_t mBendDirNodeIndex = InvalidIndex; + 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 8f1346f543..0fd06000de 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp @@ -117,8 +117,8 @@ namespace EMotionFX 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 c107ae88f7..2d5d8e2a46 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp @@ -38,7 +38,7 @@ namespace EMotionFX 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); } @@ -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 size_t 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; } @@ -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 @@ -333,8 +333,8 @@ namespace EMotionFX { // 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 154885ea7d..434f2920ee 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h @@ -104,7 +104,7 @@ namespace EMotionFX * @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 size_t GetLocalBone(size_t 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. @@ -119,11 +119,11 @@ namespace EMotionFX */ struct EMFX_API BoneInfo { - size_t 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(InvalidIndex) {} + : m_nodeNr(InvalidIndex) {} }; AZStd::vector m_bones; /**< The array of bone information used for pre-calculation. */ @@ -153,7 +153,7 @@ 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(size_t nodeIndex) const; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp index d58b4286b9..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()); @@ -111,20 +111,20 @@ namespace EMotionFX 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; @@ -143,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.size(); ++i) + for (uint32 i = 0; i < m_threadDatas.size(); ++i) { - mThreadDatas[i]->Destroy(); + m_threadDatas[i]->Destroy(); } - mThreadDatas.clear(); + m_threadDatas.clear(); } @@ -193,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()); } } @@ -217,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"); @@ -234,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(); } @@ -323,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); } @@ -345,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 { @@ -370,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 { @@ -396,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); } @@ -456,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); } @@ -476,23 +475,23 @@ namespace EMotionFX numThreads = 1; } - if (mThreadDatas.size() == numThreads) + if (m_threadDatas.size() == numThreads) { return; } // get rid of old data - for (uint32 i = 0; i < mThreadDatas.size(); ++i) + for (uint32 i = 0; i < m_threadDatas.size(); ++i) { - mThreadDatas[i]->Destroy(); + m_threadDatas[i]->Destroy(); } - mThreadDatas.clear(); // 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); } } @@ -501,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 45bf59c94c..d5c5247de6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.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.size()); 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 size_t GetNumThreads() const { return mThreadDatas.size(); } + 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. */ - AZStd::vector 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 c0b7696205..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. @@ -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 cf47eff346..356ffe05ae 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.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 402c70c8a1..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") @@ -110,13 +110,13 @@ namespace EMotionFX // (not aligned) 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 + 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) @@ -126,8 +126,8 @@ namespace EMotionFX // (aligned) struct Actor_UV { - float mU; - float mV; + float m_u; + float m_v; }; //------------------------------------------------------- @@ -136,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 }; @@ -151,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 ] }; @@ -167,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 ] }; @@ -179,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 }; @@ -191,30 +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_Nodes2 { - uint32 mNumNodes; - uint32 mNumRootNodes; - // 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) }; @@ -222,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 604dfb8bb9..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,13 +271,13 @@ 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, AZStd::vector* sharedData, MCore::Endian::EEndianType endianType) @@ -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,34 +328,34 @@ 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; } //================================================================================================= 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(); @@ -370,44 +364,44 @@ namespace EMotionFX file->Read(&nodesHeader, sizeof(FileFormat::Actor_Nodes2)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&nodesHeader.mNumNodes, endianType); - MCore::Endian::ConvertUnsignedInt32(&nodesHeader.mNumRootNodes, endianType); + 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_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::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 @@ -418,15 +412,15 @@ 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); @@ -435,41 +429,41 @@ namespace EMotionFX // 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); } } @@ -505,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); @@ -582,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); @@ -600,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)); @@ -673,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); @@ -683,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()) { @@ -693,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); } @@ -713,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 @@ -722,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()) { @@ -732,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; } @@ -747,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 @@ -756,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()) { @@ -766,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; } @@ -783,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)); @@ -807,7 +801,7 @@ namespace EMotionFX if (resultPhysicsSetup) { - if (importParams.mActorSettings->mOptimizeForServer) + if (importParams.m_actorSettings->m_optimizeForServer) { resultPhysicsSetup->OptimizeForServer(); } @@ -821,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)); @@ -854,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()) { @@ -880,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); @@ -890,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; AZStd::vector typeStrings; AZStd::vector paramStrings; AZStd::vector mirrorTypeStrings; - for (uint32 t = 0; t < fileEventTable.mNumTracks; ++t) + 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()) @@ -944,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()); @@ -958,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()); @@ -971,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()); @@ -982,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 @@ -991,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) ); } @@ -1032,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); @@ -1071,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; @@ -1122,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); @@ -1132,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()) { @@ -1143,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()) { @@ -1157,20 +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); - if (fileInformation.mMotionExtractionNodeIndex != MCORE_INVALIDINDEX32) + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); + if (fileInformation.m_motionExtractionNodeIndex != MCORE_INVALIDINDEX32) { - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); } - // actor->SetRetargetOffset( fileInformation.mRetargetRootOffset ); - actor->SetUnitType(static_cast(fileInformation.mUnitType)); + actor->SetUnitType(static_cast(fileInformation.m_unitType)); actor->SetFileUnitType(actor->GetUnitType()); return true; @@ -1180,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()) { @@ -1198,32 +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); } - if (fileInformation.mMotionExtractionNodeIndex != MCORE_INVALIDINDEX32) + if (fileInformation.m_motionExtractionNodeIndex != MCORE_INVALIDINDEX32) { - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); } - if (fileInformation.mRetargetRootNodeIndex != MCORE_INVALIDINDEX32) + if (fileInformation.m_retargetRootNodeIndex != MCORE_INVALIDINDEX32) { - actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); + actor->SetRetargetRootNodeIndex(fileInformation.m_retargetRootNodeIndex); } - actor->SetUnitType(static_cast(fileInformation.mUnitType)); + actor->SetUnitType(static_cast(fileInformation.m_unitType)); actor->SetFileUnitType(actor->GetUnitType()); return true; @@ -1233,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()) { @@ -1251,34 +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); } - if (fileInformation.mMotionExtractionNodeIndex != MCORE_INVALIDINDEX32) + if (fileInformation.m_motionExtractionNodeIndex != MCORE_INVALIDINDEX32) { - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); } - if (fileInformation.mRetargetRootNodeIndex != MCORE_INVALIDINDEX32) + if (fileInformation.m_retargetRootNodeIndex != MCORE_INVALIDINDEX32) { - actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); + actor->SetRetargetRootNodeIndex(fileInformation.m_retargetRootNodeIndex); } - actor->SetUnitType(static_cast(fileInformation.mUnitType)); + 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; } @@ -1288,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(); @@ -1299,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 @@ -1336,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()), @@ -1408,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); @@ -1429,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); @@ -1465,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 @@ -1478,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 @@ -1539,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(); @@ -1550,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()), @@ -1686,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(); @@ -1697,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()), @@ -1834,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); @@ -1846,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; @@ -1864,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 @@ -1872,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 @@ -1880,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 @@ -1889,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); } } } @@ -1904,8 +1897,8 @@ 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; MCORE_ASSERT(actor); Skeleton* skeleton = actor->GetSkeleton(); @@ -1915,8 +1908,8 @@ 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 (uint32 i = 0; i < numAttachmentNodes; ++i) @@ -1963,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()) { @@ -1999,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()); } } @@ -2019,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()); @@ -2035,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 66a2193b71..4dc6d11acb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h @@ -97,11 +97,11 @@ namespace EMotionFX 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp index e2cc633012..762fd29dcb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp @@ -51,8 +51,8 @@ namespace EMotionFX RegisterStandardChunks(); // init some default values - mLoggingActive = true; - mLogDetails = false; + m_loggingActive = true; + m_logDetails = false; } @@ -60,7 +60,7 @@ namespace EMotionFX Importer::~Importer() { // remove all chunk processors - for (ChunkProcessor* chunkProcessor : mChunkProcessors) + for (ChunkProcessor* chunkProcessor : m_chunkProcessors) { chunkProcessor->Destroy(); } @@ -88,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; @@ -103,7 +103,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; } @@ -127,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; @@ -142,7 +142,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; } @@ -164,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; @@ -179,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; } @@ -305,7 +305,7 @@ namespace EMotionFX actorSettings = *settings; } - if (actorSettings.mOptimizeForServer) + if (actorSettings.m_optimizeForServer) { actorSettings.OptimizeForServer(); } @@ -319,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)) @@ -339,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, actorSettings.mUnitTypeConvert); + actor->PostCreateInit(actorSettings.m_makeGeomLoDsCompatibleWithSkeletalLoDs, actorSettings.m_unitTypeConvert); } // close the file and return a pointer to the actor we loaded @@ -367,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()); @@ -481,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)) @@ -495,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()); } @@ -671,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(); @@ -679,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)) @@ -713,7 +713,7 @@ namespace EMotionFX void Importer::RegisterChunkProcessor(ChunkProcessor* processorToRegister) { MCORE_ASSERT(processorToRegister); - mChunkProcessors.emplace_back(processorToRegister); + m_chunkProcessors.emplace_back(processorToRegister); } @@ -739,31 +739,31 @@ namespace EMotionFX 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 - for (ChunkProcessor* processor : mChunkProcessors) + for (ChunkProcessor* processor : m_chunkProcessors) { - 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; } @@ -790,11 +790,11 @@ namespace EMotionFX ChunkProcessor* Importer::FindChunk(uint32 chunkID, uint32 version) const { // for all chunk processors - const auto foundProcessor = AZStd::find_if(begin(mChunkProcessors), end(mChunkProcessors), [chunkID, version](const ChunkProcessor* processor) + const auto foundProcessor = AZStd::find_if(begin(m_chunkProcessors), end(m_chunkProcessors), [chunkID, version](const ChunkProcessor* processor) { return processor->GetChunkID() == chunkID && processor->GetVersion() == version; }); - return foundProcessor != end(mChunkProcessors) ? *foundProcessor : nullptr; + return foundProcessor != end(m_chunkProcessors) ? *foundProcessor : nullptr; } @@ -802,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()); @@ -853,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 && AZStd::find(begin(actorSettings->mChunkIDsToIgnore), end(actorSettings->mChunkIDsToIgnore), chunk.mChunkID) != end(actorSettings->mChunkIDsToIgnore)) + if (actorSettings && AZStd::find(begin(actorSettings->m_chunkIDsToIgnore), end(actorSettings->m_chunkIDsToIgnore), chunk.m_chunkId) != end(actorSettings->m_chunkIDsToIgnore)) { mustSkip = true; } - if (skelMotionSettings && AZStd::find(begin(skelMotionSettings->mChunkIDsToIgnore), end(skelMotionSettings->mChunkIDsToIgnore), chunk.mChunkID) != end(skelMotionSettings->mChunkIDsToIgnore)) + if (skelMotionSettings && AZStd::find(begin(skelMotionSettings->m_chunkIDsToIgnore), end(skelMotionSettings->m_chunkIDsToIgnore), chunk.m_chunkId) != end(skelMotionSettings->m_chunkIDsToIgnore)) { mustSkip = true; } @@ -897,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; } @@ -909,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; } @@ -919,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; } @@ -932,28 +932,28 @@ namespace EMotionFX void Importer::ValidateActorSettings(ActorSettings* settings) { // After atom: Make sure we are not loading the tangents and bitangents - if (AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_TANGENTS) == end(settings->mLayerIDsToIgnore)) + if (AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_TANGENTS) == end(settings->m_layerIDsToIgnore)) { - settings->mLayerIDsToIgnore.emplace_back(Mesh::ATTRIB_TANGENTS); + settings->m_layerIDsToIgnore.emplace_back(Mesh::ATTRIB_TANGENTS); } - if (AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_BITANGENTS) == end(settings->mLayerIDsToIgnore)) + if (AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_BITANGENTS) == end(settings->m_layerIDsToIgnore)) { - settings->mLayerIDsToIgnore.emplace_back(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 - if(const auto it = AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_ORGVTXNUMBERS); it != end(settings->mLayerIDsToIgnore)) + if(const auto it = AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_ORGVTXNUMBERS); it != end(settings->m_layerIDsToIgnore)) { - settings->mLayerIDsToIgnore.erase(it); + settings->m_layerIDsToIgnore.erase(it); } - if(const auto it = AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_NORMALS); it != end(settings->mLayerIDsToIgnore)) + if(const auto it = AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_NORMALS); it != end(settings->m_layerIDsToIgnore)) { - settings->mLayerIDsToIgnore.erase(it); + settings->m_layerIDsToIgnore.erase(it); } - if(const auto it = AZStd::find(begin(settings->mLayerIDsToIgnore), end(settings->mLayerIDsToIgnore), Mesh::ATTRIB_POSITIONS); it != end(settings->mLayerIDsToIgnore)) + if(const auto it = AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_POSITIONS); it != end(settings->m_layerIDsToIgnore)) { - settings->mLayerIDsToIgnore.erase(it); + settings->m_layerIDsToIgnore.erase(it); } } @@ -1095,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; @@ -1104,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; } @@ -1128,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; @@ -1137,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 a708e7f017..1a9fdf3654 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h @@ -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; - AZStd::vector mChunkIDsToIgnore; /**< Add chunk ID's to this array. Chunks with these ID's will not be processed. */ - AZStd::vector 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. */ - AZStd::vector 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; - AZStd::vector* 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; }; //------------------------------------------------------------------------------------------------- @@ -355,9 +355,9 @@ namespace EMotionFX private: - AZStd::vector 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. 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/KeyTrackLinearDynamic.h b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h index 5f8f7b49d0..c94886a5f3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h @@ -257,7 +257,7 @@ namespace EMotionFX 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 806a45b69a..34598f0ae1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl @@ -25,7 +25,7 @@ void KeyTrackLinearDynamic::Reflect(AZ::ReflectContext* serializeContext->Class>() ->Version(1) - ->Field("keyValues", &KeyTrackLinearDynamic::mKeys) + ->Field("keyValues", &KeyTrackLinearDynamic::m_keys) ; } @@ -33,7 +33,7 @@ void KeyTrackLinearDynamic::Reflect(AZ::ReflectContext* template void KeyTrackLinearDynamic::ClearKeys() { - mKeys.clear(); + m_keys.clear(); } @@ -42,18 +42,18 @@ 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) { - for (KeyFrame& key : mKeys) + for (KeyFrame& key : m_keys) { key.SetTime(key.GetTime() - minTime); } @@ -64,22 +64,22 @@ void KeyTrackLinearDynamic::Init() template 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.empty() ? &mKeys[0] : nullptr; + return !m_keys.empty() ? &m_keys[0] : nullptr; } template MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::GetLastKey() { - return !mKeys.empty() ? &mKeys.back() : nullptr; + return !m_keys.empty() ? &m_keys.back() : nullptr; } @@ -87,22 +87,22 @@ MCORE_INLINE KeyFrame* KeyTrackLinearDynamic 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.empty() ? &mKeys[0] : nullptr; + return !m_keys.empty() ? &m_keys[0] : nullptr; } template MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic::GetLastKey() const { - return !mKeys.empty() ? &mKeys.back() : nullptr; + return !m_keys.empty() ? &m_keys.back() : nullptr; } @@ -125,7 +125,7 @@ MCORE_INLINE float KeyTrackLinearDynamic::GetLastTime() template MCORE_INLINE size_t KeyTrackLinearDynamic::GetNumKeys() const { - return mKeys.size(); + return m_keys.size(); } @@ -133,21 +133,21 @@ template MCORE_INLINE void KeyTrackLinearDynamic::AddKey(float time, const ReturnType& value, bool smartPreAlloc) { #ifdef MCORE_DEBUG - if (!mKeys.empty()) + 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)); } @@ -155,7 +155,7 @@ MCORE_INLINE void KeyTrackLinearDynamic::AddKey(float t template 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())); } @@ -164,10 +164,10 @@ template MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::FindKey(float curTime) const { // find the key number - const size_t 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 != InvalidIndex) ? &mKeys[keyNumber] : nullptr; + return (keyNumber != InvalidIndex) ? &m_keys[keyNumber] : nullptr; } @@ -176,7 +176,7 @@ template ReturnType KeyTrackLinearDynamic::GetValueAtTime(float currentTime, size_t* cachedKey, uint8* outWasCacheHit, bool interpolate) const { MCORE_ASSERT(currentTime >= 0.0); - MCORE_ASSERT(!mKeys.empty()); + MCORE_ASSERT(!m_keys.empty()); // make a local copy of the cached key value size_t localCachedKey = (cachedKey) ? *cachedKey : InvalidIndex; @@ -193,7 +193,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float *outWasCacheHit = 0; } - keyNumber = KeyFrameFinder::FindKey(currentTime, &mKeys.front(), mKeys.size()); + keyNumber = KeyFrameFinder::FindKey(currentTime, &m_keys.front(), m_keys.size()); if (cachedKey) { @@ -203,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 = mKeys.size() - 3; + localCachedKey = m_keys.size() - 3; } else { @@ -216,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) @@ -226,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) { @@ -242,7 +242,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float *outWasCacheHit = 0; } - keyNumber = KeyFrameFinder::FindKey(currentTime, &mKeys.front(), mKeys.size()); + keyNumber = KeyFrameFinder::FindKey(currentTime, &m_keys.front(), m_keys.size()); if (cachedKey) { @@ -256,20 +256,20 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float 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 @@ -279,7 +279,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float } else { - return mKeys[keyNumber].GetValue(); + return m_keys[keyNumber].GetValue(); } } @@ -289,8 +289,8 @@ template 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()); @@ -305,8 +305,8 @@ template <> 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()); @@ -320,8 +320,8 @@ template <> 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()); @@ -338,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 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); } } // 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; } @@ -356,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 size_t place = KeyFrameFinder::FindKey(keyTime, &mKeys.front(), 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(size_t keyNr) { - mKeys.erase(AZStd::next(mKeys.begin(), keyNr)); + m_keys.erase(AZStd::next(m_keys.begin(), keyNr)); } @@ -387,7 +387,7 @@ void KeyTrackLinearDynamic::MakeLoopable(float fadeTime { MCORE_ASSERT(fadeTime > 0); - if (mKeys.empty()) + if (m_keys.empty()) { return; } @@ -407,14 +407,14 @@ 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 @@ -423,7 +423,7 @@ size_t KeyTrackLinearDynamic::Optimize(float maxError) 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); @@ -445,13 +445,12 @@ size_t 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; } @@ -461,7 +460,7 @@ template void KeyTrackLinearDynamic::SetNumKeys(size_t numKeys) { // resize the array of keys - mKeys.resize(numKeys); + m_keys.resize(numKeys); } @@ -470,8 +469,8 @@ template 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); } @@ -480,8 +479,8 @@ template 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); } @@ -489,7 +488,7 @@ MCORE_INLINE void KeyTrackLinearDynamic::SetStorageType template MCORE_INLINE bool KeyTrackLinearDynamic::CheckIfIsAnimated(const ReturnType& initialPose, float maxError) const { - return !mKeys.empty() && AZStd::any_of(begin(mKeys), end(mKeys), [&initialPose, maxError](const auto& key) + return !m_keys.empty() && AZStd::any_of(begin(m_keys), end(m_keys), [&initialPose, maxError](const auto& key) { return !MCore::Compare::CheckIfIsClose(initialPose, key.GetValue(), maxError); }); @@ -501,7 +500,7 @@ MCORE_INLINE bool KeyTrackLinearDynamic::CheckIfIsAnima template MCORE_INLINE void KeyTrackLinearDynamic::Reserve(size_t numKeys) { - mKeys.reserve(numKeys); + m_keys.reserve(numKeys); } @@ -517,5 +516,5 @@ size_t KeyTrackLinearDynamic::CalcMemoryUsage([[maybe_u 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 450a546c27..9845ec1939 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -29,25 +29,25 @@ namespace EMotionFX Mesh::Mesh() : BaseObject() { - mNumVertices = 0; - mNumIndices = 0; - mNumOrgVerts = 0; - mNumPolygons = 0; - mIndices = nullptr; - mPolyVertexCounts = nullptr; - mIsCollisionMesh = false; + 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; + 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); @@ -73,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) @@ -98,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. @@ -192,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. @@ -359,22 +359,22 @@ 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() { - for (VertexAttributeLayer* vertexAttribute : mVertexAttributes) + for (VertexAttributeLayer* vertexAttribute : m_vertexAttributes) { vertexAttribute->ResetToOriginalData(); } @@ -391,29 +391,29 @@ namespace EMotionFX RemoveAllVertexAttributeLayers(); // get rid of all sub meshes - for (SubMesh* subMesh : mSubMeshes) + for (SubMesh* subMesh : m_subMeshes) { 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; } @@ -503,14 +503,14 @@ namespace EMotionFX 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)); } @@ -518,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; @@ -545,7 +545,7 @@ namespace EMotionFX AZ::Vector3 curBitangent; // calculate for every vertex the tangent and bitangent - for (uint32 i = 0; i < mNumVertices; ++i) + for (uint32 i = 0; i < m_numVertices; ++i) { orgTangents[i] = AZ::Vector4::CreateZero(); tangents[i] = AZ::Vector4::CreateZero(); @@ -601,7 +601,7 @@ namespace EMotionFX } // calculate the per vertex tangents now, fixing up orthogonality and handling mirroring of the bitangent - for (uint32 i = 0; i < mNumVertices; ++i) + for (uint32 i = 0; i < m_numVertices; ++i) { // get the normal AZ::Vector3 normal(normals[i]); @@ -800,8 +800,8 @@ namespace EMotionFX // remove a given submesh void Mesh::RemoveSubMesh(size_t nr, bool delFromMem) { - SubMesh* subMesh = mSubMeshes[nr]; - mSubMeshes.erase(AZStd::next(begin(mSubMeshes), nr)); + SubMesh* subMesh = m_subMeshes[nr]; + m_subMeshes.erase(AZStd::next(begin(m_subMeshes), nr)); if (delFromMem) { subMesh->Destroy(); @@ -812,7 +812,7 @@ namespace EMotionFX // insert a given submesh void Mesh::InsertSubMesh(size_t insertIndex, SubMesh* subMesh) { - mSubMeshes.emplace(AZStd::next(begin(mSubMeshes), insertIndex), subMesh); + m_subMeshes.emplace(AZStd::next(begin(m_subMeshes), insertIndex), subMesh); } @@ -822,7 +822,7 @@ namespace EMotionFX size_t numLayers = 0; // check the types of all vertex attribute layers - for (auto* vertexAttribute : mVertexAttributes) + for (auto* vertexAttribute : m_vertexAttributes) { if (vertexAttribute->GetType() == type) { @@ -844,31 +844,31 @@ namespace EMotionFX VertexAttributeLayer* Mesh::GetSharedVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mSharedVertexAttributes.size()); - return mSharedVertexAttributes[layerNr]; + MCORE_ASSERT(layerNr < m_sharedVertexAttributes.size()); + return m_sharedVertexAttributes[layerNr]; } void Mesh::AddSharedVertexAttributeLayer(VertexAttributeLayer* layer) { - MCORE_ASSERT(AZStd::find(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), layer) == end(mSharedVertexAttributes)); - mSharedVertexAttributes.emplace_back(layer); + MCORE_ASSERT(AZStd::find(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), layer) == end(m_sharedVertexAttributes)); + m_sharedVertexAttributes.emplace_back(layer); } size_t Mesh::GetNumSharedVertexAttributeLayers() const { - return mSharedVertexAttributes.size(); + return m_sharedVertexAttributes.size(); } size_t Mesh::FindSharedVertexAttributeLayerNumber(uint32 layerTypeID, size_t occurrence) const { - const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [layerTypeID, occurrence](const VertexAttributeLayer* layer) mutable + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [layerTypeID, occurrence](const VertexAttributeLayer* layer) mutable { return layer->GetType() == layerTypeID && occurrence-- == 0; }); - return foundLayer != end(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_sharedVertexAttributes) ? AZStd::distance(begin(m_sharedVertexAttributes), foundLayer) : InvalidIndex; } @@ -881,7 +881,7 @@ namespace EMotionFX return nullptr; } - return mSharedVertexAttributes[layerNr]; + return m_sharedVertexAttributes[layerNr]; } @@ -889,10 +889,10 @@ namespace EMotionFX // delete all shared attribute layers void Mesh::RemoveAllSharedVertexAttributeLayers() { - while (mSharedVertexAttributes.size()) + while (m_sharedVertexAttributes.size()) { - mSharedVertexAttributes.back()->Destroy(); - mSharedVertexAttributes.pop_back(); + m_sharedVertexAttributes.back()->Destroy(); + m_sharedVertexAttributes.pop_back(); } } @@ -900,51 +900,51 @@ namespace EMotionFX // remove a layer by its index void Mesh::RemoveSharedVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mSharedVertexAttributes.size()); - mSharedVertexAttributes[layerNr]->Destroy(); - mSharedVertexAttributes.erase(AZStd::next(begin(mSharedVertexAttributes), layerNr)); + MCORE_ASSERT(layerNr < m_sharedVertexAttributes.size()); + m_sharedVertexAttributes[layerNr]->Destroy(); + m_sharedVertexAttributes.erase(AZStd::next(begin(m_sharedVertexAttributes), layerNr)); } size_t Mesh::GetNumVertexAttributeLayers() const { - return mVertexAttributes.size(); + return m_vertexAttributes.size(); } VertexAttributeLayer* Mesh::GetVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mVertexAttributes.size()); - return mVertexAttributes[layerNr]; + MCORE_ASSERT(layerNr < m_vertexAttributes.size()); + return m_vertexAttributes[layerNr]; } void Mesh::AddVertexAttributeLayer(VertexAttributeLayer* layer) { - MCORE_ASSERT(AZStd::find(begin(mVertexAttributes), end(mVertexAttributes), layer) == end(mVertexAttributes)); - mVertexAttributes.emplace_back(layer); + MCORE_ASSERT(AZStd::find(begin(m_vertexAttributes), end(m_vertexAttributes), layer) == end(m_vertexAttributes)); + m_vertexAttributes.emplace_back(layer); } // find the layer number size_t Mesh::FindVertexAttributeLayerNumber(uint32 layerTypeID, size_t occurrence) const { - const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [layerTypeID, occurrence](const VertexAttributeLayer* layer) mutable + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [layerTypeID, occurrence](const VertexAttributeLayer* layer) mutable { return layer->GetType() == layerTypeID && occurrence-- == 0; }); - return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find the layer number size_t Mesh::FindVertexAttributeLayerNumberByName(uint32 layerTypeID, const char* name) const { - const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [layerTypeID, name](const VertexAttributeLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [layerTypeID, name](const VertexAttributeLayer* layer) { return layer->GetType() == layerTypeID && layer->GetNameString() == name; }); - return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } @@ -958,7 +958,7 @@ namespace EMotionFX return nullptr; } - return mVertexAttributes[layerNr]; + return m_vertexAttributes[layerNr]; } @@ -971,25 +971,25 @@ namespace EMotionFX return nullptr; } - return mVertexAttributes[layerNr]; + return m_vertexAttributes[layerNr]; } void Mesh::RemoveAllVertexAttributeLayers() { - while (mVertexAttributes.size()) + while (m_vertexAttributes.size()) { - mVertexAttributes.back()->Destroy(); - mVertexAttributes.pop_back(); + m_vertexAttributes.back()->Destroy(); + m_vertexAttributes.pop_back(); } } void Mesh::RemoveVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mVertexAttributes.size()); - mVertexAttributes[layerNr]->Destroy(); - mVertexAttributes.erase(AZStd::next(begin(mVertexAttributes), layerNr)); + MCORE_ASSERT(layerNr < m_vertexAttributes.size()); + m_vertexAttributes[layerNr]->Destroy(); + m_vertexAttributes.erase(AZStd::next(begin(m_vertexAttributes), layerNr)); } @@ -998,34 +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 - const size_t numSubMeshes = mSubMeshes.size(); - clone->mSubMeshes.resize(numSubMeshes); + 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 size_t numSharedAttributes = mSharedVertexAttributes.size(); - clone->mSharedVertexAttributes.resize(numSharedAttributes); + 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 size_t numAttributes = mVertexAttributes.size(); - clone->mVertexAttributes.resize(numAttributes); + 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 @@ -1036,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) @@ -1046,10 +1046,10 @@ namespace EMotionFX } // swap all vertex attribute layers - const size_t numLayers = mVertexAttributes.size(); + 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); } } @@ -1057,8 +1057,8 @@ namespace EMotionFX 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) @@ -1074,7 +1074,7 @@ 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 size_t numLayers = GetNumVertexAttributeLayers(); @@ -1091,9 +1091,9 @@ namespace EMotionFX for (uint32 w = 0; w < numVertsToRemove; ++w) { // adjust all submesh start index offsets changed - for (size_t s = 0; s < mSubMeshes.size();) + 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) @@ -1111,7 +1111,7 @@ namespace EMotionFX // remove the submesh if it's empty if (subMesh->GetNumVertices() == 0 && removeEmptySubMeshes) { - mSubMeshes.erase(AZStd::next(begin(mSubMeshes), s)); + m_subMeshes.erase(AZStd::next(begin(m_subMeshes), s)); } else { @@ -1128,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; } } } @@ -1145,9 +1145,9 @@ namespace EMotionFX size_t numRemoved = 0; // for all the submeshes - for (size_t i = 0; i < mSubMeshes.size();) + 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; @@ -1167,7 +1167,7 @@ namespace EMotionFX // remove or skip if (mustRemove) { - mSubMeshes.erase(AZStd::next(begin(mSubMeshes), i)); + m_subMeshes.erase(AZStd::next(begin(m_subMeshes), i)); numRemoved++; } else @@ -1542,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) @@ -1570,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; } @@ -1610,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]; } @@ -1640,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(); } @@ -1681,39 +1681,20 @@ namespace EMotionFX polyStartIndex += numPolyVerts; } - /* - for (uint32 f=0; fScale(scaleFactor); } - for (VertexAttributeLayer* layer : mSharedVertexAttributes) + for (VertexAttributeLayer* layer : m_sharedVertexAttributes) { layer->Scale(scaleFactor); } @@ -1847,7 +1808,7 @@ namespace EMotionFX 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; @@ -1859,65 +1820,65 @@ namespace EMotionFX // find by name size_t Mesh::FindVertexAttributeLayerIndexByName(const char* name) const { - const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [name](const VertexAttributeLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [name](const VertexAttributeLayer* layer) { return layer->GetNameString() == name; }); - return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find by name as string size_t Mesh::FindVertexAttributeLayerIndexByNameString(const AZStd::string& name) const { - const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [name](const VertexAttributeLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [name](const VertexAttributeLayer* layer) { return layer->GetNameString() == name; }); - return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find by name ID size_t Mesh::FindVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const auto foundLayer = AZStd::find_if(begin(mVertexAttributes), end(mVertexAttributes), [nameID](const VertexAttributeLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [nameID](const VertexAttributeLayer* layer) { return layer->GetNameID() == nameID; }); - return foundLayer != end(mVertexAttributes) ? AZStd::distance(begin(mVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find by name size_t Mesh::FindSharedVertexAttributeLayerIndexByName(const char* name) const { - const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [name](const VertexAttributeLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [name](const VertexAttributeLayer* layer) { return layer->GetNameString() == name; }); - return foundLayer != end(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_sharedVertexAttributes) ? AZStd::distance(begin(m_sharedVertexAttributes), foundLayer) : InvalidIndex; } // find by name as string size_t Mesh::FindSharedVertexAttributeLayerIndexByNameString(const AZStd::string& name) const { - const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [name](const VertexAttributeLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [name](const VertexAttributeLayer* layer) { return layer->GetNameString() == name; }); - return foundLayer != end(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), foundLayer) : InvalidIndex; + return foundLayer != end(m_sharedVertexAttributes) ? AZStd::distance(begin(m_sharedVertexAttributes), foundLayer) : InvalidIndex; } // find by name ID size_t Mesh::FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const auto foundLayer = AZStd::find_if(begin(mSharedVertexAttributes), end(mSharedVertexAttributes), [nameID](const VertexAttributeLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [nameID](const VertexAttributeLayer* layer) { return layer->GetNameID() == nameID; }); - return foundLayer != end(mSharedVertexAttributes) ? AZStd::distance(begin(mSharedVertexAttributes), foundLayer) : InvalidIndex; + 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 b38a1445f6..c2d776bcdb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -249,7 +249,7 @@ namespace EMotionFX * @param nr The submesh number, which must be in range of [0..GetNumSubMeshes()-1]. * @param subMesh The submesh to use. */ - MCORE_INLINE void SetSubMesh(size_t nr, SubMesh* subMesh) { mSubMeshes[nr] = subMesh; } + MCORE_INLINE void SetSubMesh(size_t nr, SubMesh* subMesh) { m_subMeshes[nr] = subMesh; } /** * Set the number of submeshes. @@ -257,7 +257,7 @@ namespace EMotionFX * Do not forget to use SetSubMesh() to initialize all submeshes! * @param numSubMeshes The number of submeshes to use. */ - MCORE_INLINE void SetNumSubMeshes(size_t numSubMeshes) { mSubMeshes.resize(numSubMeshes); } + MCORE_INLINE void SetNumSubMeshes(size_t numSubMeshes) { m_subMeshes.resize(numSubMeshes); } /** * Remove a given submesh from this mesh. @@ -648,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: - AZStd::vector 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(). */ - AZStd::vector< 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(). */ - AZStd::vector< 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 6a29a3de69..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 size_t Mesh::GetNumSubMeshes() const { - return mSubMeshes.size(); + return m_subMeshes.size(); } MCORE_INLINE SubMesh* Mesh::GetSubMesh(size_t nr) const { - MCORE_ASSERT(nr < mSubMeshes.size()); - return mSubMeshes[nr]; + MCORE_ASSERT(nr < m_subMeshes.size()); + return m_subMeshes[nr]; } MCORE_INLINE void Mesh::AddSubMesh(SubMesh* subMesh) { - mSubMeshes.emplace_back(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 b269fdecdd..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,14 +33,14 @@ 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; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h index e1caeaf5a9..dcb95fcd82 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h @@ -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 ee204cf298..bf7fd657ec 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp @@ -21,22 +21,22 @@ namespace EMotionFX MeshDeformerStack::MeshDeformerStack(Mesh* mesh) : BaseObject() { - mMesh = mesh; + m_mesh = mesh; } // destructor MeshDeformerStack::~MeshDeformerStack() { - for (MeshDeformer* deformer : mDeformers) + for (MeshDeformer* deformer : m_deformers) { deformer->Destroy(); } - mDeformers.clear(); + m_deformers.clear(); // reset - mMesh = nullptr; + m_mesh = nullptr; } @@ -50,7 +50,7 @@ namespace EMotionFX // returns the mesh Mesh* MeshDeformerStack::GetMesh() const { - return mMesh; + return m_mesh; } @@ -60,7 +60,7 @@ namespace EMotionFX bool firstEnabled = true; // iterate through the deformers and update them - for (MeshDeformer* deformer : mDeformers) + for (MeshDeformer* deformer : m_deformers) { // if the deformer is enabled if (deformer->GetIsEnabled() || forceUpdateDisabledDeformers) @@ -71,7 +71,7 @@ namespace EMotionFX firstEnabled = false; // reset all output vertex data to the original vertex data - mMesh->ResetToOriginalData(); + m_mesh->ResetToOriginalData(); } // update the mesh deformer @@ -84,7 +84,7 @@ namespace EMotionFX void MeshDeformerStack::UpdateByModifierType(ActorInstance* actorInstance, Node* node, float timeDelta, uint32 typeID, bool resetMesh, bool forceUpdateDisabledDeformers) { bool resetDone = false; - for (MeshDeformer* deformer : mDeformers) + for (MeshDeformer* deformer : m_deformers) { // if the deformer of the correct type and is enabled if (deformer->GetType() == typeID && (deformer->GetIsEnabled() || forceUpdateDisabledDeformers)) @@ -93,7 +93,7 @@ namespace EMotionFX if (resetMesh && !resetDone) { // reset all output vertex data to the original vertex data - mMesh->ResetToOriginalData(); + m_mesh->ResetToOriginalData(); resetDone = true; } @@ -108,12 +108,12 @@ namespace EMotionFX void MeshDeformerStack::ReinitializeDeformers(Actor* actor, Node* node, size_t lodLevel) { // if we have deformers in the stack - const size_t numDeformers = mDeformers.size(); + const size_t numDeformers = m_deformers.size(); // iterate through the deformers and reinitialize them for (size_t i = 0; i < numDeformers; ++i) { - mDeformers[i]->Reinitialize(actor, node, lodLevel); + m_deformers[i]->Reinitialize(actor, node, lodLevel); } } @@ -121,23 +121,23 @@ namespace EMotionFX void MeshDeformerStack::AddDeformer(MeshDeformer* meshDeformer) { // add the object into the stack - mDeformers.emplace_back(meshDeformer); + m_deformers.emplace_back(meshDeformer); } void MeshDeformerStack::InsertDeformer(size_t pos, MeshDeformer* meshDeformer) { // add the object into the stack - mDeformers.emplace(AZStd::next(begin(mDeformers), pos), meshDeformer); + m_deformers.emplace(AZStd::next(begin(m_deformers), pos), meshDeformer); } bool MeshDeformerStack::RemoveDeformer(MeshDeformer* meshDeformer) { // delete the object - if (const auto it = AZStd::find(begin(mDeformers), end(mDeformers), meshDeformer); it != end(mDeformers)) + if (const auto it = AZStd::find(begin(m_deformers), end(m_deformers), meshDeformer); it != end(m_deformers)) { - mDeformers.erase(it); + m_deformers.erase(it); return true; } return false; @@ -150,7 +150,7 @@ namespace EMotionFX MeshDeformerStack* newStack = aznew MeshDeformerStack(mesh); // clone all deformers - for (const MeshDeformer* deformer : mDeformers) + for (const MeshDeformer* deformer : m_deformers) { newStack->AddDeformer(deformer->Clone(mesh)); } @@ -162,14 +162,14 @@ namespace EMotionFX size_t MeshDeformerStack::GetNumDeformers() const { - return mDeformers.size(); + return m_deformers.size(); } MeshDeformer* MeshDeformerStack::GetDeformer(size_t nr) const { - MCORE_ASSERT(nr < mDeformers.size()); - return mDeformers[nr]; + MCORE_ASSERT(nr < m_deformers.size()); + return m_deformers[nr]; } @@ -177,9 +177,9 @@ namespace EMotionFX size_t MeshDeformerStack::RemoveAllDeformersByType(uint32 deformerTypeID) { size_t numRemoved = 0; - for (size_t a = 0; a < mDeformers.size(); ) + for (size_t a = 0; a < m_deformers.size(); ) { - MeshDeformer* deformer = mDeformers[a]; + MeshDeformer* deformer = m_deformers[a]; if (deformer->GetType() == deformerTypeID) { RemoveDeformer(deformer); @@ -199,7 +199,7 @@ namespace EMotionFX // remove all the deformers void MeshDeformerStack::RemoveAllDeformers() { - for (MeshDeformer* deformer : mDeformers) + for (MeshDeformer* deformer : m_deformers) { // retrieve the current deformer // remove the deformer @@ -213,7 +213,7 @@ namespace EMotionFX size_t MeshDeformerStack::EnableAllDeformersByType(uint32 deformerTypeID, bool enabled) { size_t numChanged = 0; - for (MeshDeformer* deformer : mDeformers) + for (MeshDeformer* deformer : m_deformers) { if (deformer->GetType() == deformerTypeID) { @@ -229,7 +229,7 @@ namespace EMotionFX // check if the stack contains a deformer of a specified type bool MeshDeformerStack::CheckIfHasDeformerOfType(uint32 deformerTypeID) const { - return AZStd::any_of(begin(mDeformers), end(mDeformers), [deformerTypeID](const MeshDeformer* deformer) + return AZStd::any_of(begin(m_deformers), end(m_deformers), [deformerTypeID](const MeshDeformer* deformer) { return deformer->GetType() == deformerTypeID; }); @@ -239,10 +239,10 @@ namespace EMotionFX // find a deformer by type ID MeshDeformer* MeshDeformerStack::FindDeformerByType(uint32 deformerTypeID, size_t occurrence) const { - const auto foundDeformer = AZStd::find_if(begin(mDeformers), end(mDeformers), [deformerTypeID, iter = occurrence](const MeshDeformer* deformer) mutable + const auto foundDeformer = AZStd::find_if(begin(m_deformers), end(m_deformers), [deformerTypeID, iter = occurrence](const MeshDeformer* deformer) mutable { return deformer->GetType() == deformerTypeID && iter-- == 0; }); - return foundDeformer != end(mDeformers) ? *foundDeformer : nullptr; + 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 ae63a1e495..885bc06cab 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h @@ -159,8 +159,8 @@ namespace EMotionFX MeshDeformer* FindDeformerByType(uint32 deformerTypeID, size_t occurrence = 0) const; private: - AZStd::vector 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 e3fd1552b0..8dd0c15d84 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp @@ -63,13 +63,13 @@ namespace EMotionFX MorphMeshDeformer* result = aznew MorphMeshDeformer(mesh); // copy the deform passes - result->mDeformPasses.resize(mDeformPasses.size()); - for (size_t i = 0; i < mDeformPasses.size(); ++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 @@ -88,23 +88,23 @@ namespace EMotionFX const size_t lodLevel = actorInstance->GetLODLevel(); // apply all deform passes - for (DeformPass& deformPass : mDeformPasses) + for (DeformPass& deformPass : m_deformPasses) { // find the morph target - MorphTargetStandard* morphTarget = (MorphTargetStandard*)actor->GetMorphSetup(lodLevel)->FindMorphTargetByID(deformPass.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(deformPass.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; } @@ -120,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 && deformPass.mLastNearZero) + if (nearZero && deformPass.m_lastNearZero) { continue; } @@ -128,36 +128,36 @@ namespace EMotionFX // update the flag if (nearZero) { - deformPass.mLastNearZero = true; + deformPass.m_lastNearZero = true; } else { - deformPass.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 for (uint32 v = 0; v < numDeformVerts; ++v) { - uint32 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); } } @@ -165,12 +165,12 @@ namespace EMotionFX { for (uint32 v = 0; v < numDeformVerts; ++v) { - uint32 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); } } @@ -179,10 +179,10 @@ namespace EMotionFX // process all vertices that we need to deform for (uint32 v = 0; v < numDeformVerts; ++v) { - uint32 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; } } } @@ -193,7 +193,7 @@ namespace EMotionFX 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(); + m_deformPasses.clear(); // get the morph setup MorphSetup* morphSetup = actor->GetMorphSetup(lodLevel); @@ -211,13 +211,13 @@ namespace EMotionFX { // 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.emplace_back(); - const size_t deformPassIndex = mDeformPasses.size() - 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; } } } @@ -226,18 +226,18 @@ namespace EMotionFX void MorphMeshDeformer::AddDeformPass(const DeformPass& deformPass) { - mDeformPasses.emplace_back(deformPass); + m_deformPasses.emplace_back(deformPass); } size_t MorphMeshDeformer::GetNumDeformPasses() const { - return mDeformPasses.size(); + return m_deformPasses.size(); } 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 882d4bdfeb..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. */ - size_t 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(InvalidIndex) - , mLastNearZero(false) {} + : m_morphTarget(nullptr) + , m_deformDataNr(InvalidIndex) + , m_lastNearZero(false) {} }; /** @@ -132,7 +132,7 @@ namespace EMotionFX void ReserveDeformPasses(size_t numPasses); private: - AZStd::vector 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 d4a70dd070..9836325ff2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp @@ -35,7 +35,7 @@ namespace EMotionFX // add a morph target void MorphSetup::AddMorphTarget(MorphTarget* morphTarget) { - mMorphTargets.emplace_back(morphTarget); + m_morphTargets.emplace_back(morphTarget); } @@ -44,20 +44,20 @@ namespace EMotionFX { if (delFromMem) { - mMorphTargets[nr]->Destroy(); + m_morphTargets[nr]->Destroy(); } - mMorphTargets.erase(AZStd::next(begin(mMorphTargets), nr)); + m_morphTargets.erase(AZStd::next(begin(m_morphTargets), nr)); } // remove a morph target void MorphSetup::RemoveMorphTarget(MorphTarget* morphTarget, bool delFromMem) { - const auto* foundMorphTarget = AZStd::find(begin(mMorphTargets), end(mMorphTargets), morphTarget); - if (foundMorphTarget != end(mMorphTargets)) + const auto* foundMorphTarget = AZStd::find(begin(m_morphTargets), end(m_morphTargets), morphTarget); + if (foundMorphTarget != end(m_morphTargets)) { - mMorphTargets.erase(foundMorphTarget); + m_morphTargets.erase(foundMorphTarget); } if (delFromMem) @@ -70,76 +70,76 @@ namespace EMotionFX // remove all morph targets void MorphSetup::RemoveAllMorphTargets() { - for (MorphTarget*& morphTarget : mMorphTargets) + for (MorphTarget*& morphTarget : m_morphTargets) { morphTarget->Destroy(); } - mMorphTargets.clear(); + m_morphTargets.clear(); } // get a morph target by ID MorphTarget* MorphSetup::FindMorphTargetByID(uint32 id) const { - const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [id](const MorphTarget* morphTarget) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [id](const MorphTarget* morphTarget) { return morphTarget->GetID() == id; }); - return foundMorphTarget != end(mMorphTargets) ? *foundMorphTarget : nullptr; + return foundMorphTarget != end(m_morphTargets) ? *foundMorphTarget : nullptr; } // get a morph target number by ID size_t MorphSetup::FindMorphTargetNumberByID(uint32 id) const { - const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [id](const MorphTarget* morphTarget) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [id](const MorphTarget* morphTarget) { return morphTarget->GetID() == id; }); - return foundMorphTarget != end(mMorphTargets) ? AZStd::distance(begin(mMorphTargets), foundMorphTarget) : InvalidIndex; + return foundMorphTarget != end(m_morphTargets) ? AZStd::distance(begin(m_morphTargets), foundMorphTarget) : InvalidIndex; } size_t MorphSetup::FindMorphTargetIndexByName(const char* name) const { - const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [name](const MorphTarget* morphTarget) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { return morphTarget->GetNameString() == name; }); - return foundMorphTarget != end(mMorphTargets) ? AZStd::distance(begin(mMorphTargets), foundMorphTarget) : InvalidIndex; + return foundMorphTarget != end(m_morphTargets) ? AZStd::distance(begin(m_morphTargets), foundMorphTarget) : InvalidIndex; } size_t MorphSetup::FindMorphTargetIndexByNameNoCase(const char* name) const { - const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [name](const MorphTarget* morphTarget) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { return AzFramework::StringFunc::Equal(morphTarget->GetNameString().c_str(), name, false /* no case */); }); - return foundMorphTarget != end(mMorphTargets) ? AZStd::distance(begin(mMorphTargets), foundMorphTarget) : InvalidIndex; + 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 auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [name](const MorphTarget* morphTarget) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { return morphTarget->GetNameString() == name; }); - return foundMorphTarget != end(mMorphTargets) ? *foundMorphTarget : nullptr; + return foundMorphTarget != end(m_morphTargets) ? *foundMorphTarget : nullptr; } // find a morph target by name (not case sensitive) MorphTarget* MorphSetup::FindMorphTargetByNameNoCase(const char* name) const { - const auto foundMorphTarget = AZStd::find_if(begin(mMorphTargets), end(mMorphTargets), [name](const MorphTarget* morphTarget) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { return AzFramework::StringFunc::Equal(morphTarget->GetNameString().c_str(), name, false /* no case */); }); - return foundMorphTarget != end(mMorphTargets) ? *foundMorphTarget : nullptr; + return foundMorphTarget != end(m_morphTargets) ? *foundMorphTarget : nullptr; } @@ -150,7 +150,7 @@ namespace EMotionFX MorphSetup* clone = MorphSetup::Create(); // clone all morph targets - for (const MorphTarget* morphTarget : mMorphTargets) + for (const MorphTarget* morphTarget : m_morphTargets) { clone->AddMorphTarget(morphTarget->Clone()); } @@ -162,7 +162,7 @@ namespace EMotionFX void MorphSetup::ReserveMorphTargets(size_t numMorphTargets) { - mMorphTargets.reserve(numMorphTargets); + m_morphTargets.reserve(numMorphTargets); } @@ -176,7 +176,7 @@ namespace EMotionFX } // scale the morph targets - for (MorphTarget* morphTarget : mMorphTargets) + for (MorphTarget* morphTarget : m_morphTargets) { morphTarget->Scale(scaleFactor); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h index 23a5789e03..12014dba8e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h @@ -40,14 +40,14 @@ namespace EMotionFX * Get the number of morph targets inside this morph setup. * @result The number of morph targets. */ - MCORE_INLINE size_t GetNumMorphTargets() const { return mMorphTargets.size(); } + 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(size_t 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. @@ -137,7 +137,7 @@ namespace EMotionFX protected: - AZStd::vector mMorphTargets; /**< The collection of morph targets. */ + AZStd::vector m_morphTargets; /**< The collection of morph targets. */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp index df4aaa0e7c..5b6e85d653 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp @@ -62,12 +62,12 @@ namespace EMotionFX // allocate the number of morph targets const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); - mMorphTargets.resize(numMorphTargets); + 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()); } } @@ -76,11 +76,11 @@ namespace EMotionFX size_t MorphSetupInstance::FindMorphTargetIndexByID(uint32 id) const { // try to locate the morph target with the given ID - const auto foundElement = AZStd::find_if(mMorphTargets.begin(), mMorphTargets.end(), [id](const MorphTarget& morphTarget) + const auto foundElement = AZStd::find_if(m_morphTargets.begin(), m_morphTargets.end(), [id](const MorphTarget& morphTarget) { return morphTarget.GetID() == id; }); - return foundElement != mMorphTargets.end() ? AZStd::distance(mMorphTargets.begin(), foundElement) : InvalidIndex; + return foundElement != m_morphTargets.end() ? AZStd::distance(m_morphTargets.begin(), foundElement) : InvalidIndex; } @@ -89,7 +89,7 @@ namespace EMotionFX 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 e93ed7cf6d..d0c71f1f84 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h @@ -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,16 +123,16 @@ 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 size_t GetNumMorphTargets() const { return mMorphTargets.size(); } + 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(size_t nr) { return &mMorphTargets[nr]; } + MCORE_INLINE MorphTarget* GetMorphTarget(size_t nr) { return &m_morphTargets[nr]; } - MCORE_INLINE const MorphTarget* GetMorphTarget(size_t 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. @@ -149,7 +149,7 @@ namespace EMotionFX MorphTarget* FindMorphTargetByID(uint32 id); private: - AZStd::vector 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 9ccafbb5f3..f2ff9eef5d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp @@ -23,9 +23,9 @@ 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); @@ -177,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 { @@ -201,11 +201,11 @@ 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); } } @@ -213,87 +213,87 @@ namespace EMotionFX // copy the base class members to the target class 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 35e2f620ae..0cd85222d0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h @@ -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. @@ -276,10 +276,10 @@ 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp index c86815be80..ccb849a0d3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp @@ -65,22 +65,12 @@ 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 size_t numPoseNodes = targetSkeleton->GetNumNodes(); for (size_t i = 0; i < numPoseNodes; ++i) @@ -99,25 +89,18 @@ namespace EMotionFX const size_t neutralNodeIndex = neutralNode->GetNodeIndex(); const size_t targetNodeIndex = targetSkeleton->GetNode(i)->GetNodeIndex(); - // skip bones in the bone list - //if (mCaptureMeshDeforms) - //if (boneList.Contains( nodeA )) - //continue; - 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,23 +127,20 @@ 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()); } } @@ -173,24 +150,24 @@ namespace EMotionFX 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 - for (const Transformation& transform : mTransforms) + for (const Transformation& transform : m_transforms) { // if this is the node that gets modified by this transform - if (transform.mNodeIndex != nodeIndex) + if (transform.m_nodeIndex != nodeIndex) { continue; } - position += transform.mPosition * newWeight; - scale += transform.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(transform.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(); @@ -204,14 +181,14 @@ namespace EMotionFX bool MorphTargetStandard::Influences(size_t nodeIndex) const { return - AZStd::any_of(begin(mDeformDatas), end(mDeformDatas), [nodeIndex](const DeformData* deformData) + AZStd::any_of(begin(m_deformDatas), end(m_deformDatas), [nodeIndex](const DeformData* deformData) { - return deformData->mNodeIndex == nodeIndex; + return deformData->m_nodeIndex == nodeIndex; }) || - AZStd::any_of(begin(mTransforms), end(mTransforms), [nodeIndex](const Transformation& transform) + AZStd::any_of(begin(m_transforms), end(m_transforms), [nodeIndex](const Transformation& transform) { - return transform.mNodeIndex == nodeIndex; + return transform.m_nodeIndex == nodeIndex; }); } @@ -220,45 +197,34 @@ 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 - for (const Transformation& transform : mTransforms) + for (const Transformation& transform : m_transforms) { // try to find the node - const size_t nodeIndex = transform.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 += transform.mPosition * newWeight; + newTransform.m_position += transform.m_position * newWeight; EMFX_SCALECODE ( - newTransform.mScale += transform.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(transform.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); } @@ -266,33 +232,33 @@ namespace EMotionFX size_t MorphTargetStandard::GetNumDeformDatas() const { - return mDeformDatas.size(); + return m_deformDatas.size(); } 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.emplace_back(transform); + m_transforms.emplace_back(transform); } // get the number of transformations in this morph target size_t MorphTargetStandard::GetNumTransformations() const { - return mTransforms.size(); + return m_transforms.size(); } MorphTargetStandard::Transformation& MorphTargetStandard::GetTransformation(size_t nr) { - return mTransforms[nr]; + return m_transforms[nr]; } @@ -305,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 (uint32 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 @@ -327,18 +293,18 @@ namespace EMotionFX // constructor 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); } @@ -352,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(size_t numDeformDatas) { - mDeformDatas.reserve(numDeformDatas); + m_deformDatas.reserve(numDeformDatas); } // pre-allocate memory for the transformations void MorphTargetStandard::ReserveTransformations(size_t numTransforms) { - mTransforms.reserve(numTransforms); + m_transforms.reserve(numTransforms); } 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(size_t index) { - mTransforms.erase(AZStd::next(begin(mTransforms), index)); + m_transforms.erase(AZStd::next(begin(m_transforms), index)); } @@ -421,18 +387,18 @@ namespace EMotionFX } // scale the transformations - for (Transformation& transform : mTransforms) + for (Transformation& transform : m_transforms) { - 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) @@ -450,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 2ea1c43906..c4187fd638 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h @@ -59,11 +59,11 @@ 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(size_t nodeIndex, uint32 numVerts); @@ -72,11 +72,11 @@ namespace EMotionFX DeformData* Clone(); public: - VertexDelta* mDeltas; /**< The delta values. */ - uint32 mNumVerts; /**< The number of vertices in the mDeltas and mVertexNumbers arrays. */ - size_t 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. @@ -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. */ - size_t 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); @@ -260,8 +260,8 @@ namespace EMotionFX void Scale(float scaleFactor) override; private: - AZStd::vector 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 382a640e65..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 = aznumeric_caster(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 7421495c60..e3391ed44f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp @@ -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 @@ -474,11 +474,11 @@ namespace EMotionFX 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; } } @@ -491,14 +491,14 @@ namespace EMotionFX 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/NonUniformMotionData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.cpp index 619a962d7e..6ced6152e1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.cpp @@ -92,10 +92,10 @@ namespace EMotionFX 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; } @@ -153,10 +153,10 @@ namespace EMotionFX 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 @@ -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/UniformMotionData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.cpp index 44ed629756..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; ) } } @@ -156,10 +156,10 @@ namespace EMotionFX { 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; } @@ -225,11 +225,11 @@ namespace EMotionFX { 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 @@ -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/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/MotionInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp index 3cefe9e513..696430271a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp @@ -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(); @@ -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 @@ -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 59bd08d248..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. */ @@ -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. @@ -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 a10a4722eb..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,36 +42,36 @@ namespace EMotionFX // constructor MotionInstancePool::Pool::Pool() { - 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 - for (SubPool* subPool : mSubPools) + for (SubPool* subPool : m_subPools) { delete subPool; } - mSubPools.clear(); + m_subPools.clear(); - mFreeList.clear(); + m_freeList.clear(); } else { @@ -89,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; } @@ -115,7 +115,7 @@ namespace EMotionFX // init the motion instance pool 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; @@ -130,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.resize_no_construct(numInitialInstances); + 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.resize_no_construct(numInitialInstances); + 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.emplace_back(subPool); + m_pool->m_subPools.emplace_back(subPool); } else { @@ -176,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.size() > 0) + if (m_pool->m_freeList.size() > 0) { - const MemLocation& location = mPool->mFreeList.back(); - 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.pop_back(); // 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 size_t 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 size_t startIndex = mPool->mFreeList.size(); - //mPool->mFreeList.Reserve( numInstances * 2 ); - if (mPool->mFreeList.capacity() < 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.capacity() / 2); + m_pool->m_freeList.reserve(m_pool->m_numInstances + m_pool->m_freeList.capacity() / 2); } - mPool->mFreeList.resize_no_construct(startIndex + numInstances); + 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.emplace_back(subPool); + m_pool->m_subPools.emplace_back(subPool); - const MemLocation& location = mPool->mFreeList.back(); - 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.pop_back(); // 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 @@ -260,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); @@ -270,13 +269,13 @@ namespace EMotionFX // add it back to the free list if (motionInstance->GetSubPool()) { - motionInstance->GetSubPool()->mNumInUse--; + motionInstance->GetSubPool()->m_numInUse--; } - mPool->mFreeList.emplace_back(); - mPool->mFreeList.back().mAddress = motionInstance; - mPool->mFreeList.back().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 @@ -289,27 +288,27 @@ namespace EMotionFX Lock(); MCore::LogInfo("EMotionFX::MotionInstancePool::LogMemoryStats() - Logging motion instance pool info"); - const size_t numFree = mPool->mFreeList.size(); - size_t numUsed = mPool->mNumUsedInstances; + 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); } } @@ -317,17 +316,17 @@ namespace EMotionFX totalUsedInstancesMemUsage += usedMemUsage; totalMemUsage += memUsage; totalMemUsage += sizeof(Pool); - totalMemUsage += mPool->mFreeList.capacity() * sizeof(decltype(mPool->mFreeList)::value_type); + 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.size()); + 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); @@ -358,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(); } @@ -374,26 +373,26 @@ namespace EMotionFX { Lock(); - for (size_t i = 0; i < mPool->mSubPools.size(); ) + 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 (size_t a = 0; a < mPool->mFreeList.size(); ) + 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.erase(AZStd::next(begin(mPool->mFreeList), 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.erase(AZStd::next(begin(mPool->mSubPools), i)); + m_pool->m_subPools.erase(AZStd::next(begin(m_pool->m_subPools), i)); delete subPool; } else @@ -402,11 +401,10 @@ namespace EMotionFX } } - mPool->mSubPools.shrink_to_fit(); - //mPool->mFreeList.Shrink(); - if ((mPool->mFreeList.capacity() - mPool->mFreeList.size()) > 4096) + m_pool->m_subPools.shrink_to_fit(); + if ((m_pool->m_freeList.capacity() - m_pool->m_freeList.size()) > 4096) { - mPool->mFreeList.reserve(mPool->mFreeList.size() + 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 e257640e33..54837a1113 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h @@ -68,15 +68,15 @@ namespace EMotionFX SubPool(); ~SubPool(); - uint8* mData; - size_t mNumInstances; - size_t 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; - size_t mNumInstances; - size_t mNumUsedInstances; - size_t mSubPoolSize; - AZStd::vector mFreeList; - AZStd::vector 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 b613ecc147..dddfd1eba8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp @@ -24,7 +24,7 @@ namespace EMotionFX : MotionSystem(actorInstance) { // set the motion based actor repositioning layer pass - mRepositioningPass = RepositioningLayerPass::Create(this); + m_repositioningPass = RepositioningLayerPass::Create(this); } @@ -34,7 +34,7 @@ namespace EMotionFX RemoveAllLayerPasses(); // get rid of the repositioning layer pass - mRepositioningPass->Destroy(); + m_repositioningPass->Destroy(); } @@ -49,7 +49,7 @@ namespace EMotionFX void MotionLayerSystem::RemoveAllLayerPasses(bool delFromMem) { // delete all layer passes - for (LayerPass* layerPass : mLayerPasses) + for (LayerPass* layerPass : m_layerPasses) { if (delFromMem) { @@ -57,7 +57,7 @@ namespace EMotionFX } } - mLayerPasses.clear(); + m_layerPasses.clear(); } @@ -65,23 +65,23 @@ namespace EMotionFX void MotionLayerSystem::StartMotion(MotionInstance* motion, PlayBackInfo* info) { // check if we have any motions playing already - const size_t numMotionInstances = mMotionInstances.size(); + const size_t numMotionInstances = m_motionInstances.size(); if (numMotionInstances > 0) { // find the right location in the motion instance array to insert this motion instance size_t insertPos = FindInsertPos(motion->GetPriorityLevel()); if (insertPos != InvalidIndex) { - mMotionInstances.emplace(AZStd::next(begin(mMotionInstances), insertPos), motion); + m_motionInstances.emplace(AZStd::next(begin(m_motionInstances), insertPos), motion); } else { - mMotionInstances.emplace_back(motion); + m_motionInstances.emplace_back(motion); } } else // no motions are playing, so just add it { - mMotionInstances.emplace_back(motion); + m_motionInstances.emplace_back(motion); } // trigger an event @@ -92,18 +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 size_t MotionLayerSystem::FindInsertPos(size_t priorityLevel) const { - const auto* foundInsertPosition = AZStd::lower_bound(begin(mMotionInstances), end(mMotionInstances), priorityLevel, [](const MotionInstance* motionInstance, size_t level) + const auto* foundInsertPosition = AZStd::lower_bound(begin(m_motionInstances), end(m_motionInstances), priorityLevel, [](const MotionInstance* motionInstance, size_t level) { return motionInstance->GetPriorityLevel() < level; }); - return foundInsertPosition != end(mMotionInstances) ? AZStd::distance(begin(mMotionInstances), foundInsertPosition) : InvalidIndex; + return foundInsertPosition != end(m_motionInstances) ? AZStd::distance(begin(m_motionInstances), foundInsertPosition) : InvalidIndex; } @@ -117,22 +117,22 @@ namespace EMotionFX UpdateMotionTree(); // update the motion queue - mMotionQueue->Update(); + m_motionQueue->Update(); // process all layer passes - for (LayerPass* layerPass : mLayerPasses) + for (LayerPass* layerPass : m_layerPasses) { 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) @@ -145,9 +145,9 @@ namespace EMotionFX // update the motion tree void MotionLayerSystem::UpdateMotionTree() { - for (size_t i = 0; i < mMotionInstances.size(); ++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()) @@ -227,10 +227,10 @@ namespace EMotionFX if (source->GetCanOverwrite()) { // remove all motions that got overwritten by the current one - const size_t numToRemove = mMotionInstances.size() - (i + 1); + 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]); } } } @@ -245,7 +245,7 @@ namespace EMotionFX size_t numRemoved = 0; // start from the bottom up - for (auto iter = rbegin(mMotionInstances); iter != rend(mMotionInstances); ++iter) + for (auto iter = rbegin(m_motionInstances); iter != rend(m_motionInstances); ++iter) { MotionInstance* curInstance = *iter; @@ -267,11 +267,11 @@ namespace EMotionFX MotionInstance* MotionLayerSystem::FindFirstNonMixingMotionInstance() const { // if there aren't any motion instances, return nullptr - const auto foundMotionInstance = AZStd::find_if(begin(mMotionInstances), end(mMotionInstances), [](const MotionInstance* motionInstance) + const auto foundMotionInstance = AZStd::find_if(begin(m_motionInstances), end(m_motionInstances), [](const MotionInstance* motionInstance) { return !motionInstance->GetIsMixing(); }); - return foundMotionInstance != end(mMotionInstances) ? *foundMotionInstance : nullptr; + return foundMotionInstance != end(m_motionInstances) ? *foundMotionInstance : nullptr; } @@ -279,25 +279,25 @@ 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 size_t numMotionInstances = mMotionInstances.size(); + 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 (auto iter = rbegin(mMotionInstances); iter != rend(mMotionInstances); ++iter) + for (auto iter = rbegin(m_motionInstances); iter != rend(m_motionInstances); ++iter) { // skip inactive motion instances MotionInstance* instance = *iter; // the motion to be blended @@ -322,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 @@ -340,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 @@ -365,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 @@ -377,14 +377,14 @@ namespace EMotionFX // add a new pass void MotionLayerSystem::AddLayerPass(LayerPass* newPass) { - mLayerPasses.emplace_back(newPass); + m_layerPasses.emplace_back(newPass); } // get the number of layer passes size_t MotionLayerSystem::GetNumLayerPasses() const { - return mLayerPasses.size(); + return m_layerPasses.size(); } @@ -393,19 +393,19 @@ namespace EMotionFX { if (delFromMem) { - mLayerPasses[nr]->Destroy(); + m_layerPasses[nr]->Destroy(); } - mLayerPasses.erase(AZStd::next(begin(mLayerPasses), nr)); + m_layerPasses.erase(AZStd::next(begin(m_layerPasses), nr)); } // remove a given pass void MotionLayerSystem::RemoveLayerPass(LayerPass* pass, bool delFromMem) { - if (const auto it = AZStd::find(begin(mLayerPasses), end(mLayerPasses), pass); it != end(mLayerPasses)) + if (const auto it = AZStd::find(begin(m_layerPasses), end(m_layerPasses), pass); it != end(m_layerPasses)) { - mLayerPasses.erase(it); + m_layerPasses.erase(it); } if (delFromMem) @@ -418,7 +418,7 @@ namespace EMotionFX // insert a layer pass at a given position void MotionLayerSystem::InsertLayerPass(size_t insertPos, LayerPass* pass) { - mLayerPasses.emplace(AZStd::next(begin(mLayerPasses), insertPos), pass); + m_layerPasses.emplace(AZStd::next(begin(m_layerPasses), insertPos), pass); } @@ -439,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(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 be14780341..81119977dd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h @@ -179,8 +179,8 @@ namespace EMotionFX private: - AZStd::vector 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 8472e46796..5ed15fe896 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp @@ -43,7 +43,7 @@ namespace EMotionFX : BaseObject() { // reserve space for 400 motions - mMotions.reserve(400); + m_motions.reserve(400); m_motionDataFactory = aznew MotionDataFactory(); } @@ -66,28 +66,28 @@ namespace EMotionFX if (delFromMemory) { // destroy all motion sets, they will internally call RemoveMotionSetWithoutLock(this) in their destructor - while (mMotionSets.size() > 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.size() > 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(); } } @@ -95,81 +95,81 @@ 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 { - const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [motionName, isTool](const auto& motion) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [motionName, isTool](const auto& motion) { return motion->GetIsOwnedByRuntime() != isTool && motion->GetNameString() == motionName; }); - return foundMotion != end(mMotions) ? *foundMotion : nullptr; + 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 { - const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [fileName, isTool](const auto& motion) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [fileName, isTool](const auto& motion) { return motion->GetIsOwnedByRuntime() != isTool && AzFramework::StringFunc::Equal(motion->GetFileNameString().c_str(), fileName, false /* no case */); }); - return foundMotion != end(mMotions) ? *foundMotion : nullptr; + 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 { - const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [fileName, isTool](const auto& motionSet) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [fileName, isTool](const auto& motionSet) { return motionSet->GetIsOwnedByRuntime() != isTool && AzFramework::StringFunc::Equal(motionSet->GetFilename(), fileName); }); - return foundMotionSet != end(mMotionSets) ? *foundMotionSet : nullptr; + 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 { - const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [name, isOwnedByRuntime](const auto& motionSet) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [name, isOwnedByRuntime](const auto& motionSet) { return motionSet->GetIsOwnedByRuntime() == isOwnedByRuntime && AzFramework::StringFunc::Equal(motionSet->GetName(), name); }); - return foundMotionSet != end(mMotionSets) ? *foundMotionSet : nullptr; + return foundMotionSet != end(m_motionSets) ? *foundMotionSet : nullptr; } // find the motion index for the given motion size_t MotionManager::FindMotionIndexByName(const char* motionName, bool isTool) const { - const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [motionName, isTool](const auto& motion) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [motionName, isTool](const auto& motion) { return motion->GetIsOwnedByRuntime() != isTool && motion->GetNameString() == motionName; }); - return foundMotion != end(mMotions) ? AZStd::distance(begin(mMotions), foundMotion) : InvalidIndex; + return foundMotion != end(m_motions) ? AZStd::distance(begin(m_motions), foundMotion) : InvalidIndex; } // find the motion set index for the given motion size_t MotionManager::FindMotionSetIndexByName(const char* name, bool isTool) const { - const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [name, isTool](const MotionSet* motionSet) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [name, isTool](const MotionSet* motionSet) { return motionSet->GetIsOwnedByRuntime() != isTool && AzFramework::StringFunc::Equal(motionSet->GetName(), name); }); - return foundMotionSet != end(mMotionSets) ? AZStd::distance(begin(mMotionSets), foundMotionSet) : InvalidIndex; + return foundMotionSet != end(m_motionSets) ? AZStd::distance(begin(m_motionSets), foundMotionSet) : InvalidIndex; } // find the motion index for the given motion size_t MotionManager::FindMotionIndexByID(uint32 id) const { - const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [id](const Motion* motion) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [id](const Motion* motion) { return motion->GetID() == id; }); - return foundMotion != end(mMotions) ? AZStd::distance(begin(mMotions), foundMotion) : InvalidIndex; + return foundMotion != end(m_motions) ? AZStd::distance(begin(m_motions), foundMotion) : InvalidIndex; // get the number of motions and iterate through them } @@ -177,55 +177,55 @@ namespace EMotionFX // find the motion set index size_t MotionManager::FindMotionSetIndexByID(uint32 id) const { - const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [id](const MotionSet* motionSet) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [id](const MotionSet* motionSet) { return motionSet->GetID() == id; }); - return foundMotionSet != end(mMotionSets) ? AZStd::distance(begin(mMotionSets), foundMotionSet) : InvalidIndex; + 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 { - const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [id](const Motion* motion) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [id](const Motion* motion) { return motion->GetID() == id; }); - return foundMotion != end(mMotions) ? *foundMotion : nullptr; + 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 { - const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [id](const MotionSet* motionSet) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [id](const MotionSet* motionSet) { return motionSet->GetID() == id; }); - return foundMotionSet != end(mMotionSets) ? *foundMotionSet : nullptr; + return foundMotionSet != end(m_motionSets) ? *foundMotionSet : nullptr; } // find the motion set index and return it size_t MotionManager::FindMotionSetIndex(MotionSet* motionSet) const { - const auto foundMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [motionSet](const MotionSet* ms) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [motionSet](const MotionSet* ms) { return ms == motionSet; }); - return foundMotionSet != end(mMotionSets) ? AZStd::distance(begin(mMotionSets), foundMotionSet) : InvalidIndex; + return foundMotionSet != end(m_motionSets) ? AZStd::distance(begin(m_motionSets), foundMotionSet) : InvalidIndex; } // find the motion index for the given motion size_t MotionManager::FindMotionIndex(Motion* motion) const { - const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [motion](const Motion* m) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [motion](const Motion* m) { return m == motion; }); - return foundMotion != end(mMotions) ? AZStd::distance(begin(mMotions), foundMotion) : InvalidIndex; + return foundMotion != end(m_motions) ? AZStd::distance(begin(m_motions), foundMotion) : InvalidIndex; } @@ -233,16 +233,16 @@ namespace EMotionFX void MotionManager::AddMotion(Motion* motion) { // wait with execution until we can set the lock - mLock.Lock(); - mMotions.emplace_back(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); } @@ -250,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); } @@ -258,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); } @@ -266,7 +266,7 @@ 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); } @@ -274,18 +274,18 @@ namespace EMotionFX // find the index by filename size_t MotionManager::FindMotionIndexByFileName(const char* fileName, bool isTool) const { - const auto foundMotion = AZStd::find_if(begin(mMotions), end(mMotions), [fileName, isTool](const Motion* motion) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [fileName, isTool](const Motion* motion) { return motion->GetIsOwnedByRuntime() != isTool && motion->GetFileNameString() == fileName; }); - return foundMotion != end(mMotions) ? AZStd::distance(begin(mMotions), foundMotion) : InvalidIndex; + 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); } @@ -314,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(); @@ -340,7 +340,7 @@ namespace EMotionFX return false; } - Motion* motion = mMotions[index]; + Motion* motion = m_motions[index]; // stop all motion instances of the motion to delete const size_t numActorInstances = GetActorManager().GetNumActorInstances(); @@ -370,7 +370,7 @@ namespace EMotionFX } // Reset all motion entries in the motion sets of the current motion. - for (const MotionSet* motionSet : mMotionSets) + for (const MotionSet* motionSet : m_motionSets) { const EMotionFX::MotionSet::MotionEntries& motionEntries = motionSet->GetMotionEntries(); for (const auto& item : motionEntries) @@ -398,11 +398,11 @@ namespace EMotionFX // which unregisters the motion from the motion manager motion->SetAutoUnregister(false); motion->Destroy(); - mMotions.erase(AZStd::next(begin(mMotions), 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.erase(AZStd::next(begin(mMotions), 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; @@ -412,8 +412,8 @@ namespace EMotionFX // add a new motion set void MotionManager::AddMotionSet(MotionSet* motionSet) { - MCore::LockGuard lock(mLock); - mMotionSets.emplace_back(motionSet); + MCore::LockGuard lock(m_lock); + m_motionSets.emplace_back(motionSet); } @@ -425,7 +425,7 @@ namespace EMotionFX return false; } - MotionSet* motionSet = mMotionSets[index]; + MotionSet* motionSet = m_motionSets[index]; // remove from the parent MotionSet* parentSet = motionSet->GetParentSet(); @@ -451,7 +451,7 @@ namespace EMotionFX delete motionSet; } - mMotionSets.erase(AZStd::next(begin(mMotionSets), index)); + m_motionSets.erase(AZStd::next(begin(m_motionSets), index)); return true; } @@ -460,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); } @@ -468,7 +468,7 @@ 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); } @@ -479,7 +479,7 @@ namespace EMotionFX size_t result = 0; // get the number of motion sets and iterate through them - for (const MotionSet* motionSet : mMotionSets) + for (const MotionSet* motionSet : m_motionSets) { // sum up the root motion sets if (motionSet->GetParentSet() == nullptr) @@ -495,25 +495,25 @@ namespace EMotionFX // find the given root motion set MotionSet* MotionManager::FindRootMotionSet(size_t index) { - auto foundRootMotionSet = AZStd::find_if(begin(mMotionSets), end(mMotionSets), [iter = index](const MotionSet* motionSet) mutable + auto foundRootMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [iter = index](const MotionSet* motionSet) mutable { return motionSet->GetParentSet() == nullptr && iter-- == 0; }); - return foundRootMotionSet != end(mMotionSets) ? *foundRootMotionSet : nullptr; + 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 2aad2f72d9..24c8c784f3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h @@ -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(size_t 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 size_t GetNumMotions() const { return mMotions.size(); } + MCORE_INLINE size_t GetNumMotions() const { return m_motions.size(); } /** * Remove the motion with the given name from the motion manager. @@ -154,13 +154,13 @@ 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(size_t 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 size_t GetNumMotionSets() const { return mMotionSets.size(); } + MCORE_INLINE size_t GetNumMotionSets() const { return m_motionSets.size(); } /** * Calculate the number of root motion sets. @@ -233,10 +233,10 @@ namespace EMotionFX const MotionDataFactory& GetMotionDataFactory() const; private: - AZStd::vector mMotions; /**< The array of motions. */ - AZStd::vector 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp index 10b52b1f8b..e523572689 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp @@ -26,8 +26,8 @@ namespace EMotionFX { MCORE_ASSERT(actorInstance && motionSystem); - mActorInstance = actorInstance; - mMotionSystem = motionSystem; + m_actorInstance = actorInstance; + m_motionSystem = motionSystem; } @@ -48,12 +48,12 @@ namespace EMotionFX // remove a given entry from the queue 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.erase(AZStd::next(begin(mEntries), nr)); + m_entries.erase(AZStd::next(begin(m_entries), nr)); } @@ -70,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(); @@ -79,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; @@ -109,7 +109,7 @@ namespace EMotionFX RemoveFirstEntry(); // start the motion - mMotionSystem->StartMotion(queueEntry.mMotion, &queueEntry.mPlayInfo); + m_motionSystem->StartMotion(queueEntry.m_motion, &queueEntry.m_playInfo); } @@ -117,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) @@ -126,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()) @@ -167,7 +167,7 @@ namespace EMotionFX void MotionQueue::ClearAllEntries() { - while (mEntries.size()) + while (m_entries.size()) { RemoveEntry(0); } @@ -176,31 +176,31 @@ namespace EMotionFX void MotionQueue::AddEntry(const MotionQueue::QueueEntry& motion) { - mEntries.emplace_back(motion); + m_entries.emplace_back(motion); } size_t MotionQueue::GetNumEntries() const { - return mEntries.size(); + return m_entries.size(); } MotionQueue::QueueEntry& MotionQueue::GetFirstEntry() { - MCORE_ASSERT(mEntries.size() > 0); - return mEntries[0]; + MCORE_ASSERT(m_entries.size() > 0); + return m_entries[0]; } void MotionQueue::RemoveFirstEntry() { - mEntries.erase(mEntries.begin()); + m_entries.erase(m_entries.begin()); } 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 aa30ccab46..8584d43be2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h @@ -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) {} }; /** @@ -133,9 +133,9 @@ namespace EMotionFX void PlayNextMotion(); private: - AZStd::vector 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/MotionSystem.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp index 7619187d23..a6ddb776c2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp @@ -29,11 +29,11 @@ namespace EMotionFX { MCORE_ASSERT(actorInstance); - 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); } @@ -45,17 +45,16 @@ namespace EMotionFX GetEventManager().OnDeleteMotionSystem(this); // delete the motion infos - while (!mMotionInstances.empty()) + while (!m_motionInstances.empty()) { - //delete mMotionInstances.GetLast(); - GetMotionInstancePool().Free(mMotionInstances.back()); - mMotionInstances.pop_back(); + 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(); } } @@ -75,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); @@ -109,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); @@ -124,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,9 +125,9 @@ namespace EMotionFX { // remove the motion instance from the actor const bool isSuccess = [this, instance] { - if(const auto it = AZStd::find(begin(mMotionInstances), end(mMotionInstances), instance); it != end(mMotionInstances)) + if(const auto it = AZStd::find(begin(m_motionInstances), end(m_motionInstances), instance); it != end(m_motionInstances)) { - mMotionInstances.erase(it); + m_motionInstances.erase(it); return true; } return false; @@ -163,7 +150,7 @@ namespace EMotionFX MCORE_UNUSED(updateNodes); // update the motion queue - mMotionQueue->Update(); + m_motionQueue->Update(); // update the motions UpdateMotionInstances(timePassed); @@ -173,7 +160,7 @@ namespace EMotionFX // stop all the motions that are currently playing void MotionSystem::StopAllMotions() { - for (MotionInstance* motionInstance : mMotionInstances) + for (MotionInstance* motionInstance : m_motionInstances) { motionInstance->Stop(); } @@ -183,7 +170,7 @@ namespace EMotionFX // stop all motion instances of a given motion void MotionSystem::StopAllMotions(Motion* motion) { - for (MotionInstance* motionInstance : mMotionInstances) + for (MotionInstance* motionInstance : m_motionInstances) { if (motionInstance->GetMotion()->GetID() == motion->GetID()) { @@ -196,14 +183,14 @@ namespace EMotionFX // remove the given motion void MotionSystem::RemoveMotion(size_t nr, bool deleteMem) { - MCORE_ASSERT(nr < mMotionInstances.size()); + MCORE_ASSERT(nr < m_motionInstances.size()); if (deleteMem) { - GetEMotionFX().GetMotionInstancePool()->Free(mMotionInstances[nr]); + GetEMotionFX().GetMotionInstancePool()->Free(m_motionInstances[nr]); } - mMotionInstances.erase(AZStd::next(begin(mMotionInstances), nr)); + m_motionInstances.erase(AZStd::next(begin(m_motionInstances), nr)); } @@ -212,15 +199,15 @@ namespace EMotionFX { MCORE_ASSERT(motion); - const auto it = AZStd::find(begin(mMotionInstances), end(mMotionInstances), motion); - MCORE_ASSERT(it != end(mMotionInstances)); + const auto it = AZStd::find(begin(m_motionInstances), end(m_motionInstances), motion); + MCORE_ASSERT(it != end(m_motionInstances)); - if (it == end(mMotionInstances)) + if (it == end(m_motionInstances)) { return; } - RemoveMotion(AZStd::distance(begin(mMotionInstances), it), delMem); + RemoveMotion(AZStd::distance(begin(m_motionInstances), it), delMem); } @@ -228,7 +215,7 @@ namespace EMotionFX void MotionSystem::UpdateMotionInstances(float timePassed) { // update all the motion infos - for (MotionInstance* motionInstance : mMotionInstances) + for (MotionInstance* motionInstance : m_motionInstances) { motionInstance->Update(timePassed); } @@ -238,7 +225,7 @@ 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 { - return instance && AZStd::any_of(begin(mMotionInstances), end(mMotionInstances), [instance](const MotionInstance* motionInstance) + return instance && AZStd::any_of(begin(m_motionInstances), end(m_motionInstances), [instance](const MotionInstance* motionInstance) { return motionInstance->GetID() == instance->GetID(); }); @@ -248,7 +235,7 @@ namespace EMotionFX // check if there is a motion instance playing, which is an instance of a specified motion bool MotionSystem::CheckIfIsPlayingMotion(Motion* motion, bool ignorePausedMotions) const { - return motion && AZStd::any_of(begin(mMotionInstances), end(mMotionInstances), [motion, ignorePausedMotions](const MotionInstance* motionInstance) + return motion && AZStd::any_of(begin(m_motionInstances), end(m_motionInstances), [motion, ignorePausedMotions](const MotionInstance* motionInstance) { return !(ignorePausedMotions && motionInstance->GetIsPaused()) && motionInstance->GetMotion()->GetID() == motion->GetID(); @@ -259,27 +246,27 @@ namespace EMotionFX // return given motion instance MotionInstance* MotionSystem::GetMotionInstance(size_t nr) const { - MCORE_ASSERT(nr < mMotionInstances.size()); - return mMotionInstances[nr]; + MCORE_ASSERT(nr < m_motionInstances.size()); + return m_motionInstances[nr]; } // return number of motion instances size_t MotionSystem::GetNumMotionInstances() const { - return mMotionInstances.size(); + 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; } @@ -291,7 +278,7 @@ namespace EMotionFX // copy entries from the given queue to the motion system's one 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 @@ -302,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.emplace_back(instance); + m_motionInstances.emplace_back(instance); } bool MotionSystem::GetIsPlaying() const { - return !mMotionInstances.empty(); + 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 109cf5d41f..611ccd731a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h @@ -215,9 +215,9 @@ namespace EMotionFX protected: - AZStd::vector 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 3cc4d027a8..6f07936fe7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp @@ -30,8 +30,8 @@ namespace EMotionFX MultiThreadScheduler::MultiThreadScheduler() : ActorUpdateScheduler() { - 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); } @@ -52,7 +52,7 @@ namespace EMotionFX void MultiThreadScheduler::Clear() { Lock(); - mSteps.clear(); + m_steps.clear(); Unlock(); } @@ -78,10 +78,10 @@ namespace EMotionFX void MultiThreadScheduler::Print() { // for all steps - const size_t numSteps = mSteps.size(); + const size_t numSteps = m_steps.size(); for (size_t i = 0; i < numSteps; ++i) { - AZ_Printf("EMotionFX", "STEP %.3zu - %zu", i, mSteps[i].mActorInstances.size()); + AZ_Printf("EMotionFX", "STEP %.3zu - %zu", i, m_steps[i].m_actorInstances.size()); } AZ_Printf("EMotionFX", "---------"); @@ -91,15 +91,15 @@ namespace EMotionFX void MultiThreadScheduler::RemoveEmptySteps() { // process all steps - for (size_t s = 0; s < mSteps.size(); ) + for (size_t s = 0; s < m_steps.size(); ) { - if (!mSteps[s].mActorInstances.empty()) + if (!m_steps[s].m_actorInstances.empty()) { s++; } else { - mSteps.erase(AZStd::next(begin(mSteps), s)); + m_steps.erase(AZStd::next(begin(m_steps), s)); } } } @@ -108,21 +108,21 @@ namespace EMotionFX // execute the schedule void MultiThreadScheduler::Execute(float timePassedInSeconds) { - MCore::LockGuardRecursive guard(mMutex); + MCore::LockGuardRecursive guard(m_mutex); - size_t numSteps = mSteps.size(); + 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.size(); + numSteps = m_steps.size(); } //----------------------------------------------------------- @@ -142,20 +142,20 @@ 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 (const ScheduleStep& currentStep : mSteps) + for (const ScheduleStep& currentStep : m_steps) { - if (currentStep.mActorInstances.empty()) + if (currentStep.m_actorInstances.empty()) { continue; } // process the actor instances in the current step in parallel AZ::JobCompletion jobCompletion; - for (ActorInstance* actorInstance : currentStep.mActorInstances) + for (ActorInstance* actorInstance : currentStep.m_actorInstances) { if (actorInstance->GetIsEnabled() == false) { @@ -173,7 +173,7 @@ namespace EMotionFX const bool isVisible = actorInstance->GetIsVisible(); if (isVisible) { - mNumVisible.Increment(); + m_numVisible.Increment(); } // check if we want to sample motions @@ -186,7 +186,7 @@ namespace EMotionFX if (isVisible) { - mNumSampled.Increment(); + m_numSampled.Increment(); } } @@ -197,7 +197,7 @@ namespace EMotionFX job->SetDependent(&jobCompletion); job->Start(); - mNumUpdated.Increment(); + m_numUpdated.Increment(); } jobCompletion.StartAndWaitForCompletion(); @@ -209,11 +209,11 @@ namespace EMotionFX bool MultiThreadScheduler::FindNextFreeItem(ActorInstance* actorInstance, size_t startStep, size_t* outStepNr) { // try out all steps - const size_t numSteps = mSteps.size(); + 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; } @@ -229,11 +229,11 @@ namespace EMotionFX bool MultiThreadScheduler::HasActorInstanceInSteps(const ActorInstance* actorInstance) const { - const size_t numSteps = mSteps.size(); + 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; } @@ -244,33 +244,33 @@ namespace EMotionFX 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 size_t outStep = startStep; if (!FindNextFreeItem(instance, startStep, &outStep)) { - mSteps.reserve(10); - mSteps.emplace_back(); - outStep = mSteps.size() - 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.size() % 5 == 0) + if (m_steps[outStep].m_dependencies.size() % 5 == 0) { - mSteps[outStep].mDependencies.reserve(mSteps[outStep].mDependencies.size() + 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 size_t numAttachments = instance->GetNumAttachments(); @@ -288,27 +288,27 @@ namespace EMotionFX // remove the actor instance from the schedule (excluding attachments) 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 size_t numSteps = mSteps.size(); + 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(); + 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); } @@ -326,7 +326,7 @@ namespace EMotionFX // remove the actor instance (including all of its attachments) void MultiThreadScheduler::RecursiveRemoveActorInstance(ActorInstance* actorInstance, size_t startStep) { - MCore::LockGuardRecursive guard(mMutex); + MCore::LockGuardRecursive guard(m_mutex); // remove the actual actor instance const size_t step = RemoveActorInstance(actorInstance, startStep); @@ -346,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 6d5a7251e5..cf22875d97 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h @@ -50,8 +50,8 @@ namespace EMotionFX */ struct EMFX_API ScheduleStep { - AZStd::vector 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. */ + 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. */ }; /** @@ -119,13 +119,13 @@ namespace EMotionFX void Lock(); void Unlock(); - const ScheduleStep& GetScheduleStep(size_t index) const { return mSteps[index]; } - size_t GetNumScheduleSteps() const { return mSteps.size(); } + const ScheduleStep& GetScheduleStep(size_t index) const { return m_steps[index]; } + size_t GetNumScheduleSteps() const { return m_steps.size(); } protected: - AZStd::vector< 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; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp index 4bb1d850c9..1217c928bc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp @@ -20,20 +20,20 @@ namespace EMotionFX Node::Node(const char* name, Skeleton* skeleton) : BaseObject() { - mParentIndex = InvalidIndex; - mNodeIndex = InvalidIndex; // 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 = 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 = InvalidIndex32; + m_nameId = InvalidIndex32; } } @@ -41,13 +41,13 @@ namespace EMotionFX Node::Node(uint32 nameID, Skeleton* skeleton) : BaseObject() { - mParentIndex = InvalidIndex; - mNodeIndex = InvalidIndex; // 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 = 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; } @@ -78,19 +78,19 @@ namespace EMotionFX // 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.size()); - for (const NodeAttribute* attribute : mAttributes) + result->m_attributes.reserve(m_attributes.size()); + for (const NodeAttribute* attribute : m_attributes) { result->AddAttribute(attribute->Clone()); } @@ -103,10 +103,10 @@ namespace EMotionFX // removes all attributes void Node::RemoveAllAttributes() { - while (!mAttributes.empty()) + while (!m_attributes.empty()) { - mAttributes.back()->Destroy(); - mAttributes.pop_back(); + m_attributes.back()->Destroy(); + m_attributes.pop_back(); } } @@ -118,9 +118,9 @@ namespace EMotionFX size_t result = 0; // retrieve the number of child nodes of the actual node - for (size_t childIndex : mChildIndices) + for (size_t childIndex : m_childIndices) { - mSkeleton->GetNode(childIndex)->RecursiveCountChildNodes(result); + m_skeleton->GetNode(childIndex)->RecursiveCountChildNodes(result); } return result; @@ -134,9 +134,9 @@ namespace EMotionFX numNodes++; // recurse down the hierarchy - for (size_t childIndex : mChildIndices) + for (size_t childIndex : m_childIndices) { - mSkeleton->GetNode(childIndex)->RecursiveCountChildNodes(numNodes); + m_skeleton->GetNode(childIndex)->RecursiveCountChildNodes(numNodes); } } @@ -173,7 +173,7 @@ namespace EMotionFX // remove the given attribute of the given type from the node void Node::RemoveAttributeByType(uint32 attributeTypeID, size_t occurrence) { - const auto foundAttribute = AZStd::find_if(begin(mAttributes), end(mAttributes), [attributeTypeID, occurrence, currentOccurrence = size_t{0}] (const NodeAttribute* attribute) mutable + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [attributeTypeID, occurrence, currentOccurrence = size_t{0}] (const NodeAttribute* attribute) mutable { if (attribute->GetType() == attributeTypeID) { @@ -183,14 +183,14 @@ namespace EMotionFX return false; }); - mAttributes.erase(foundAttribute); + m_attributes.erase(foundAttribute); } // remove all attributes of the given type from the node size_t Node::RemoveAllAttributesByType(uint32 attributeTypeID) { - return AZStd::erase_if(mAttributes, [attributeTypeID](const NodeAttribute* attribute) + return AZStd::erase_if(m_attributes, [attributeTypeID](const NodeAttribute* attribute) { return attribute->GetType() == attributeTypeID; }); @@ -201,12 +201,12 @@ namespace EMotionFX // recursively find the root node (expensive call) Node* Node::FindRoot() const { - size_t parentIndex = mParentIndex; + size_t parentIndex = m_parentIndex; const Node* curNode = this; while (parentIndex != InvalidIndex) { - curNode = mSkeleton->GetNode(parentIndex); + curNode = m_skeleton->GetNode(parentIndex); parentIndex = curNode->GetParentIndex(); } @@ -217,9 +217,9 @@ namespace EMotionFX // get the parent node, or nullptr when it doesn't exist Node* Node::GetParentNode() const { - if (mParentIndex != InvalidIndex) + if (m_parentIndex != InvalidIndex) { - return mSkeleton->GetNode(mParentIndex); + return m_skeleton->GetNode(m_parentIndex); } return nullptr; @@ -231,11 +231,11 @@ namespace EMotionFX { if (name) { - mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } else { - mNameID = InvalidIndex32; + m_nameId = InvalidIndex32; } } @@ -245,53 +245,53 @@ namespace EMotionFX { if (name) { - mSemanticNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_semanticNameId = MCore::GetStringIdPool().GenerateIdForString(name); } else { - mSemanticNameID = InvalidIndex32; + m_semanticNameId = InvalidIndex32; } } 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 == InvalidIndex); + return (m_parentIndex == InvalidIndex); } @@ -299,110 +299,110 @@ namespace EMotionFX void Node::AddAttribute(NodeAttribute* attribute) { - mAttributes.emplace_back(attribute); + m_attributes.emplace_back(attribute); } size_t Node::GetNumAttributes() const { - return mAttributes.size(); + return m_attributes.size(); } NodeAttribute* Node::GetAttribute(size_t attributeNr) { // make sure we are in range - MCORE_ASSERT(attributeNr < mAttributes.size()); + MCORE_ASSERT(attributeNr < m_attributes.size()); // return the attribute - return mAttributes[attributeNr]; + return m_attributes[attributeNr]; } size_t Node::FindAttributeNumber(uint32 attributeTypeID) const { // check all attributes, and find where the specific attribute is - const auto foundAttribute = AZStd::find_if(begin(mAttributes), end(mAttributes), [attributeTypeID](const NodeAttribute* attribute) + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [attributeTypeID](const NodeAttribute* attribute) { return attribute->GetType() == attributeTypeID; }); - return foundAttribute != end(mAttributes) ? AZStd::distance(begin(mAttributes), foundAttribute) : InvalidIndex; + return foundAttribute != end(m_attributes) ? AZStd::distance(begin(m_attributes), foundAttribute) : InvalidIndex; } NodeAttribute* Node::GetAttributeByType(uint32 attributeType) { // check all attributes - const auto foundAttribute = AZStd::find_if(begin(mAttributes), end(mAttributes), [attributeType](const NodeAttribute* attribute) + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [attributeType](const NodeAttribute* attribute) { return attribute->GetType() == attributeType; }); - return foundAttribute != end(mAttributes) ? *foundAttribute : nullptr; + return foundAttribute != end(m_attributes) ? *foundAttribute : nullptr; } // remove the given attribute void Node::RemoveAttribute(size_t index) { - mAttributes.erase(AZStd::next(begin(mAttributes), index)); + m_attributes.erase(AZStd::next(begin(m_attributes), index)); } void Node::AddChild(size_t nodeIndex) { - mChildIndices.emplace_back(nodeIndex); + m_childIndices.emplace_back(nodeIndex); } void Node::SetChild(size_t childNr, size_t childNodeIndex) { - mChildIndices[childNr] = childNodeIndex; + m_childIndices[childNr] = childNodeIndex; } void Node::SetNumChildNodes(size_t numChildNodes) { - mChildIndices.resize(numChildNodes); + m_childIndices.resize(numChildNodes); } void Node::PreAllocNumChildNodes(size_t numChildNodes) { - mChildIndices.reserve(numChildNodes); + m_childIndices.reserve(numChildNodes); } void Node::RemoveChild(size_t nodeIndex) { - if (const auto it = AZStd::find(begin(mChildIndices), end(mChildIndices), nodeIndex); it != end(mChildIndices)) + if (const auto it = AZStd::find(begin(m_childIndices), end(m_childIndices), nodeIndex); it != end(m_childIndices)) { - mChildIndices.erase(it); + m_childIndices.erase(it); } } void Node::RemoveAllChildNodes() { - mChildIndices.clear(); + m_childIndices.clear(); } bool Node::GetHasChildNodes() const { - return !mChildIndices.empty(); + return !m_childIndices.empty(); } void Node::SetNodeIndex(size_t index) { - mNodeIndex = index; + m_nodeIndex = index; } void Node::SetSkeletalLODLevelBits(size_t bitValues) { - mSkeletalLODs = bitValues; + m_skeletalLoDs = bitValues; } @@ -411,11 +411,11 @@ namespace EMotionFX MCORE_ASSERT(lodLevel <= 63); if (enabled) { - mSkeletalLODs |= (1ull << lodLevel); + m_skeletalLoDs |= (1ull << lodLevel); } else { - mSkeletalLODs &= ~(1ull << lodLevel); + m_skeletalLoDs &= ~(1ull << lodLevel); } } @@ -424,11 +424,11 @@ namespace EMotionFX { if (includeThisNode) { - mNodeFlags |= FLAG_INCLUDEINBOUNDSCALC; + m_nodeFlags |= FLAG_INCLUDEINBOUNDSCALC; } else { - mNodeFlags &= ~FLAG_INCLUDEINBOUNDSCALC; + m_nodeFlags &= ~FLAG_INCLUDEINBOUNDSCALC; } } @@ -436,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; } @@ -455,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 19d9f53ff8..01dfacc28c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h @@ -92,7 +92,7 @@ namespace EMotionFX * 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 size_t GetParentIndex() const { return mParentIndex; } + MCORE_INLINE size_t GetParentIndex() const { return m_parentIndex; } /** * Get the parent node as node pointer. @@ -155,20 +155,20 @@ 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 size_t GetNumChildNodes() const { return mChildIndices.size(); } + MCORE_INLINE size_t GetNumChildNodes() const { return m_childIndices.size(); } /** * Get the number of child nodes down the hierarchy of this node. @@ -182,14 +182,14 @@ namespace EMotionFX * @param nr The child number. * @result The index of the child node, which is a node number inside the actor. */ - MCORE_INLINE size_t GetChildIndex(size_t 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(size_t nodeIndex) const { return (AZStd::find(begin(mChildIndices), end(mChildIndices), nodeIndex) != end(mChildIndices)); } + 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. @@ -336,7 +336,7 @@ namespace EMotionFX * So Actor::GetNode( nodeIndex ) will return this node. * @result The index of the node. */ - MCORE_INLINE size_t GetNodeIndex() const { return mNodeIndex; } + MCORE_INLINE size_t GetNodeIndex() const { return m_nodeIndex; } //------------------------------ @@ -364,7 +364,7 @@ namespace EMotionFX * @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(size_t lodLevel) const { return (mSkeletalLODs & (1ull << 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: - size_t mNodeIndex; /**< The node index, which is the index into the array of nodes inside the Skeleton class. */ - size_t mParentIndex; /**< The parent node index, or MCORE_INVALIDINDEX32 when there is no parent. */ - size_t 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. */ - AZStd::vector mChildIndices; /**< The indices that point to the child nodes. */ - AZStd::vector 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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp index cd2139ec9a..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) 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 b3e82e648b..7ee74415c0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h @@ -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 fb2fbd9ed7..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; } @@ -41,36 +41,36 @@ namespace EMotionFX // preallocate space void NodeMap::Reserve(size_t numEntries) { - mEntries.reserve(numEntries); + m_entries.reserve(numEntries); } // resize the entries array void NodeMap::Resize(size_t numEntries) { - mEntries.resize(numEntries); + m_entries.resize(numEntries); } // modify the first name of a given entry 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(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(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); } @@ -101,15 +101,15 @@ namespace EMotionFX void NodeMap::AddEntry(const char* firstName, const char* secondName) { MCORE_ASSERT(GetHasEntry(firstName) == false); // prevent duplicates - mEntries.emplace_back(); - SetEntry(mEntries.size() - 1, firstName, secondName); + m_entries.emplace_back(); + SetEntry(m_entries.size() - 1, firstName, secondName); } // remove a given entry by its index void NodeMap::RemoveEntryByIndex(size_t entryIndex) { - mEntries.erase(AZStd::next(begin(mEntries), entryIndex)); + m_entries.erase(AZStd::next(begin(m_entries), entryIndex)); } @@ -122,7 +122,7 @@ namespace EMotionFX return; } - mEntries.erase(AZStd::next(begin(mEntries), entryIndex)); + m_entries.erase(AZStd::next(begin(m_entries), entryIndex)); } @@ -135,28 +135,28 @@ namespace EMotionFX return; } - mEntries.erase(AZStd::next(begin(mEntries), 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; } @@ -211,7 +211,7 @@ namespace EMotionFX size_t numBytes = sizeof(FileFormat::NodeMapChunk); // for all entries - const size_t numEntries = mEntries.size(); + const size_t numEntries = m_entries.size(); for (size_t i = 0; i < numEntries; ++i) { numBytes += CalcFileStringSize(GetFirstNameString(i)); @@ -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 = aznumeric_caster(mEntries.size()); - 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 = aznumeric_caster(mEntries.size()); + const uint32 numEntries = aznumeric_caster(m_entries.size()); for (uint32 i = 0; i < numEntries; ++i) { if (WriteFileString(&f, GetFirstNameString(i), targetEndianType) == false) @@ -308,49 +308,49 @@ 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 size_t NodeMap::GetNumEntries() const { - return mEntries.size(); + return m_entries.size(); } // get the first name as char pointer 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(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(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(size_t entryIndex) const { - return MCore::GetStringIdPool().GetName(mEntries[entryIndex].mSecondNameID); + return MCore::GetStringIdPool().GetName(m_entries[entryIndex].m_secondNameId); } @@ -364,22 +364,22 @@ namespace EMotionFX // find an entry index by its name size_t NodeMap::FindEntryIndexByName(const char* firstName) const { - const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [firstName](const MapEntry& entry) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [firstName](const MapEntry& entry) { - return MCore::GetStringIdPool().GetName(entry.mFirstNameID) == firstName; + return MCore::GetStringIdPool().GetName(entry.m_firstNameId) == firstName; }); - return foundEntry != end(mEntries) ? AZStd::distance(begin(mEntries), foundEntry) : InvalidIndex; + return foundEntry != end(m_entries) ? AZStd::distance(begin(m_entries), foundEntry) : InvalidIndex; } // find an entry index by its name ID size_t NodeMap::FindEntryIndexByNameID(uint32 firstNameID) const { - const auto foundEntry = AZStd::find_if(begin(mEntries), end(mEntries), [firstNameID](const MapEntry& entry) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [firstNameID](const MapEntry& entry) { - return entry.mFirstNameID == firstNameID; + return entry.m_firstNameId == firstNameID; }); - return foundEntry != end(mEntries) ? AZStd::distance(begin(mEntries), foundEntry) : InvalidIndex; + return foundEntry != end(m_entries) ? AZStd::distance(begin(m_entries), foundEntry) : InvalidIndex; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h index 3fe2c94386..c0744323af 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h @@ -39,8 +39,8 @@ namespace EMotionFX public: struct MapEntry { - uint32 mFirstNameID = InvalidIndex32; /**< The first name ID, which is the primary key in the map. */ - uint32 mSecondNameID = InvalidIndex32; /**< The second name ID. */ + 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(); @@ -84,9 +84,9 @@ namespace EMotionFX bool Save(const char* fileName, MCore::Endian::EEndianType targetEndianType) const; private: - AZStd::vector 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 dbe57cdd34..02b3fd7649 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp @@ -510,15 +510,15 @@ namespace EMotionFX 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 b9f223eded..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 size_t 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 size_t 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 size_t oldSize = mFlags.GetLength(); - mFlags.ResizeFast(numTransforms); + const size_t oldSize = m_flags.GetLength(); + m_flags.ResizeFast(numTransforms); if (oldSize < numTransforms && clearAllFlags == false) { 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) { @@ -117,15 +111,15 @@ namespace EMotionFX void Pose::SetNumTransforms(size_t numTransforms) { // resize the buffers - mLocalSpaceTransforms.ResizeFast(numTransforms); - mModelSpaceTransforms.ResizeFast(numTransforms); + m_localSpaceTransforms.ResizeFast(numTransforms); + m_modelSpaceTransforms.ResizeFast(numTransforms); - const size_t oldSize = mFlags.GetLength(); - mFlags.ResizeFast(numTransforms); + const size_t oldSize = m_flags.GetLength(); + m_flags.ResizeFast(numTransforms); 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) { @@ -192,23 +171,23 @@ namespace EMotionFX // update the full local space pose void Pose::ForceUpdateFullLocalSpacePose() { - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); const size_t numNodes = skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { 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; } } @@ -217,21 +196,21 @@ namespace EMotionFX void Pose::ForceUpdateFullModelSpacePose() { // iterate from root towards child nodes recursively, updating all model space transforms on the way - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); const size_t numNodes = skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { 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; } } @@ -239,28 +218,28 @@ namespace EMotionFX // recursively update void Pose::UpdateModelSpaceTransform(size_t nodeIndex) const { - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); const size_t parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); - if (parentIndex != InvalidIndex && !(mFlags[parentIndex] & FLAG_MODELTRANSFORMREADY)) + 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 != 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; } } @@ -268,7 +247,7 @@ namespace EMotionFX // update the local transform void Pose::UpdateLocalSpaceTransform(size_t nodeIndex) const { - const uint8 flags = mFlags[nodeIndex]; + const uint8 flags = m_flags[nodeIndex]; if (flags & FLAG_LOCALTRANSFORMREADY) { return; @@ -276,20 +255,20 @@ namespace EMotionFX MCORE_ASSERT(flags & FLAG_MODELTRANSFORMREADY); // the model space transform has to be updated already, otherwise we cannot possibly calculate the local space one - Skeleton* skeleton = mActor->GetSkeleton(); + 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; } @@ -297,63 +276,63 @@ namespace EMotionFX const Transform& Pose::GetLocalSpaceTransform(size_t nodeIndex) const { UpdateLocalSpaceTransform(nodeIndex); - return mLocalSpaceTransforms[nodeIndex]; + return m_localSpaceTransforms[nodeIndex]; } const Transform& Pose::GetModelSpaceTransform(size_t nodeIndex) const { UpdateModelSpaceTransform(nodeIndex); - return mModelSpaceTransforms[nodeIndex]; + return m_modelSpaceTransforms[nodeIndex]; } 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(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(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(size_t nodeIndex, Transform* outResult) const { UpdateModelSpaceTransform(nodeIndex); - *outResult = mModelSpaceTransforms[nodeIndex]; + *outResult = m_modelSpaceTransforms[nodeIndex]; } // set the local transform 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); } } } @@ -363,13 +342,13 @@ namespace EMotionFX 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(); @@ -384,34 +363,34 @@ namespace EMotionFX 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(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); } @@ -419,38 +398,38 @@ namespace EMotionFX // invalidate all local transforms void Pose::InvalidateAllLocalSpaceTransforms() { - const size_t numFlags = mFlags.GetLength(); + 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 size_t numFlags = mFlags.GetLength(); + 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 size_t numFlags = mFlags.GetLength(); + 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 size_t motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); + MCORE_ASSERT(m_actor); + const size_t motionExtractionNodeIndex = m_actor->GetMotionExtractionNodeIndex(); if (motionExtractionNodeIndex == InvalidIndex) { return Transform::CreateIdentity(); @@ -462,7 +441,7 @@ namespace EMotionFX void Pose::UpdateAllLocalSpaceTranforms() { - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); const size_t numNodes = skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { @@ -473,7 +452,7 @@ namespace EMotionFX void Pose::UpdateAllModelSpaceTranforms() { - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); const size_t numNodes = skeleton->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { @@ -490,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 @@ -530,12 +509,12 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); 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 @@ -554,12 +533,12 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const size_t numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += destPose->mMorphWeights[i] * weight; + m_morphWeights[i] += destPose->m_morphWeights[i] * weight; } } } @@ -571,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); @@ -585,7 +564,7 @@ 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) @@ -610,12 +589,12 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const size_t numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); 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 @@ -640,12 +619,12 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const size_t numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += destPose->mMorphWeights[i] * weight; + m_morphWeights[i] += destPose->m_morphWeights[i] * weight; } } } @@ -656,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. @@ -739,35 +718,35 @@ namespace EMotionFX // reset all transforms to zero void Pose::Zero() { - if (mActorInstance) + if (m_actorInstance) { - const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const uint16 nodeNr = mActorInstance->GetEnabledNode(i); - mLocalSpaceTransforms[nodeNr].Zero(); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); + m_localSpaceTransforms[nodeNr].Zero(); } - const size_t numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); + 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 size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { - mLocalSpaceTransforms[i].Zero(); + m_localSpaceTransforms[i].Zero(); } - const size_t 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); for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] = 0.0f; + m_morphWeights[i] = 0.0f; } } @@ -778,23 +757,23 @@ namespace EMotionFX // normalize all quaternions void Pose::NormalizeQuaternions() { - if (mActorInstance) + if (m_actorInstance) { - const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const uint16 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 size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + 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(); } } } @@ -803,12 +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) { - const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const uint16 nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); const Transform& otherTransform = other->GetLocalSpaceTransform(nodeNr); @@ -816,17 +795,17 @@ namespace EMotionFX } // blend the morph weights - const size_t 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 (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += other->mMorphWeights[i] * weight; + m_morphWeights[i] += other->m_morphWeights[i] * weight; } } else { - const size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -835,12 +814,12 @@ namespace EMotionFX } // blend the morph weights - const size_t 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 (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += other->mMorphWeights[i] * weight; + m_morphWeights[i] += other->m_morphWeights[i] * weight; } } @@ -851,23 +830,23 @@ namespace EMotionFX // blend, without motion instance void Pose::Blend(const Pose* destPose, float weight) { - if (mActorInstance) + if (m_actorInstance) { - const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const uint16 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 size_t 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 (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) @@ -878,7 +857,7 @@ namespace EMotionFX } else { - const size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); for (size_t i = 0; i < numNodes; ++i) { Transform& curTransform = const_cast(GetLocalSpaceTransform(i)); @@ -886,12 +865,12 @@ namespace EMotionFX } // blend the morph weights - const size_t 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 (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) @@ -907,20 +886,20 @@ 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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const 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 size_t numNodes = mLocalSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.GetLength(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -928,11 +907,11 @@ namespace EMotionFX } } - const size_t 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 (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] -= other.mMorphWeights[i]; + m_morphWeights[i] -= other.m_morphWeights[i]; } InvalidateAllModelSpaceTransforms(); @@ -942,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"); } @@ -960,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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + 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 size_t numNodes = mLocalSpaceTransforms.GetLength(); + 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 size_t 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 (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += additivePose.mMorphWeights[i] * weight; + m_morphWeights[i] += additivePose.m_morphWeights[i] * weight; } InvalidateAllModelSpaceTransforms(); @@ -1010,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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + 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 size_t numNodes = mLocalSpaceTransforms.GetLength(); + 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 size_t 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 (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += additivePose.mMorphWeights[i]; + m_morphWeights[i] += additivePose.m_morphWeights[i]; } InvalidateAllModelSpaceTransforms(); @@ -1059,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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + 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 size_t numNodes = mLocalSpaceTransforms.GetLength(); + 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 size_t 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 (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] -= refPose.mMorphWeights[i]; + m_morphWeights[i] -= refPose.m_morphWeights[i]; } InvalidateAllModelSpaceTransforms(); @@ -1107,36 +1086,36 @@ 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; - const size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const uint16 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 size_t 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 (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 size_t numNodes = mActor->GetSkeleton()->GetNumNodes(); + 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); @@ -1144,12 +1123,12 @@ namespace EMotionFX } // blend the morph weights - const size_t 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 (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += destPose->mMorphWeights[i] * weight; + m_morphWeights[i] += destPose->m_morphWeights[i] * weight; } } @@ -1253,11 +1232,11 @@ namespace EMotionFX // compensate for motion extraction, basically making it in-place void Pose::CompensateForMotionExtractionDirect(EMotionExtractionFlags motionExtractionFlags) { - const size_t motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); + 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); } } @@ -1266,11 +1245,11 @@ namespace EMotionFX // compensate for motion extraction, basically making it in-place void Pose::CompensateForMotionExtraction(EMotionExtractionFlags motionExtractionFlags) { - const size_t motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); + 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); } } @@ -1279,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(); + 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]); } } } @@ -1295,29 +1274,29 @@ namespace EMotionFX // zero all morph weights void Pose::ZeroMorphWeights() { - const size_t numMorphs = mMorphWeights.GetLength(); + 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(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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const 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; @@ -1325,7 +1304,7 @@ namespace EMotionFX } else { - const size_t numNodes = mLocalSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.GetLength(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -1341,20 +1320,20 @@ 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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + 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 size_t numNodes = mLocalSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.GetLength(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -1369,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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + 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(); @@ -1384,7 +1363,7 @@ namespace EMotionFX } else { - const size_t numNodes = mLocalSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.GetLength(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -1401,15 +1380,15 @@ namespace EMotionFX 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); @@ -1419,21 +1398,21 @@ 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(); - 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 size_t numNodes = mActorInstance->GetNumEnabledNodes(); + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); for (size_t i = 0; i < numNodes; ++i) { - const size_t nodeNumber = mActorInstance->GetEnabledNode(i); + const size_t nodeNumber = m_actorInstance->GetEnabledNode(i); const size_t jointDataIndex = jointLinks[nodeNumber]; if (jointDataIndex == InvalidIndex) { @@ -1444,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 58dcb59ee4..32c7a33bd2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h @@ -87,7 +87,7 @@ 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(size_t lodLevel, size_t nodeIndex) const; @@ -98,25 +98,25 @@ 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 size_t 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(size_t nodeIndex) { return mLocalSpaceTransforms[nodeIndex]; } - MCORE_INLINE Transform& GetModelSpaceTransformDirect(size_t nodeIndex) { return mModelSpaceTransforms[nodeIndex]; } - MCORE_INLINE const Transform& GetLocalSpaceTransformDirect(size_t nodeIndex) const { return mLocalSpaceTransforms[nodeIndex]; } - MCORE_INLINE const Transform& GetModelSpaceTransformDirect(size_t nodeIndex) const { return mModelSpaceTransforms[nodeIndex]; } - MCORE_INLINE void SetLocalSpaceTransformDirect(size_t nodeIndex, const Transform& transform){ mLocalSpaceTransforms[nodeIndex] = transform; mFlags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; } - MCORE_INLINE void SetModelSpaceTransformDirect(size_t nodeIndex, const Transform& transform){ mModelSpaceTransforms[nodeIndex] = transform; mFlags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; } - MCORE_INLINE void InvalidateLocalSpaceTransform(size_t nodeIndex) { mFlags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; } - MCORE_INLINE void InvalidateModelSpaceTransform(size_t nodeIndex) { mFlags[nodeIndex] &= ~FLAG_MODELTRANSFORMREADY; } - - MCORE_INLINE void SetMorphWeight(size_t index, float weight) { mMorphWeights[index] = weight; } - MCORE_INLINE float GetMorphWeight(size_t index) const { return mMorphWeights[index]; } - MCORE_INLINE size_t GetNumMorphWeights() const { return mMorphWeights.GetLength(); } + 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); /** @@ -168,8 +168,8 @@ namespace EMotionFX Pose& operator=(const Pose& other); - MCORE_INLINE uint8 GetFlags(size_t nodeIndex) const { return mFlags[nodeIndex]; } - MCORE_INLINE void SetFlags(size_t 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,14 +193,14 @@ 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, size_t nodeIndex); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp index e5c3aa7d8c..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. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp index 87221c0bd2..c7da3430b1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp @@ -333,12 +333,12 @@ namespace EMotionFX 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,8 +349,8 @@ 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); @@ -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; } } @@ -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/Recorder.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp index 3eb32f24ce..085d164a94 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp @@ -48,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 ; } @@ -80,27 +80,27 @@ 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; + 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 size_t numActorInstances = GetActorManager().GetNumActorInstances(); - mRecordSettings.m_actorInstances.resize(numActorInstances); + 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 size_t numNodes = actorInstance->GetNumNodes(); actorInstanceData.m_transformTracks.resize(numNodes); 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 size_t numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); - actorInstanceData.mMorphTracks.resize(numMorphs); + 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,7 +381,7 @@ namespace EMotionFX { for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - const ActorInstance* actorInstance = actorInstanceData->mActorInstance; + const ActorInstance* actorInstance = actorInstanceData->m_actorInstance; if (actorInstanceData->m_transformTracks.empty()) { continue; @@ -390,12 +390,12 @@ namespace EMotionFX 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; } @@ -474,13 +474,13 @@ namespace EMotionFX for (size_t i = 0; i < numActorInstances; ++i) { ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[i]; - ActorInstance* actorInstance = actorInstanceData.mActorInstance; + ActorInstance* actorInstance = actorInstanceData.m_actorInstance; 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,7 +509,7 @@ namespace EMotionFX { for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - ActorInstance* actorInstance = actorInstanceData->mActorInstance; + ActorInstance* actorInstance = actorInstanceData->m_actorInstance; const TransformData* transformData = actorInstance->GetTransformData(); { @@ -519,9 +519,9 @@ namespace EMotionFX 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,43 +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 - AZStd::vector& frames = animGraphInstanceData.mFrames; + AZStd::vector& frames = animGraphInstanceData.m_frames; if (!frames.empty()) { - const size_t byteOffset = frames.back().mByteOffset + frames.back().mNumBytes; + const size_t byteOffset = frames.back().m_byteOffset + frames.back().m_numBytes; frames.emplace_back(); - frames.back().mByteOffset = byteOffset; - frames.back().mNumBytes = 0; + frames.back().m_byteOffset = byteOffset; + frames.back().m_numBytes = 0; } else { frames.emplace_back(); - frames.back().mByteOffset = 0; - frames.back().mNumBytes = 0; + frames.back().m_byteOffset = 0; + frames.back().m_numBytes = 0; } // get the current frame AnimGraphAnimFrame& currentFrame = frames.back(); - currentFrame.mTimeValue = mRecordTime; + currentFrame.m_timeValue = m_recordTime; // save the parameter values const size_t numParams = animGraphInstance->GetAnimGraph()->GetNumValueParameters(); - currentFrame.mParameterValues.resize(numParams); + currentFrame.m_parameterValues.resize(numParams); for (size_t p = 0; p < numParams; ++p) { - currentFrame.mParameterValues[p] = AZStd::unique_ptr(animGraphInstance->GetParameterValue(p)->Clone()); + currentFrame.m_parameterValues[p] = AZStd::unique_ptr(animGraphInstance->GetParameterValue(p)->Clone()); } // recursively save all unique datas @@ -581,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; @@ -594,52 +592,52 @@ namespace EMotionFX bool Recorder::SaveUniqueData(AnimGraphInstance* animGraphInstance, AnimGraphObject* object, AnimGraphInstanceData& animGraphInstanceData) { // get the current frame's data pointer - AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames.back(); - const size_t frameOffset = currentFrame.mByteOffset; + AnimGraphAnimFrame& currentFrame = animGraphInstanceData.m_frames.back(); + const size_t frameOffset = currentFrame.m_byteOffset; // prepare the objects array - mObjects.clear(); - 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 size_t numObjects = mObjects.size(); - 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 size_t requiredFrameBytes = 0; - for (const AnimGraphObject* animGraphObject : mObjects) + for (const AnimGraphObject* animGraphObject : m_objects) { 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 (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 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; } @@ -649,19 +647,19 @@ namespace EMotionFX 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 size_t 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, @@ -681,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); } } ) @@ -733,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()) { @@ -746,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()) { @@ -766,18 +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 = AZStd::distance(recordedActorInstances.begin(), iterator); const ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[index]; - const size_t numMorphs = actorInstanceData.mMorphTracks.size(); + const size_t numMorphs = actorInstanceData.m_morphTracks.size(); if (numMorphs == actorInstance->GetMorphSetupInstance()->GetNumMorphTargets()) { for (size_t i = 0; i < numMorphs; ++i) { - actorInstance->GetMorphSetupInstance()->GetMorphTarget(i)->SetWeight(actorInstanceData.mMorphTracks[i].GetValueAtTime(timeInSeconds)); + actorInstance->GetMorphSetupInstance()->GetMorphTarget(i)->SetWeight(actorInstanceData.m_morphTracks[i].GetValueAtTime(timeInSeconds)); } } } @@ -787,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)); } ) } @@ -805,7 +803,7 @@ 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 @@ -817,14 +815,14 @@ namespace EMotionFX 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); } ) @@ -843,25 +841,25 @@ namespace EMotionFX } // 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 size_t realFrameNumber = AZStd::min(frameNumber, animGraphInstanceData.mFrames.size() - 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 size_t byteOffset = currentFrame.mByteOffset; - const uint8* frameDataBuffer = &animGraphInstanceData.mDataBuffer[byteOffset]; - const AZStd::vector& 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.size() == animGraphInstance->GetAnimGraph()->GetNumParameters()); - const size_t numParameters = currentFrame.mParameterValues.size(); + 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].get()); + 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 @@ -870,25 +868,25 @@ namespace EMotionFX for (size_t a = 0; a < numObjects; ++a) { const AnimGraphAnimObjectInfo& objectInfo = frameObjects[a]; - const size_t 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(); } size_t Recorder::FindActorInstanceDataIndex(ActorInstance* actorInstance) const { const auto found = AZStd::find_if(begin(m_actorInstanceDatas), end(m_actorInstanceDatas), [actorInstance](const ActorInstanceData* data) { - return data->mActorInstance == actorInstance; + return data->m_actorInstance == actorInstance; }); return found != end(m_actorInstanceDatas) ? AZStd::distance(begin(m_actorInstanceDatas), found) : InvalidIndex; } @@ -899,46 +897,46 @@ 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 - AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; + AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; // finalize items for (NodeHistoryItem* curItem : historyItems) { - if (curItem->mIsFinalized) + if (curItem->m_isFinalized) { continue; } // check if we have an active node for the given item - const bool haveActiveNode = AZStd::find_if(begin(mActiveNodes), end(mActiveNodes), [curItem](const AnimGraphNode* activeNode) + const bool haveActiveNode = AZStd::find_if(begin(m_activeNodes), end(m_activeNodes), [curItem](const AnimGraphNode* activeNode) { - return activeNode->GetId() == curItem->mNodeId; - }) != end(mActiveNodes); + return activeNode->GetId() == curItem->m_nodeId; + }) != end(m_activeNodes); // the node got deactivated, finalize the item 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 (const AnimGraphNode* activeNode : mActiveNodes) + for (const AnimGraphNode* activeNode : m_activeNodes) { if (activeNode == animGraphInstance->GetRootNode()) // skip the root node { @@ -948,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()) { @@ -957,42 +955,42 @@ 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()) @@ -1001,8 +999,8 @@ namespace EMotionFX 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); } } @@ -1011,9 +1009,9 @@ namespace EMotionFX // 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(); @@ -1026,8 +1024,8 @@ 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 } @@ -1036,15 +1034,15 @@ namespace EMotionFX // try to find a given node history item Recorder::NodeHistoryItem* Recorder::FindNodeHistoryItem(const ActorInstanceData& actorInstanceData, const AnimGraphNode* node, float recordTime) const { - const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; for (NodeHistoryItem* curItem : historyItems) { - 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; } @@ -1057,7 +1055,7 @@ namespace EMotionFX // find a free track size_t Recorder::FindFreeNodeHistoryItemTrack(const ActorInstanceData& actorInstanceData, NodeHistoryItem* item) const { - const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; bool found = false; size_t trackIndex = 0; @@ -1067,23 +1065,23 @@ namespace EMotionFX for (const NodeHistoryItem* curItem : historyItems) { - 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; @@ -1091,7 +1089,7 @@ namespace EMotionFX } 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; @@ -1117,12 +1115,12 @@ namespace EMotionFX size_t Recorder::CalcMaxNodeHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const { size_t result = 0; - const AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; for (const NodeHistoryItem* curItem : historyItems) { - if (curItem->mTrackIndex > result) + if (curItem->m_trackIndex > result) { - result = curItem->mTrackIndex; + result = curItem->m_trackIndex; } } @@ -1134,12 +1132,12 @@ namespace EMotionFX size_t Recorder::CalcMaxEventHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const { size_t result = 0; - const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData.m_eventHistoryItems; for (const EventHistoryItem* curItem : historyItems) { - if (curItem->mTrackIndex > result) + if (curItem->m_trackIndex > result) { - result = curItem->mTrackIndex; + result = curItem->m_trackIndex; } } @@ -1169,28 +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 AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; // finalize all items for (NodeHistoryItem* historyItem : historyItems) { // remove unneeded key frames - if (historyItem->mIsFinalized == false) + if (historyItem->m_isFinalized == false) { - historyItem->mGlobalWeights.Optimize(0.0001f); - historyItem->mLocalWeights.Optimize(0.0001f); - historyItem->mPlayTimes.Optimize(0.0001f); - historyItem->mIsFinalized = true; + historyItem->m_globalWeights.Optimize(0.0001f); + historyItem->m_localWeights.Optimize(0.0001f); + historyItem->m_playTimes.Optimize(0.0001f); + historyItem->m_isFinalized = true; } } } @@ -1204,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; @@ -1214,7 +1212,7 @@ namespace EMotionFX const AnimGraphEventBuffer& eventBuffer = animGraphInstance->GetEventBuffer(); // iterate over all events - AZStd::vector& historyItems = actorInstanceData->mEventHistoryItems; + AZStd::vector& historyItems = actorInstanceData->m_eventHistoryItems; const size_t numEvents = eventBuffer.GetNumEvents(); for (size_t i = 0; i < numEvents; ++i) { @@ -1223,26 +1221,26 @@ namespace EMotionFX { 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.emplace_back(item); } - item->mEndTime = mRecordTime; + item->m_endTime = m_recordTime; } } } @@ -1252,10 +1250,10 @@ namespace EMotionFX Recorder::EventHistoryItem* Recorder::FindEventHistoryItem(const ActorInstanceData& actorInstanceData, const EventInfo& eventInfo, float recordTime) { MCORE_UNUSED(recordTime); - const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData.m_eventHistoryItems; for (const EventHistoryItem* curItem : historyItems) { - if (curItem->mStartTime < eventInfo.mTimeValue) + if (curItem->m_startTime < eventInfo.m_timeValue) { continue; } @@ -1268,7 +1266,7 @@ namespace EMotionFX // find a free event track index size_t Recorder::FindFreeEventHistoryItemTrack(const ActorInstanceData& actorInstanceData, EventHistoryItem* item) const { - const AZStd::vector& historyItems = actorInstanceData.mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData.m_eventHistoryItems; bool found = false; size_t trackIndex = 0; while (found == false) @@ -1277,12 +1275,12 @@ namespace EMotionFX for (const EventHistoryItem* curItem : historyItems) { - 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; @@ -1314,13 +1312,13 @@ 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 InvalidIndex; } - const size_t numFrames = animGraphData->mFrames.size(); + const size_t numFrames = animGraphData->m_frames.size(); if (numFrames == 0) { return InvalidIndex; @@ -1335,16 +1333,16 @@ namespace EMotionFX return 0; } - if (timeValue > animGraphData->mFrames.back().mTimeValue) + if (timeValue > animGraphData->m_frames.back().m_timeValue) { - return animGraphData->mFrames.size() - 1; + return animGraphData->m_frames.size() - 1; } 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; } @@ -1358,7 +1356,7 @@ 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()); @@ -1366,7 +1364,7 @@ namespace EMotionFX // Remove the actual recorded data. 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)); @@ -1386,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; } } @@ -1411,12 +1409,12 @@ namespace EMotionFX void Recorder::Lock() { - mLock.Lock(); + m_lock.Lock(); } void Recorder::Unlock() { - mLock.Unlock(); + m_lock.Unlock(); } @@ -1429,44 +1427,44 @@ namespace EMotionFX for (size_t i = 0; i <= maxIndex; ++i) { ExtractedNodeHistoryItem item; - item.mTrackIndex = i; - item.mValue = 0.0f; - item.mKeyTrackSampleTime = 0.0f; - item.mNodeHistoryItem = nullptr; + 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 AZStd::vector& historyItems = actorInstanceData.mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; for (NodeHistoryItem* curItem : historyItems) { - 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->emplace(AZStd::next(begin(*outItems), curItem->mTrackIndex), item); + outItems->emplace(AZStd::next(begin(*outItems), curItem->m_trackIndex), item); } } @@ -1484,7 +1482,7 @@ namespace EMotionFX for (size_t i = 0; i <= maxIndex; ++i) { - outMap->emplace(AZStd::next(begin(*outMap), outItems->at(i).mTrackIndex), i); + outMap->emplace(AZStd::next(begin(*outMap), outItems->at(i).m_trackIndex), i); } } } @@ -1499,13 +1497,13 @@ namespace EMotionFX const size_t maxNumTracks = static_cast(CalcMaxNodeHistoryTrackIndex()) + 1; trackFlags.resize(maxNumTracks); - const size_t numNodeHistoryItems = actorInstanceData.mNodeHistoryItems.size(); + 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; } @@ -1518,32 +1516,32 @@ namespace EMotionFX // We at least have a single active motion. size_t intermediateResult = 1; - trackFlags[item->mTrackIndex] = true; + trackFlags[item->m_trackIndex] = true; 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; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h index 7d76b09483..fe87d36ea1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h @@ -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). */ - size_t 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; - size_t mEventIndex; /**< The index to use in combination with GetEventManager().GetEvent(index). */ - size_t 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 = InvalidIndex; - mTrackIndex = InvalidIndex; - 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 - size_t mTrackIndex; // the track index - size_t 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 = InvalidIndex; - mCachedKey = InvalidIndex; - 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; - size_t 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,38 +183,38 @@ 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 { - size_t mFrameByteOffset; - AnimGraphObject* mObject; + size_t m_frameByteOffset; + AnimGraphObject* m_object; }; struct EMFX_API AnimGraphAnimFrame { - float mTimeValue = 0.0f; - size_t mByteOffset = 0; - size_t mNumBytes = 0; - AZStd::vector mObjectInfos{}; - AZStd::vector> mParameterValues{}; + float m_timeValue = 0.0f; + size_t m_byteOffset = 0; + size_t m_numBytes = 0; + AZStd::vector m_objectInfos{}; + AZStd::vector> m_parameterValues{}; }; struct EMFX_API AnimGraphInstanceData { - AnimGraphInstance* mAnimGraphInstance = nullptr; - size_t mNumFrames = 0; - size_t mDataBufferSize = 0; - uint8* mDataBuffer = nullptr; - AZStd::vector mFrames{}; + 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; @@ -224,16 +224,16 @@ namespace EMotionFX { return; } - mAnimGraphInstance = rhs.mAnimGraphInstance; - mNumFrames = rhs.mNumFrames; - mDataBufferSize = rhs.mDataBufferSize; - mDataBuffer = rhs.mDataBuffer; - mFrames = AZStd::move(rhs.mFrames); - rhs.mAnimGraphInstance = nullptr; - rhs.mNumFrames = 0; - rhs.mDataBufferSize = 0; - rhs.mDataBuffer = nullptr; - rhs.mFrames = {}; + 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 = {}; } AnimGraphInstanceData& operator=(const AnimGraphInstanceData&) = delete; @@ -243,22 +243,22 @@ namespace EMotionFX { return *this; } - mAnimGraphInstance = rhs.mAnimGraphInstance; - mNumFrames = rhs.mNumFrames; - mDataBufferSize = rhs.mDataBufferSize; - mDataBuffer = rhs.mDataBuffer; - mFrames = AZStd::move(rhs.mFrames); - rhs.mAnimGraphInstance = nullptr; - rhs.mNumFrames = 0; - rhs.mDataBufferSize = 0; - rhs.mDataBuffer = nullptr; - rhs.mFrames = {}; + 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); } }; @@ -267,40 +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 - AZStd::vector mNodeHistoryItems; // node history items - AZStd::vector mEventHistoryItems; // event history item - TransformTracks mActorLocalTransform; // the actor instance's local transformation - AZStd::vector< 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.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 - for (NodeHistoryItem* nodeHistoryItem : mNodeHistoryItems) + for (NodeHistoryItem* nodeHistoryItem : m_nodeHistoryItems) { delete nodeHistoryItem; } - mNodeHistoryItems.clear(); + m_nodeHistoryItems.clear(); // clear the event history items - for (auto & eventHistoryItem : mEventHistoryItems) + for (auto & eventHistoryItem : m_eventHistoryItems) { delete eventHistoryItem; } - mEventHistoryItems.clear(); + m_eventHistoryItems.clear(); - delete mAnimGraphData; + delete m_animGraphData; } static void Reflect(AZ::ReflectContext* context); @@ -334,13 +334,13 @@ 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; } @@ -367,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 - AZStd::vector 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(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp index 6bbf60700b..1e3171d419 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp @@ -26,7 +26,7 @@ namespace EMotionFX RepositioningLayerPass::RepositioningLayerPass(MotionLayerSystem* motionLayerSystem) : LayerPass(motionLayerSystem) { - mLastReposNode = InvalidIndex; + m_lastReposNode = InvalidIndex; } @@ -53,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()); @@ -63,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; @@ -77,10 +77,10 @@ namespace EMotionFX // Bottom up traversal of the layers. bool firstBlend = true; - const size_t numMotionInstances = mMotionSystem->GetNumMotionInstances(); + 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 4df680092a..333749141a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h @@ -59,8 +59,8 @@ namespace EMotionFX private: - AZStd::vector mHierarchyPath; /**< The path of node indices to the repositioning node. */ - size_t 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/SingleThreadScheduler.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp index 0e871499df..f5ba7856ac 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp @@ -45,9 +45,9 @@ 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 size_t numRootActorInstances = GetActorManager().GetNumRootActorInstances(); @@ -81,7 +81,7 @@ namespace EMotionFX { actorInstance->SetThreadIndex(0); - mNumUpdated.Increment(); + m_numUpdated.Increment(); const bool isVisible = actorInstance->GetIsVisible(); @@ -95,13 +95,13 @@ namespace EMotionFX if (isVisible) { - mNumSampled.Increment(); + m_numSampled.Increment(); } } if (isVisible) { - mNumVisible.Increment(); + m_numVisible.Increment(); } // update the transformations diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp index 4483d98e40..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); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h index 48eeabac77..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,14 +157,14 @@ 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. @@ -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 004e415501..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(); } @@ -67,8 +67,8 @@ namespace EMotionFX 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 size_t 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 @@ -209,24 +209,21 @@ namespace EMotionFX 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 @@ -246,17 +243,14 @@ namespace EMotionFX if (boneIndex == InvalidIndex) { // add the bone to the array of bones in this deformer - mNodeNumbers.emplace_back(influence->GetNodeNr()); - mBoneMatrices.emplace_back(mat); - boneIndex = 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 466f1702a7..ce157baf49 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h @@ -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 size_t GetLocalBone(size_t 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(size_t 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,12 +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 size_t FindLocalBoneIndex(size_t nodeIndex) const { - const auto foundBoneIndex = AZStd::find(begin(mNodeNumbers), end(mNodeNumbers), nodeIndex); - return foundBoneIndex != end(mNodeNumbers) ? AZStd::distance(begin(mNodeNumbers), foundBoneIndex) : InvalidIndex; + 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 8765a0e991..83cbc41a36 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp @@ -412,7 +412,7 @@ namespace EMotionFX 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) @@ -562,7 +562,7 @@ 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 = m_parentParticle; m_particles.emplace_back(particle); @@ -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(); } @@ -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,17 +816,17 @@ 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; } @@ -839,7 +839,7 @@ namespace EMotionFX } 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); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp index 5f5c439f7c..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,16 +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; + 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; } @@ -384,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 size_t numLayers = mLayers.size(); - standardMaterial->mLayers.resize(numLayers); + 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 @@ -418,9 +418,9 @@ namespace EMotionFX { layer->Destroy(); } - if (const auto it = AZStd::find(begin(mLayers), end(mLayers), layer); it != end(mLayers)) + if (const auto it = AZStd::find(begin(m_layers), end(m_layers), layer); it != end(m_layers)) { - mLayers.erase(it); + m_layers.erase(it); } } } @@ -428,180 +428,180 @@ namespace EMotionFX 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.emplace_back(layer); + m_layers.emplace_back(layer); return layer; } size_t StandardMaterial::GetNumLayers() const { - return mLayers.size(); + return m_layers.size(); } StandardMaterialLayer* StandardMaterial::GetLayer(size_t nr) { - MCORE_ASSERT(nr < mLayers.size()); - return mLayers[nr]; + MCORE_ASSERT(nr < m_layers.size()); + return m_layers[nr]; } void StandardMaterial::RemoveLayer(size_t nr, bool delFromMem) { - MCORE_ASSERT(nr < mLayers.size()); + MCORE_ASSERT(nr < m_layers.size()); if (delFromMem) { - mLayers[nr]->Destroy(); + m_layers[nr]->Destroy(); } - mLayers.erase(AZStd::next(begin(mLayers), nr)); + m_layers.erase(AZStd::next(begin(m_layers), nr)); } void StandardMaterial::RemoveAllLayers() { - for (StandardMaterialLayer* layer : mLayers) + for (StandardMaterialLayer* layer : m_layers) { layer->Destroy(); } - mLayers.clear(); + m_layers.clear(); } size_t StandardMaterial::FindLayer(uint32 layerType) const { // search through all layers - const auto foundLayer = AZStd::find_if(begin(mLayers), end(mLayers), [layerType](const StandardMaterialLayer* layer) + const auto foundLayer = AZStd::find_if(begin(m_layers), end(m_layers), [layerType](const StandardMaterialLayer* layer) { return layer->GetType() == layerType; }); - return foundLayer != end(mLayers) ? AZStd::distance(begin(mLayers), foundLayer) : InvalidIndex; + return foundLayer != end(m_layers) ? AZStd::distance(begin(m_layers), foundLayer) : InvalidIndex; } 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 05f8154a72..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. @@ -471,17 +471,17 @@ namespace EMotionFX protected: - AZStd::vector< 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 d18006527f..548816b82c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp @@ -21,14 +21,14 @@ namespace EMotionFX // constructor 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; + 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); } @@ -50,8 +50,8 @@ namespace EMotionFX // clone the submesh SubMesh* SubMesh::Clone(Mesh* newParentMesh) { - SubMesh* clone = aznew SubMesh(newParentMesh, mStartVertex, mStartIndex, mStartPolygon, mNumVertices, mNumIndices, mNumPolygons, mMaterial, mBones.size()); - 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; } @@ -59,7 +59,7 @@ namespace EMotionFX // remap bone (oldNodeNr) to bone (newNodeNr) void SubMesh::RemapBone(size_t oldNodeNr, size_t newNodeNr) { - AZStd::replace(mBones.begin(), mBones.end(), oldNodeNr, newNodeNr); + AZStd::replace(m_bones.begin(), m_bones.end(), oldNodeNr, newNodeNr); } @@ -67,10 +67,10 @@ namespace EMotionFX void SubMesh::ReinitBonesArray(SkinningInfoVertexAttributeLayer* skinLayer) { // clear the bones array - mBones.clear(); + 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(); @@ -89,9 +89,9 @@ namespace EMotionFX const uint16 nodeNr = influence->GetNodeNr(); // put the node index in the bones array in case it isn't in already - if (AZStd::find(begin(mBones), end(mBones), nodeNr) == end(mBones)) + if (AZStd::find(begin(m_bones), end(m_bones), nodeNr) == end(m_bones)) { - mBones.emplace_back(nodeNr); + m_bones.emplace_back(nodeNr); } } } @@ -116,118 +116,118 @@ 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; } size_t SubMesh::FindBoneIndex(size_t nodeNr) const { - const auto foundBone = AZStd::find(mBones.begin(), mBones.end(), nodeNr); - return foundBone != mBones.end() ? AZStd::distance(mBones.begin(), foundBone) : InvalidIndex; + 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(size_t index) { - mBones.erase(AZStd::next(begin(mBones), index)); + m_bones.erase(AZStd::next(begin(m_bones), index)); } @@ -235,17 +235,17 @@ namespace EMotionFX { if (numBones == 0) { - mBones.clear(); + m_bones.clear(); } else { - mBones.resize(numBones); + m_bones.resize(numBones); } } 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 d234a9e4c1..57e3f2b486 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h @@ -191,35 +191,35 @@ namespace EMotionFX * Get the number of bones used by this submesh. * @result The number of bones used by this submesh. */ - MCORE_INLINE size_t GetNumBones() const { return mBones.size(); } + 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 size_t GetBone(size_t 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 size_t* GetBones() { return mBones.data(); } + 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 AZStd::vector& 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 AZStd::vector& GetBonesArray() { return mBones; } + MCORE_INLINE AZStd::vector& GetBonesArray() { return m_bones; } /** * Reinitialize the bones. @@ -268,15 +268,15 @@ namespace EMotionFX protected: - AZStd::vector 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. 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 cf66a1543e..3ad8ae605a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h @@ -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 5164f97c01..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,7 +69,7 @@ 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 size_t numNodes = actorInstance->GetNumNodes(); @@ -79,23 +79,23 @@ namespace EMotionFX 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 (size_t i = 0; i < numNodes; ++i) { - mSkinningMatrices[i] = AZ::Matrix3x4::CreateIdentity(); + m_skinningMatrices[i] = AZ::Matrix3x4::CreateIdentity(); } } @@ -103,16 +103,16 @@ 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(); } @@ -121,7 +121,7 @@ namespace EMotionFX // set the scaling value for the node and all child nodes 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 @@ -141,15 +141,15 @@ namespace EMotionFX // update the local space 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(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 d4e70134a3..71c2ee6446 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h @@ -64,33 +64,33 @@ 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(size_t 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 (size_t 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)); } } @@ -100,8 +100,8 @@ namespace EMotionFX void SetBindPoseLocalScale(size_t nodeIndex, const AZ::Vector3& scale); ) - MCORE_INLINE const ActorInstance* GetActorInstance() const { return mPose.GetActorInstance(); } - MCORE_INLINE size_t 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(); @@ -109,11 +109,11 @@ namespace EMotionFX 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. */ - size_t 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/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 2f557ad290..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 size_t numPlugins = mPluginManager->GetNumPlugins(); + const size_t numPlugins = m_pluginManager->GetNumPlugins(); if (numPlugins) { AZ::SerializeContext* serializeContext = nullptr; @@ -190,31 +190,31 @@ namespace EMStudio { 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(); } @@ -432,7 +432,7 @@ namespace EMStudio } // add and return the manipulator - mTransformationManipulators.emplace_back(manipulator); + m_transformationManipulators.emplace_back(manipulator); return manipulator; } @@ -440,9 +440,9 @@ namespace EMStudio // remove the given gizmo from the array void EMStudioManager::RemoveTransformationManipulator(MCommon::TransformationManipulator* manipulator) { - if (const auto it = AZStd::find(begin(mTransformationManipulators), end(mTransformationManipulators), manipulator); it != end(mTransformationManipulators)) + if (const auto it = AZStd::find(begin(m_transformationManipulators), end(m_transformationManipulators), manipulator); it != end(m_transformationManipulators)) { - mTransformationManipulators.erase(it); + m_transformationManipulators.erase(it); } } @@ -450,7 +450,7 @@ namespace EMStudio // returns the gizmo array 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 95dbd3012a..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); @@ -99,7 +99,7 @@ namespace EMStudio 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); @@ -108,29 +108,29 @@ namespace EMStudio 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: - AZStd::vector mTransformationManipulators; - QPointer mMainWindow; - QApplication* mApp; - PluginManager* mPluginManager; - LayoutManager* mLayoutManager; - NotificationWindowManager* mNotificationWindowManager; - CommandSystem::CommandManager* mCommandManager; - AZStd::string mCompileDate; + 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 mWorkspace; - bool mAutoLoadLastWorkspace; - AZStd::string mHTMLLinkString; - bool mAvoidRendering; - bool mIgnoreVisible = false; - MotionEventPresetManager* mEventPresetManager; + 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 @@ -150,7 +150,7 @@ namespace EMStudio 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 dcb7c46fe5..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(); @@ -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,14 +557,14 @@ 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; } @@ -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 50dfce390a..98d7de188d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h @@ -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 eed352ad7c..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 = aznumeric_caster(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; } @@ -345,7 +332,7 @@ namespace EMStudio 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 c5781ebf12..8ca4e1de81 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp @@ -99,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); } } @@ -113,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()) @@ -183,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); @@ -222,7 +222,7 @@ namespace EMStudio text += "

"; } - mTextEdit->setText(text.c_str()); + m_textEdit->setText(text.c_str()); } MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) @@ -232,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(); @@ -280,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(); @@ -363,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); @@ -373,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(); @@ -401,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(); @@ -416,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")); @@ -443,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")); @@ -483,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(); @@ -514,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(); @@ -541,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() @@ -965,7 +965,7 @@ namespace EMStudio void MainWindow::OnWorkspaceSaved(const char* filename) { - mRecentWorkspaces.AddRecentFile(filename); + m_recentWorkspaces.AddRecentFile(filename); SetWindowTitleFromFileName(filename); } @@ -975,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); } @@ -1052,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); } @@ -1100,7 +1100,7 @@ namespace EMStudio AZStd::sort(begin(sortedPlugins), end(sortedPlugins)); // clear the window menu - mCreateWindowMenu->clear(); + m_createWindowMenu->clear(); // for all registered plugins, create a menu items for (size_t p = 0; p < numPlugins; ++p) @@ -1120,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 @@ -1144,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); } } } @@ -1210,16 +1210,16 @@ 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 size_t numPlugins = pluginManager->GetNumActivePlugins(); @@ -1247,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(); } @@ -1261,7 +1261,7 @@ namespace EMStudio { // open the config file QSettings settings(this); - mOptions.Save(settings, *this); + m_options.Save(settings, *this); } @@ -1270,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) @@ -1321,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()); @@ -1346,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); @@ -1396,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) @@ -1429,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(); } @@ -1449,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; } @@ -1491,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; @@ -1503,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; } @@ -1552,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; } @@ -1643,7 +1643,7 @@ namespace EMStudio void MainWindow::OnReset() { - if (mDirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) { return; } @@ -1673,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(); } @@ -1727,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()) { @@ -1750,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()) { @@ -1829,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"); @@ -1840,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(); @@ -1857,36 +1857,36 @@ namespace EMStudio if (extension == "layout") { AzFramework::StringFunc::Path::GetFileName(filename.c_str(), filename); - mLayoutNames.emplace_back(filename); + m_layoutNames.emplace_back(filename); } } // add each menu - for (const AZStd::string& layoutName : mLayoutNames) + for (const AZStd::string& layoutName : m_layoutNames) { - QAction* action = mLayoutsMenu->addAction(layoutName.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 (!mLayoutNames.empty()) + 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 (!mLayoutNames.empty()) + 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 (const AZStd::string& layoutName : mLayoutNames) + 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. @@ -1900,26 +1900,26 @@ namespace EMStudio } // disable signals to avoid to switch of layout - mApplicationMode->blockSignals(true); + m_applicationMode->blockSignals(true); // update the combo box - mApplicationMode->clear(); - for (const AZStd::string& layoutName : mLayoutNames) + m_applicationMode->clear(); + for (const AZStd::string& layoutName : m_layoutNames) { - mApplicationMode->addItem(layoutName.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 { @@ -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); @@ -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,10 +2457,10 @@ 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(); @@ -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 size_t animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(dirtyObjects[i].mAnimGraph); + 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); 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 d49d47452b..734dd7840d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h @@ -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; } - size_t GetNumLayouts() const { return mLayoutNames.size(); } - 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) - AZStd::vector 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 { 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 e189b98dcf..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,10 +85,10 @@ namespace EMStudio return; } - mListWidget->blockSignals(true); - mListWidget->clear(); + m_listWidget->blockSignals(true); + m_listWidget->clear(); - mSelection = selection; + m_selection = selection; const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); for (size_t i = 0; i < numMorphTargets; ++i) @@ -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 a5e3a64f1f..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,12 +106,12 @@ 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 { @@ -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 { @@ -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,11 +302,11 @@ namespace EMStudio void MotionSetHierarchyWidget::UpdateSelection() { // Get the selected items in the tree widget. - QList selectedItems = mHierarchy->selectedItems(); + QList selectedItems = m_hierarchy->selectedItems(); // Reset the selection. - mSelected.clear(); - mSelected.reserve(selectedItems.size()); + m_selected.clear(); + m_selected.reserve(selectedItems.size()); AZStd::string motionId; for (const QTreeWidgetItem* item : selectedItems) @@ -325,7 +325,7 @@ namespace EMStudio } MotionSetSelectionItem selectionItem(motionId, motionSet); - mSelected.push_back(selectionItem); + m_selected.push_back(selectionItem); } } @@ -334,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; } @@ -364,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; } @@ -384,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); } } @@ -395,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 1aa8082f08..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,10 +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")); + 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); @@ -67,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; @@ -75,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)) ); @@ -133,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 AZStd::vector& actorInstanceIDs, CommandSystem::SelectionList* selectionList) { - mActorInstanceIDs = actorInstanceIDs; + m_actorInstanceIDs = actorInstanceIDs; ConvertFromSelectionList(selectionList); Update(); @@ -151,7 +151,7 @@ namespace EMStudio void NodeHierarchyWidget::Update(uint32 actorInstanceID, CommandSystem::SelectionList* selectionList) { - mActorInstanceIDs.clear(); + m_actorInstanceIDs.clear(); if (actorInstanceID == MCORE_INVALIDINDEX32) { @@ -167,27 +167,27 @@ namespace EMStudio continue; } - mActorInstanceIDs.emplace_back(actorInstance->GetID()); + m_actorInstanceIDs.emplace_back(actorInstance->GetID()); } } else { - mActorInstanceIDs.emplace_back(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 - for (const uint32 actorInstanceID : mActorInstanceIDs) + for (const uint32 actorInstanceID : m_actorInstanceIDs) { // get the actor instance by its id EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); @@ -197,7 +197,7 @@ namespace EMStudio } } - mHierarchy->blockSignals(false); + m_hierarchy->blockSignals(false); // after we refilled everything, update the selection UpdateSelection(); @@ -212,13 +212,13 @@ namespace EMStudio 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())) @@ -232,11 +232,11 @@ 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 size_t numRootNodes = actor->GetSkeleton()->GetNumRootNodes(); @@ -264,7 +264,7 @@ namespace EMStudio AZStd::to_lower(nodeName.begin(), nodeName.end()); EMotionFX::Mesh* mesh = actorInstance->GetActor()->GetMesh(actorInstance->GetLODLevel(), nodeIndex); const bool isMeshNode = (mesh); - const bool isBone = (AZStd::find(begin(mBoneList), end(mBoneList), nodeIndex) != end(mBoneList)); + 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); @@ -293,7 +293,7 @@ namespace EMStudio const size_t numChildren = node->GetNumChildNodes(); EMotionFX::Mesh* mesh = actor->GetMesh(actorInstance->GetLODLevel(), nodeIndex); const bool isMeshNode = (mesh); - const bool isBone = (AZStd::find(begin(mBoneList), end(mBoneList), nodeIndex) != end(mBoneList)); + 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)) @@ -314,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 @@ -336,13 +336,13 @@ 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); @@ -384,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); @@ -405,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); @@ -430,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(); } @@ -452,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 @@ -480,24 +480,24 @@ namespace EMStudio void NodeHierarchyWidget::UpdateSelection() { // get the selected items and the number of them - QList selectedItems = mHierarchy->selectedItems(); + QList selectedItems = m_hierarchy->selectedItems(); // remove the unselected tree widget items from the selected nodes - const int numTopLevelItems = mHierarchy->topLevelItemCount(); + 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 (const QTreeWidgetItem* item : selectedItems) { // get the item name - FromQtString(item->text(0), &mItemName); - FromQtString(item->whatsThis(0), &mActorInstanceIDString); + 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); @@ -509,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 @@ -528,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; } @@ -571,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 @@ -581,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; @@ -592,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()); } } @@ -607,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(); @@ -632,7 +631,7 @@ namespace EMStudio { return AZStd::any_of(begin(m_selectedNodes), end(m_selectedNodes), [nodeName, actorInstanceID](const SelectionItem& selectedItem) { - return selectedItem.mActorInstanceID == actorInstanceID && selectedItem.GetNodeNameString() == nodeName; + return selectedItem.m_actorInstanceId == actorInstanceID && selectedItem.GetNodeNameString() == nodeName; }); } @@ -642,7 +641,7 @@ namespace EMStudio { return AZStd::any_of(begin(m_selectedNodes), end(m_selectedNodes), [actorInstanceID](const SelectionItem& selectedItem) { - return selectedItem.mActorInstanceID == actorInstanceID && selectedItem.GetNodeNameString().empty(); + return selectedItem.m_actorInstanceId == actorInstanceID && selectedItem.GetNodeNameString().empty(); }); } @@ -659,7 +658,7 @@ namespace EMStudio m_selectedNodes.clear(); // get the number actor instances and iterate over them - for (const uint32 actorInstanceID : mActorInstanceIDs) + for (const uint32 actorInstanceID : m_actorInstanceIDs) { // add the actor to the node hierarchy widget // get the number of selected nodes and iterate through them @@ -670,7 +669,7 @@ namespace EMStudio if (joint) { SelectionItem selectionItem; - selectionItem.mActorInstanceID = actorInstanceID; + selectionItem.m_actorInstanceId = actorInstanceID; selectionItem.SetNodeName(joint->GetName()); m_selectedNodes.emplace_back(selectionItem); } @@ -681,19 +680,19 @@ 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); } } // namespace EMStudio 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 e4dd215819..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; }; @@ -70,7 +70,7 @@ namespace EMStudio void Update(uint32 actorInstanceID, 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? @@ -126,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; - AZStd::vector mBoneList; - AZStd::vector 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 e0d562ee0f..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,35 +28,35 @@ 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); @@ -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 46eabf7b58..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(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); + * 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 AZStd::vector& 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(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 e1c22ee60d..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,7 +33,7 @@ namespace EMStudio // compute the height of all notification windows with the spacing int allNotificationWindowsHeight = 0; - for (const NotificationWindow* currentNotificationWindow : mNotificationWindows) + for (const NotificationWindow* currentNotificationWindow : m_notificationWindows) { allNotificationWindowsHeight += currentNotificationWindow->geometry().height() + notificationWindowSpacing; } @@ -44,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.emplace_back(notificationWindow); + m_notificationWindows.emplace_back(notificationWindow); } @@ -52,24 +52,24 @@ namespace EMStudio void NotificationWindowManager::RemoveNotificationWindow(NotificationWindow* notificationWindow) { // find the notification window - auto windowIt = AZStd::find(begin(mNotificationWindows), end(mNotificationWindows), notificationWindow); + auto windowIt = AZStd::find(begin(m_notificationWindows), end(m_notificationWindows), notificationWindow); // if not found, stop here - if (windowIt == end(mNotificationWindows)) + 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; - for (auto it = windowIt + 1; it != end(mNotificationWindows); ++it) + for (auto it = windowIt + 1; it != end(m_notificationWindows); ++it) { const QPoint pos = (*it)->pos(); (*it)->move(pos.x(), pos.y() + notificationWindowHeight); } // remove the notification window - mNotificationWindows.erase(windowIt); + m_notificationWindows.erase(windowIt); } @@ -81,7 +81,7 @@ namespace EMStudio // move each notification window int currentNotificationWindowHeight = notificationWindowMainWindowPadding; - for (NotificationWindow* notificationWindow : mNotificationWindows) + for (NotificationWindow* notificationWindow : m_notificationWindows) { // add the height of the notification window currentNotificationWindowHeight += notificationWindow->geometry().height(); 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 8817f3d451..4724b4ba54 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.h @@ -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 size_t GetNumNotificationWindow() const { - return mNotificationWindows.size(); + 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: - AZStd::vector 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 d0e8730e52..fde4336a49 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp @@ -34,8 +34,8 @@ namespace EMStudio // constructor PluginManager::PluginManager() { - mActivePlugins.reserve(50); - mPlugins.reserve(50); + m_activePlugins.reserve(50); + m_plugins.reserve(50); } @@ -50,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; } @@ -74,22 +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 - for (auto plugin = mActivePlugins.rbegin(); plugin != mActivePlugins.rend(); ++plugin) + for (auto plugin = m_activePlugins.rbegin(); plugin != m_activePlugins.rend(); ++plugin) { - for (EMStudioPlugin* pluginToNotify : mActivePlugins) + for (EMStudioPlugin* pluginToNotify : m_activePlugins) { pluginToNotify->OnBeforeRemovePlugin((*plugin)->GetClassID()); } delete *plugin; - mActivePlugins.pop_back(); + m_activePlugins.pop_back(); } } @@ -97,7 +97,7 @@ namespace EMStudio // register the plugin void PluginManager::RegisterPlugin(EMStudioPlugin* plugin) { - mPlugins.push_back(plugin); + m_plugins.push_back(plugin); } @@ -112,7 +112,7 @@ namespace EMStudio } // create the new plugin of this type - EMStudioPlugin* newPlugin = mPlugins[ pluginIndex ]->Clone(); + EMStudioPlugin* newPlugin = m_plugins[ pluginIndex ]->Clone(); // init the plugin newPlugin->CreateBaseInterface(objectName); @@ -120,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(); @@ -131,20 +131,20 @@ namespace EMStudio // find a given plugin by its name (type string) size_t PluginManager::FindPluginByTypeString(const char* pluginType) const { - const auto foundPlugin = AZStd::find_if(begin(mPlugins), end(mPlugins), [pluginType](const EMStudioPlugin* plugin) + const auto foundPlugin = AZStd::find_if(begin(m_plugins), end(m_plugins), [pluginType](const EMStudioPlugin* plugin) { return AzFramework::StringFunc::Equal(pluginType, plugin->GetName()); }); - return foundPlugin != end(mPlugins) ? AZStd::distance(begin(mPlugins), foundPlugin) : InvalidIndex; + return foundPlugin != end(m_plugins) ? AZStd::distance(begin(m_plugins), foundPlugin) : InvalidIndex; } EMStudioPlugin* PluginManager::GetActivePluginByTypeString(const char* pluginType) const { - const auto foundPlugin = AZStd::find_if(begin(mActivePlugins), end(mActivePlugins), [pluginType](const EMStudioPlugin* plugin) + const auto foundPlugin = AZStd::find_if(begin(m_activePlugins), end(m_activePlugins), [pluginType](const EMStudioPlugin* plugin) { return AzFramework::StringFunc::Equal(pluginType, plugin->GetName()); }); - return foundPlugin != end(mActivePlugins) ? *foundPlugin : nullptr; + return foundPlugin != end(m_activePlugins) ? *foundPlugin : nullptr; } // generate a unique object name @@ -166,7 +166,7 @@ namespace EMStudio ); // check if we have a conflict with a current plugin - const bool hasConflict = AZStd::any_of(begin(mActivePlugins), end(mActivePlugins), [&randomString](EMStudioPlugin* plugin) + const bool hasConflict = AZStd::any_of(begin(m_activePlugins), end(m_activePlugins), [&randomString](EMStudioPlugin* plugin) { return plugin->GetHasWindowWithObjectName(randomString); }); @@ -181,7 +181,7 @@ namespace EMStudio // find the number of active plugins of a given type size_t PluginManager::GetNumActivePluginsOfType(const char* pluginType) const { - return AZStd::accumulate(mActivePlugins.begin(), mActivePlugins.end(), size_t{0}, [pluginType](size_t total, const EMStudioPlugin* plugin) + return AZStd::accumulate(m_activePlugins.begin(), m_activePlugins.end(), size_t{0}, [pluginType](size_t total, const EMStudioPlugin* plugin) { return total + AzFramework::StringFunc::Equal(pluginType, plugin->GetName()); }); @@ -191,11 +191,11 @@ namespace EMStudio // find the first active plugin of a given type EMStudioPlugin* PluginManager::FindActivePlugin(uint32 classID) const { - const auto foundPlugin = AZStd::find_if(begin(mActivePlugins), end(mActivePlugins), [classID](const EMStudioPlugin* plugin) + const auto foundPlugin = AZStd::find_if(begin(m_activePlugins), end(m_activePlugins), [classID](const EMStudioPlugin* plugin) { return plugin->GetClassID() == classID; }); - return foundPlugin != end(mActivePlugins) ? *foundPlugin : nullptr; + return foundPlugin != end(m_activePlugins) ? *foundPlugin : nullptr; } @@ -203,7 +203,7 @@ namespace EMStudio // find the number of active plugins of a given type size_t PluginManager::GetNumActivePluginsOfType(uint32 classID) const { - return AZStd::accumulate(mActivePlugins.begin(), mActivePlugins.end(), size_t{0}, [classID](size_t total, const EMStudioPlugin* plugin) + return AZStd::accumulate(m_activePlugins.begin(), m_activePlugins.end(), size_t{0}, [classID](size_t total, const EMStudioPlugin* plugin) { return total + (plugin->GetClassID() == classID); }); 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 2937c3b387..e3a5f9627a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.h @@ -47,12 +47,12 @@ namespace EMStudio } EMStudioPlugin* FindActivePlugin(uint32 classID) const; // find first active plugin, or nullptr when not found - MCORE_INLINE size_t GetNumPlugins() const { return mPlugins.size(); } - MCORE_INLINE EMStudioPlugin* GetPlugin(const size_t 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 size_t GetNumActivePlugins() const { return mActivePlugins.size(); } - MCORE_INLINE EMStudioPlugin* GetActivePlugin(const size_t 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; } size_t GetNumActivePluginsOfType(const char* pluginType) const; size_t GetNumActivePluginsOfType(uint32 classID) const; @@ -61,9 +61,9 @@ namespace EMStudio 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 750de85344..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 - size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + 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 - size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + 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 - size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + 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 - size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + 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() { - size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + 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 - size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + 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 - size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); + 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 274edd36ce..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 @@ -130,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) @@ -229,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()); @@ -300,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(); @@ -358,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) @@ -449,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) @@ -662,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(); } } 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 60f7aa1291..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 @@ -114,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; } @@ -324,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; 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 d3e9593add..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,34 +27,34 @@ namespace EMStudio RenderPlugin::RenderPlugin() : DockWidgetPlugin() { - 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(); } @@ -83,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) { @@ -128,14 +128,14 @@ namespace EMStudio void RenderPlugin::CleanEMStudioActors() { // get rid of the actors - for (EMStudioRenderActor* actor : mActors) + for (EMStudioRenderActor* actor : m_actors) { if (actor) { delete actor; } } - mActors.clear(); + m_actors.clear(); } @@ -156,7 +156,7 @@ namespace EMStudio // get rid of the emstudio actor delete emstudioActor; - mActors.erase(AZStd::next(begin(mActors), index)); + m_actors.erase(AZStd::next(begin(m_actors), index)); return true; } @@ -216,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); } } @@ -269,14 +269,14 @@ 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); 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; + const AZ::Vector3 childPosition = pose->GetWorldSpaceTransform(childJoint->GetNodeIndex()).m_position; aabb.AddPoint(childPosition); } } @@ -300,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); } } } @@ -313,23 +313,23 @@ namespace EMStudio // try to locate the helper actor for a given instance RenderPlugin::EMStudioRenderActor* RenderPlugin::FindEMStudioActor(const EMotionFX::ActorInstance* actorInstance, bool doubleCheckInstance) const { - const auto foundActor = AZStd::find_if(begin(mActors), end(mActors), [actorInstance, doubleCheckInstance](const EMStudioRenderActor* renderActor) + const auto foundActor = AZStd::find_if(begin(m_actors), end(m_actors), [actorInstance, doubleCheckInstance](const EMStudioRenderActor* renderActor) { // is the parent actor of the instance the same as the one in the emstudio actor? - if (renderActor->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 auto foundActorInstance = AZStd::find(begin(renderActor->mActorInstances), end(renderActor->mActorInstances), actorInstance); - return foundActorInstance != end(renderActor->mActorInstances); + const auto foundActorInstance = AZStd::find(begin(renderActor->m_actorInstances), end(renderActor->m_actorInstances), actorInstance); + return foundActorInstance != end(renderActor->m_actorInstances); } return true; } return false; }); - return foundActor != end(mActors) ? *foundActor : nullptr; + return foundActor != end(m_actors) ? *foundActor : nullptr; } @@ -341,19 +341,19 @@ namespace EMStudio return nullptr; } - const auto foundActor = AZStd::find_if(begin(mActors), end(mActors), [match = actor](const EMStudioRenderActor* actor) + const auto foundActor = AZStd::find_if(begin(m_actors), end(m_actors), [match = actor](const EMStudioRenderActor* actor) { - return actor->mActor == match; + return actor->m_actor == match; }); - return foundActor != end(mActors) ? *foundActor : nullptr; + return foundActor != end(m_actors) ? *foundActor : nullptr; } // get the index of the given emstudio actor size_t RenderPlugin::FindEMStudioActorIndex(const EMStudioRenderActor* EMStudioRenderActor) const { - const auto foundActor = AZStd::find(begin(mActors), end(mActors), EMStudioRenderActor); - return foundActor != end(mActors) ? AZStd::distance(begin(mActors), foundActor) : InvalidIndex; + const auto foundActor = AZStd::find(begin(m_actors), end(m_actors), EMStudioRenderActor); + return foundActor != end(m_actors) ? AZStd::distance(begin(m_actors), foundActor) : InvalidIndex; } @@ -371,13 +371,13 @@ namespace EMStudio void RenderPlugin::AddEMStudioActor(EMStudioRenderActor* emstudioActor) { // add the actor to the list and return success - mActors.emplace_back(emstudioActor); + m_actors.emplace_back(emstudioActor); } void RenderPlugin::ReInit(bool resetViewCloseup) { - if (!mRenderUtil) + if (!m_renderUtil) { return; } @@ -404,10 +404,10 @@ namespace EMStudio } } - for (size_t i = 0; i < mActors.size(); ++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 (size_t j = 0; j < numActors; ++j) @@ -442,9 +442,9 @@ namespace EMStudio if (!emstudioActor) { - for (EMStudioRenderActor* currentEMStudioActor : mActors) + for (EMStudioRenderActor* currentEMStudioActor : m_actors) { - if (actor == currentEMStudioActor->mActor) + if (actor == currentEMStudioActor->m_actor) { emstudioActor = currentEMStudioActor; break; @@ -455,22 +455,22 @@ 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 (AZStd::find(begin(emstudioActor->mActorInstances), end(emstudioActor->mActorInstances), actorInstance) == end(emstudioActor->mActorInstances)) + if (AZStd::find(begin(emstudioActor->m_actorInstances), end(emstudioActor->m_actorInstances), actorInstance) == end(emstudioActor->m_actorInstances)) { - emstudioActor->mActorInstances.emplace_back(actorInstance); + emstudioActor->m_actorInstances.emplace_back(actorInstance); } } } // 4. Unlink invalid actor instances from the emstudio actors - for (EMStudioRenderActor* emstudioActor : mActors) + for (EMStudioRenderActor* emstudioActor : m_actors) { - for (size_t j = 0; j < emstudioActor->mActorInstances.size();) + 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 (size_t k = 0; k < numActorInstances; ++k) @@ -484,7 +484,7 @@ namespace EMStudio if (found == false) { - emstudioActor->mActorInstances.erase(AZStd::next(begin(emstudioActor->mActorInstances), j)); + emstudioActor->m_actorInstances.erase(AZStd::next(begin(emstudioActor->m_actorInstances), j)); } else { @@ -493,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 @@ -513,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(); } @@ -531,7 +531,7 @@ namespace EMStudio RenderPlugin::EMStudioRenderActor::~EMStudioRenderActor() { // get the number of actor instances and iterate through them - for (EMotionFX::ActorInstance* actorInstance : mActorInstances) + for (EMotionFX::ActorInstance* actorInstance : m_actorInstances) { // 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 @@ -549,17 +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) == InvalidIndex) + 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(); } } @@ -567,7 +567,7 @@ 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); AZ::Aabb aabb; @@ -578,14 +578,14 @@ namespace EMStudio actorInstance->CalcNodeBasedAabb(&aabb); } - mCharacterHeight = aabb.GetExtents().GetZ(); - 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 const float radius = AZ::Vector3(aabb.GetMax() - aabb.GetMin()).GetLength() * 0.5f; - mNormalsScaleMultiplier = radius * 0.01f; + m_normalsScaleMultiplier = radius * 0.01f; } @@ -640,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; @@ -702,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) @@ -727,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) @@ -745,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) { @@ -763,7 +762,7 @@ namespace EMStudio void RenderPlugin::VisibilityChanged(bool visible) { - mIsVisible = visible; + m_isVisible = visible; } void RenderPlugin::UpdateActorInstances(float timePassedInSeconds) @@ -794,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; } @@ -811,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 @@ -833,17 +832,17 @@ namespace EMStudio 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 @@ -933,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); @@ -981,7 +980,7 @@ namespace EMStudio { for (MCommon::RenderUtil::TrajectoryTracePath* trajectoryPath : m_trajectoryTracePaths) { - if (trajectoryPath->mActorInstance == actorInstance) + if (trajectoryPath->m_actorInstance == actorInstance) { return trajectoryPath; } @@ -990,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; @@ -1032,20 +1031,20 @@ namespace EMStudio const EMotionFX::Transform& worldTM = actorInstance->GetWorldSpaceTransform(); bool distanceTraveledEnough = false; - if (trajectoryPath->mTraceParticles.empty()) + if (trajectoryPath->m_traceParticles.empty()) { distanceTraveledEnough = true; } else { - const size_t numParticles = trajectoryPath->mTraceParticles.size(); - 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) { @@ -1054,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.emplace_back(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.size() > 50) + if (trajectoryPath->m_traceParticles.size() > 50) { - trajectoryPath->mTraceParticles.erase(begin(trajectoryPath->mTraceParticles)); + trajectoryPath->m_traceParticles.erase(begin(trajectoryPath->m_traceParticles)); } } } @@ -1106,9 +1105,9 @@ namespace EMStudio if (widget->GetRenderFlag(RenderViewWidget::RENDER_AABB)) { MCommon::RenderUtil::AABBRenderSettings settings; - settings.mNodeBasedColor = renderOptions->GetNodeAABBColor(); - settings.mStaticBasedColor = renderOptions->GetStaticAABBColor(); - settings.mMeshBasedColor = renderOptions->GetMeshAABBColor(); + settings.m_nodeBasedColor = renderOptions->GetNodeAABBColor(); + settings.m_staticBasedColor = renderOptions->GetStaticAABBColor(); + settings.m_meshBasedColor = renderOptions->GetMeshAABBColor(); renderUtil->RenderAabbs(actorInstance, settings); } @@ -1146,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)) { @@ -1161,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); @@ -1181,9 +1180,9 @@ namespace EMStudio 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::Node* node = emstudioActor->m_actor->GetSkeleton()->GetNode(actorInstance->GetEnabledNode(i)); const size_t nodeIndex = node->GetNodeIndex(); - EMotionFX::Mesh* mesh = emstudioActor->mActor->GetMesh(geomLODLevel, nodeIndex); + EMotionFX::Mesh* mesh = emstudioActor->m_actor->GetMesh(geomLODLevel, nodeIndex); renderUtil->ResetCurrentMesh(); @@ -1196,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); } } } 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 a99a64ef68..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; - AZStd::vector mBoneList; - RenderGL::GLActor* mRenderActor; - AZStd::vector 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,7 +103,7 @@ 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(const EMotionFX::ActorInstance* actorInstance, bool doubleCheckInstance = true) const; @@ -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,19 +140,19 @@ 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; } AZ::Aabb GetSceneAabb(bool selectedInstancesOnly); @@ -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; - AZStd::vector 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 3c146c528b..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.empty()) + if (trajectoryPath->m_traceParticles.empty()) { distanceTraveledEnough = true; } else { - const size_t numParticles = trajectoryPath->mTraceParticles.size(); - 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.emplace_back(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.size() > 50) + if (trajectoryPath->m_traceParticles.size() > 50) { - trajectoryPath->mTraceParticles.erase(begin(trajectoryPath->mTraceParticles)); + 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,8 +157,8 @@ 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(); @@ -167,9 +167,9 @@ namespace EMStudio if (widget->GetRenderFlag(RenderViewWidget::RENDER_AABB)) { MCommon::RenderUtil::AABBRenderSettings settings; - settings.mNodeBasedColor = renderOptions->GetNodeAABBColor(); - settings.mStaticBasedColor = renderOptions->GetStaticAABBColor(); - settings.mMeshBasedColor = renderOptions->GetMeshAABBColor(); + settings.m_nodeBasedColor = renderOptions->GetNodeAABBColor(); + settings.m_staticBasedColor = renderOptions->GetStaticAABBColor(); + settings.m_meshBasedColor = renderOptions->GetMeshAABBColor(); renderUtil->RenderAabbs(actorInstance, settings); } @@ -185,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)) { @@ -200,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); @@ -220,9 +219,8 @@ namespace EMStudio 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(); @@ -234,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) { @@ -253,7 +251,7 @@ 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)) { AZ::Aabb aabb = actorInstance->GetAabb(); aabb.Expand(aabb.GetExtents() * 0.005f); 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 55699c165f..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); @@ -131,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); @@ -166,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", @@ -195,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); @@ -257,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); } } @@ -280,7 +280,7 @@ namespace EMStudio if (actionIndex >= 0) { - mActions[actionIndex] = action; + m_actions[actionIndex] = action; } } @@ -290,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; } @@ -299,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(); } @@ -327,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)); @@ -339,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); } @@ -366,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); } } @@ -379,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); } } @@ -389,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()); } @@ -403,7 +403,7 @@ 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); } @@ -411,8 +411,8 @@ namespace EMStudio 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); @@ -426,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 defdb0d2a7..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 @@ -71,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); @@ -89,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); @@ -117,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 56d27222bb..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 @@ -30,31 +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); + 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; } @@ -62,81 +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 AZ::Aabb& aabb, float flightTime, uint32 viewCloseupWaiting) { - mViewCloseupWaiting = viewCloseupWaiting; - mViewCloseupAABB = aabb; - mViewCloseupFlightTime = flightTime; + m_viewCloseupWaiting = viewCloseupWaiting; + m_viewCloseupAabb = aabb; + m_viewCloseupFlightTime = flightTime; } void RenderWidget::ViewCloseup(bool selectedInstancesOnly, float flightTime, uint32 viewCloseupWaiting) { - 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); } @@ -160,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()) @@ -168,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; @@ -191,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(); } } @@ -213,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); } } @@ -229,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; @@ -249,7 +246,7 @@ 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 @@ -268,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 @@ -287,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 @@ -335,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; } } } @@ -363,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 { @@ -379,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: { @@ -395,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 @@ -424,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 @@ -442,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(); } } @@ -455,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; @@ -473,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 @@ -485,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) @@ -497,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); } } @@ -552,7 +547,7 @@ 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 size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); @@ -581,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; @@ -615,7 +610,7 @@ namespace EMStudio } } - mSelectedActorInstances.clear(); + m_selectedActorInstances.clear(); if (ctrlPressed) { @@ -623,16 +618,16 @@ namespace EMStudio const size_t numSelectedActorInstances = selection.GetNumSelectedActorInstances(); for (size_t i = 0; i < numSelectedActorInstances; ++i) { - mSelectedActorInstances.emplace_back(selection.GetActorInstance(i)); + m_selectedActorInstances.emplace_back(selection.GetActorInstance(i)); } } if (selectedActorInstance) { - mSelectedActorInstances.emplace_back(selectedActorInstance); + m_selectedActorInstances.emplace_back(selectedActorInstance); } - CommandSystem::SelectActorInstancesUsingCommands(mSelectedActorInstances); + CommandSystem::SelectActorInstancesUsingCommands(m_selectedActorInstances); } } } @@ -647,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 @@ -664,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()); } @@ -704,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(); } @@ -720,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 @@ -756,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(); @@ -860,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); @@ -881,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); @@ -905,17 +893,17 @@ 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; @@ -923,12 +911,12 @@ namespace EMStudio 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 @@ -937,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()) { @@ -972,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()) { @@ -990,7 +978,7 @@ namespace EMStudio } else { - mOldActorInstancePos.Set(0.0f, 0.0f, 0.0f); + m_oldActorInstancePos.Set(0.0f, 0.0f, 0.0f); } } @@ -998,7 +986,7 @@ namespace EMStudio // render the manipulator gizmos void RenderWidget::RenderManipulators() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; @@ -1019,7 +1007,7 @@ namespace EMStudio UpdateActiveTransformationManipulator(activeManipulator); // render the current actor - activeManipulator->Render(mCamera, renderUtil); + activeManipulator->Render(m_camera, renderUtil); } // render any remaining lines @@ -1033,16 +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 - for (const Triangle& curTri : mTriangles) + for (const Triangle& curTri : m_triangles) { - 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(); @@ -1053,7 +1041,7 @@ 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; @@ -1064,9 +1052,9 @@ namespace EMStudio 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(); @@ -1078,7 +1066,7 @@ namespace EMStudio void RenderWidget::RenderDebugDraw() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (!renderUtil) { return; @@ -1107,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); @@ -1129,7 +1117,7 @@ namespace EMStudio 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); } } } @@ -1138,34 +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(MCore::AABB(mViewCloseupAABB.GetMin(), mViewCloseupAABB.GetMax()), mViewCloseupFlightTime); + 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(); } @@ -1173,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; @@ -1189,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(); } @@ -1210,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); } @@ -1222,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 d2ec5d71ea..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 @@ -47,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) {} }; @@ -76,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); @@ -98,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.emplace_back(Triangle(posA, posB, posC, normalA, normalB, normalC, color)); } - MCORE_INLINE void ClearTriangles() { mTriangles.clear(); } + 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 @@ -113,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; } + 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); @@ -137,40 +137,40 @@ namespace EMStudio void closeEvent(QCloseEvent* event); - RenderPlugin* mPlugin; - RenderViewWidget* mViewWidget; - AZStd::vector mTriangles; - EventHandler mEventHandler; + RenderPlugin* m_plugin; + RenderViewWidget* m_viewWidget; + AZStd::vector m_triangles; + EventHandler m_eventHandler; - AZStd::vector 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; - AZ::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 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 a791b17e25..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; } @@ -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 @@ -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 ac23dd489b..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(); + 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,66 +61,66 @@ 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()); } } @@ -128,44 +128,44 @@ namespace EMStudio 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(aznumeric_caster(historyIndex), new QListWidgetItem(mTempString.c_str(), mList)); - mList->setCurrentRow(aznumeric_caster(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(size_t historyIndex) { // Remove the item. - mIsRemoving = true; - delete mList->takeItem(aznumeric_caster(historyIndex)); - mIsRemoving = false; + m_isRemoving = true; + delete m_list->takeItem(aznumeric_caster(historyIndex)); + m_isRemoving = false; } // Set the current command. void ActionHistoryCallback::OnSetCurrentCommand(size_t index) { - if (mIsRemoving) + if (m_isRemoving) { return; } if (index == InvalidIndex) { - mList->setCurrentRow(-1); + m_list->setCurrentRow(-1); // Darken all history items. - const int numCommands = mList->count(); + 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(aznumeric_caster(index)); + m_list->setCurrentRow(aznumeric_caster(index)); // Get the current history index. const size_t historyIndex = GetCommandManager()->GetHistoryIndex(); @@ -225,13 +225,13 @@ namespace EMStudio const int numCommands = static_cast(GetCommandManager()->GetNumHistoryItems()); 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. for (int i = 0; i <= static_cast(index); ++i) { - mList->item(i)->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 0433b22d5d..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 @@ -44,15 +44,15 @@ namespace EMStudio 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 9a4170d1b0..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,8 +206,8 @@ 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 size_t motionIndex = EMotionFX::GetMotionManager().FindMotionIndexByName(motion->GetName()); 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 f6e308f07b..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); @@ -303,7 +303,7 @@ namespace EMotionFX const CommandSystem::SelectionList& selectionList = CommandSystem::GetCommandManager()->GetCurrentSelection(); 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) { 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 1d17c46815..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 @@ -58,9 +58,9 @@ namespace EMotionFX 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/AnimGraphModelCallbacks.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModelCallbacks.cpp index 5de2b58905..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); } @@ -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 1a713f52fe..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 @@ -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); } } @@ -150,12 +150,12 @@ namespace EMStudio for (const SaveDirtyFilesCallback::ObjectPointer& objPointer : objects) { // get the current object pointer and skip directly if the type check fails - 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; @@ -177,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; @@ -214,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) @@ -223,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) @@ -322,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 @@ -427,17 +426,17 @@ namespace EMStudio void AnimGraphPlugin::SetOptionFlag(EDockWindowOptionFlag option, bool isEnabled) { - if (mDockWindowActions[option]) + if (m_dockWindowActions[option]) { - mDockWindowActions[option]->setChecked(isEnabled); + m_dockWindowActions[option]->setChecked(isEnabled); } } void AnimGraphPlugin::SetOptionEnabled(EDockWindowOptionFlag option, bool isEnabled) { - if (mDockWindowActions[option]) + if (m_dockWindowActions[option]) { - mDockWindowActions[option]->setEnabled(isEnabled); + m_dockWindowActions[option]->setEnabled(isEnabled); } } @@ -474,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); } } @@ -537,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(); @@ -645,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(); @@ -658,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); } @@ -673,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 @@ -700,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 } @@ -715,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; @@ -745,7 +740,7 @@ namespace EMStudio continue; } - if (actorInstance == outIntersectInfo->mIgnoreActorInstance) + if (actorInstance == outIntersectInfo->m_ignoreActorInstance) { continue; } @@ -757,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 @@ -769,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; } @@ -1008,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. @@ -1108,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; @@ -1127,7 +1122,7 @@ 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; } @@ -1144,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()) { @@ -1269,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); } @@ -1392,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; } @@ -1422,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 af6fcde3d6..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 @@ -84,7 +84,7 @@ namespace EMStudio void OnDeleteAnimGraphInstance(EMotionFX::AnimGraphInstance* animGraphInstance) override; private: - AnimGraphPlugin* mPlugin; + AnimGraphPlugin* m_plugin; }; class AnimGraphPerFrameCallback @@ -133,7 +133,7 @@ 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, size_t animGraphIndex, MCore::CommandGroup* commandGroup = nullptr); void SaveAnimGraph(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup = nullptr); @@ -141,7 +141,7 @@ namespace EMStudio 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 037d75a9b9..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]); 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 5d57763ea6..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) { @@ -813,9 +813,9 @@ namespace EMStudio 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; } @@ -853,7 +853,7 @@ namespace EMStudio { 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); @@ -936,7 +936,7 @@ namespace EMStudio 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; @@ -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; @@ -1455,7 +1455,7 @@ namespace EMStudio } } - GraphNode* node = mActiveGraph->FindNode(localPos); + GraphNode* node = m_activeGraph->FindNode(localPos); EMotionFX::AnimGraphNode* animGraphNode = nullptr; if (node) @@ -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 fa0801cdc1..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 @@ -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/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 4ec48bbffb..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(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); + * 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 0cf44af794..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 AZStd::vector& inPorts = m_emfxNode->GetInputPorts(); const AZ::u16 numInputs = aznumeric_caster(inPorts.size()); - mInputPorts.reserve(numInputs); + 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 AZStd::vector& outPorts = m_emfxNode->GetOutputPorts(); const AZ::u16 numOutputs = aznumeric_caster(outPorts.size()); - mOutputPorts.reserve(numOutputs); + 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 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); @@ -119,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; } @@ -130,8 +130,8 @@ namespace EMStudio RenderShadow(painter); } - float opacityFactor = mOpacity; - if (mIsEnabled == false) + float opacityFactor = m_opacity; + if (m_isEnabled == false) { opacityFactor *= 0.35f; } @@ -155,7 +155,7 @@ namespace EMStudio { borderColor.setRgb(255, 128, 0); - if (mParentGraph->GetScale() > 0.75f) + if (m_parentGraph->GetScale() > 0.75f) { pen->setWidth(2); } @@ -166,12 +166,9 @@ namespace EMStudio { borderColor.setRgb(255, 0, 0); } - //else - //if (mIsProcessed) - //borderColor.setRgb(255,225,0); else { - borderColor = mBorderColor; + borderColor = m_borderColor; } } @@ -183,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 { @@ -204,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 { @@ -220,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; } @@ -243,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); @@ -255,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)); } @@ -268,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); @@ -294,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 AZ::u16 numInputs = aznumeric_caster(mInputPorts.size()); + 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 @@ -321,11 +315,11 @@ namespace EMStudio if (GetHasVisualOutputPorts()) { // draw the output ports - const AZ::u16 numOutputs = aznumeric_caster(mOutputPorts.size()); + 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 @@ -342,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); @@ -359,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; @@ -370,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) @@ -384,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); } @@ -424,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 AZ::u16 numInputs = aznumeric_caster(mInputPorts.size()); + 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 AZ::u16 numOutputs = aznumeric_caster(mOutputPorts.size()); + 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 da092f93f6..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()); @@ -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 c1d0d25c9e..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; } 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 f1ee2e0e9d..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 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 eeb765ce54..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,8 +320,8 @@ 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(); @@ -340,16 +340,16 @@ 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 - mParameterInfos.clear(); + m_parameterInfos.clear(); const EMotionFX::ValueParameterVector& parameters = animGraph->RecursivelyGetValueParameters(); const int numParameters = aznumeric_caster(parameters.size()); - mParameterInfos.reserve(numParameters); + m_parameterInfos.reserve(numParameters); for (int parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex) { @@ -373,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(); @@ -389,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) @@ -408,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) @@ -418,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) @@ -433,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(); @@ -446,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(); @@ -459,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(); @@ -468,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.emplace_back(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(); @@ -517,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.emplace_back(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); @@ -535,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(); @@ -568,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(); @@ -595,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 (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 size_t activePresetIndex = gameControllerSettings.GetActivePresetIndex(); if (activePresetIndex != InvalidIndex) { - mPresetComboBox->setCurrentIndex(aznumeric_caster(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); //////////////////////////// @@ -658,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(); @@ -679,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 @@ -700,22 +700,22 @@ namespace EMStudio GameControllerWindow::ButtonInfo* GameControllerWindow::FindButtonInfo(QWidget* widget) { // get the number of button infos and iterate through them - const auto foundButtonInfo = AZStd::find_if(begin(mButtonInfos), end(mButtonInfos), [widget](const ButtonInfo& buttonInfo) + const auto foundButtonInfo = AZStd::find_if(begin(m_buttonInfos), end(m_buttonInfos), [widget](const ButtonInfo& buttonInfo) { - return buttonInfo.mWidget == widget; + return buttonInfo.m_widget == widget; }); - return foundButtonInfo != end(mButtonInfos) ? &(*foundButtonInfo) : nullptr; + return foundButtonInfo != end(m_buttonInfos) ? &(*foundButtonInfo) : nullptr; } GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByModeComboBox(QComboBox* comboBox) { // get the number of parameter infos and iterate through them - const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [comboBox](const ParameterInfo& parameterInfo) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [comboBox](const ParameterInfo& parameterInfo) { - return parameterInfo.mMode == comboBox; + return parameterInfo.m_mode == comboBox; }); - return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; + return foundParameterInfo != end(m_parameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -723,30 +723,30 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindButtonInfoByAttributeInfo(const EMotionFX::Parameter* parameter) { // get the number of parameter infos and iterate through them - const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [parameter](const ParameterInfo& parameterInfo) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [parameter](const ParameterInfo& parameterInfo) { - return parameterInfo.mParameter == parameter; + return parameterInfo.m_parameter == parameter; }); - return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; + 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); } } @@ -756,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(); @@ -772,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(); } @@ -781,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(); @@ -794,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(); @@ -850,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() || @@ -888,7 +888,7 @@ namespace EMStudio if (widget) { - mButtonGridLayout->addWidget(widget, buttonIndex, 2); + m_buttonGridLayout->addWidget(widget, buttonIndex, 2); } } @@ -905,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(); @@ -936,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()); } @@ -947,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(); @@ -963,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(); @@ -974,7 +974,7 @@ namespace EMStudio } // update the parameter window - mPlugin->GetParameterWindow()->Reinit(/*forceReinit*/true); + m_plugin->GetParameterWindow()->Reinit(/*forceReinit*/true); } @@ -984,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(); @@ -1000,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(); @@ -1010,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() || @@ -1022,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(); size_t presetNumber = gameControllerSettings.GetNumPresets(); - mString = AZStd::string::format("Preset %zu", presetNumber); - while (gameControllerSettings.FindPresetIndexByName(mString.c_str()) != InvalidIndex) + m_string = AZStd::string::format("Preset %zu", presetNumber); + while (gameControllerSettings.FindPresetIndexByName(m_string.c_str()) != InvalidIndex) { presetNumber++; - mString = AZStd::string::format("Preset %zu", 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(); @@ -1054,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()); @@ -1067,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; @@ -1094,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()); @@ -1102,7 +1102,7 @@ namespace EMStudio FromQtString(widget->text(), &newValue); // get the currently selected preset - uint32 presetIndex = mPresetComboBox->currentIndex(); + uint32 presetIndex = m_presetComboBox->currentIndex(); size_t newValueIndex = gameControllerSettings.FindPresetIndexByName(newValue.c_str()); if (newValueIndex == InvalidIndex) @@ -1117,28 +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 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) { - const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [comboBox](const ParameterInfo& parameterInfo) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [comboBox](const ParameterInfo& parameterInfo) { - return parameterInfo.mAxis == comboBox; + return parameterInfo.m_axis == comboBox; }); - return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; + return foundParameterInfo != end(m_parameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -1147,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(); @@ -1163,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->FindElementIDByName(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; @@ -1180,7 +1180,7 @@ namespace EMStudio } } else - if (azrtti_typeid(paramInfo->mParameter) == azrtti_typeid()) + if (azrtti_typeid(paramInfo->m_parameter) == azrtti_typeid()) { if (value == 0) { @@ -1199,17 +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) { - const auto foundParameterInfo = AZStd::find_if(begin(mParameterInfos), end(mParameterInfos), [checkBox](const ParameterInfo& parameterInfo) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [checkBox](const ParameterInfo& parameterInfo) { - return parameterInfo.mInvert == checkBox; + return parameterInfo.m_invert == checkBox; }); - return foundParameterInfo != end(mParameterInfos) ? &(*foundParameterInfo) : nullptr; + return foundParameterInfo != end(m_parameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -1218,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(); @@ -1234,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; } @@ -1248,7 +1248,7 @@ namespace EMStudio UpdateGameControllerComboBox(); AutoSelectGameController(); ReInit(); - mPlugin->GetParameterWindow()->Reinit(/*forceReinit*/true); + m_plugin->GetParameterWindow()->Reinit(/*forceReinit*/true); } @@ -1266,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; } @@ -1290,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; } @@ -1301,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(); @@ -1310,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) { @@ -1334,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(); @@ -1421,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); } @@ -1438,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 @@ -1461,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); @@ -1577,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); } @@ -1596,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); @@ -1637,7 +1637,7 @@ 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()) @@ -1680,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); } } @@ -1697,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); } } @@ -1714,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); } } @@ -1751,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); } } @@ -1767,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 c9ea776337..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 @@ -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; - AZStd::vector mPreviewLabels; - AZStd::vector mParameterInfos; - AZStd::vector 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 4f29a15669..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,59 +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, AZ::u16 numInputs, AZ::u16 numOutputs) : m_modelIndex(modelIndex) { - 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(); @@ -80,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(); } @@ -93,55 +93,53 @@ 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 size_t numInputs = mInputPorts.size(); - mInputPortText.resize(numInputs); + 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 size_t numOutputs = mOutputPorts.size(); - mOutputPortText.resize(numOutputs); + 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); } } @@ -149,20 +147,20 @@ namespace EMStudio // remove all node connections void GraphNode::RemoveAllConnections() { - for (NodeConnection* connection : mConnections) + for (NodeConnection* connection : m_connections) { 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) { @@ -175,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) { @@ -189,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(); @@ -201,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(); } @@ -224,48 +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 - const AZ::u16 numInputPorts = aznumeric_caster(mInputPorts.size()); + 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 AZ::u16 numOutputPorts = aznumeric_caster(mOutputPorts.size()); + 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; } } @@ -273,11 +269,11 @@ 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 (NodePort& inputPort : mInputPorts) + for (NodePort& inputPort : m_inputPorts) { // get the input port and the corresponding rect const QRect& portRect = inputPort.GetRect(); @@ -295,7 +291,7 @@ namespace EMStudio if (highlightedPortFound == false) { // set the set highlight flags for the output ports - for (NodePort& outputPort : mOutputPorts) + for (NodePort& outputPort : m_outputPorts) { // get the output port and the corresponding rect const QRect& portRect = outputPort.GetRect(); @@ -322,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; } @@ -336,8 +332,8 @@ namespace EMStudio RenderShadow(painter); } - float opacityFactor = mOpacity; - if (mIsEnabled == false) + float opacityFactor = m_opacity; + if (m_isEnabled == false) { opacityFactor *= 0.35f; } @@ -358,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; @@ -381,9 +368,9 @@ namespace EMStudio } else // not selected { - if (mIsEnabled) + if (m_isEnabled) { - bgColor = mBaseColor; + bgColor = m_baseColor; } else { @@ -400,7 +387,7 @@ namespace EMStudio QColor textColor; if (!isSelected) { - if (mIsEnabled) + if (m_isEnabled) { textColor = Qt::white; } @@ -415,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); @@ -450,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 AZ::u16 numInputs = aznumeric_caster(mInputPorts.size()); + 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 @@ -496,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 AZ::u16 numOutputs = aznumeric_caster(mOutputPorts.size()); + 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 @@ -521,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); } } } @@ -530,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); @@ -547,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; @@ -560,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) @@ -582,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); } @@ -614,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 );*/ } @@ -629,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); @@ -648,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; @@ -659,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 @@ -685,8 +655,8 @@ namespace EMStudio } else { - *outPenColor = mPortHighlightColor; - *outBrushColor = mPortHighlightBGColor; + *outPenColor = s_portHighlightColo; + *outBrushColor = s_portHighlightBGColor; } } } @@ -695,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; } @@ -706,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 @@ -716,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 @@ -731,12 +701,12 @@ namespace EMStudio const bool alwaysColor = GetAlwaysColor(); // for all connections - for (NodeConnection* nodeConnection : mConnections) + for (NodeConnection* nodeConnection : m_connections) { if (nodeConnection->GetIsVisible()) { float opacity = 1.0f; - if (!mIsEnabled) + if (!m_isEnabled) { opacity = 0.25f; } @@ -765,7 +735,7 @@ namespace EMStudio { QColor vizBorder; QColor vizBackGround = bgColor2.lighter(110); - if (mVisualize) + if (m_visualize) { vizBorder = Qt::black; } @@ -774,57 +744,56 @@ 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) { - int32 numPorts = aznumeric_caster(AZStd::max(mInputPorts.size(), mOutputPorts.size())); + int32 numPorts = aznumeric_caster(AZStd::max(m_inputPorts.size(), m_outputPorts.size())); int32 result = (numPorts * 15) + 34; return MCore::Math::Align(result, 10); } @@ -840,9 +809,9 @@ namespace EMStudio { // calc the maximum input port width int maxInputWidth = 0; - for (const NodePort& nodePort : mInputPorts) + for (const NodePort& nodePort : m_inputPorts) { - maxInputWidth = AZStd::max(maxInputWidth, mPortFontMetrics->horizontalAdvance(nodePort.GetName())); + maxInputWidth = AZStd::max(maxInputWidth, m_portFontMetrics->horizontalAdvance(nodePort.GetName())); } return maxInputWidth; @@ -853,9 +822,9 @@ namespace EMStudio { // calc the maximum output port width int maxOutputWidth = 0; - for (const NodePort& nodePort : mOutputPorts) + for (const NodePort& nodePort : m_outputPorts) { - maxOutputWidth = AZStd::max(maxOutputWidth, mPortFontMetrics->horizontalAdvance(nodePort.GetName())); + maxOutputWidth = AZStd::max(maxOutputWidth, m_portFontMetrics->horizontalAdvance(nodePort.GetName())); } return maxOutputWidth; @@ -864,40 +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 int infoWidth = mInfoFontMetrics->horizontalAdvance(mElidedNodeInfo); - const int 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 - const int headerWidth = AZStd::max(mHeaderFontMetrics->horizontalAdvance(mElidedName) + 40, 100); + const int headerWidth = AZStd::max(m_headerFontMetrics->horizontalAdvance(m_elidedName) + 40, 100); - mRequiredWidth = AZStd::max(headerWidth, totalPortWidth); - mRequiredWidth = MCore::Math::Align(mRequiredWidth, 10); + m_requiredWidth = AZStd::max(headerWidth, totalPortWidth); + m_requiredWidth = MCore::Math::Align(m_requiredWidth, 10); - mNameAndPortsUpdated = true; + m_nameAndPortsUpdated = true; - return mRequiredWidth; + return m_requiredWidth; } // get the rect for a given input port 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(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); } @@ -906,11 +875,11 @@ 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); } } @@ -920,11 +889,11 @@ namespace EMStudio { 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); } } @@ -934,11 +903,11 @@ namespace EMStudio { 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); } } @@ -946,40 +915,40 @@ namespace EMStudio // remove all input ports void GraphNode::RemoveAllInputPorts() { - mInputPorts.clear(); + m_inputPorts.clear(); } // remove all output ports void GraphNode::RemoveAllOutputPorts() { - mOutputPorts.clear(); + m_outputPorts.clear(); } // add a new input port NodePort* GraphNode::AddInputPort(bool updateTextPixMap) { - mInputPorts.emplace_back(); - mInputPorts.back().SetNode(this); + m_inputPorts.emplace_back(); + m_inputPorts.back().SetNode(this); if (updateTextPixMap) { UpdateTextPixmap(); } - return &mInputPorts.back(); + return &m_inputPorts.back(); } // add a new output port NodePort* GraphNode::AddOutputPort(bool updateTextPixMap) { - mOutputPorts.emplace_back(); - mOutputPorts.back().SetNode(this); + m_outputPorts.emplace_back(); + m_outputPorts.back().SetNode(this); if (updateTextPixMap) { UpdateTextPixmap(); } - return &mOutputPorts.back(); + return &m_outputPorts.back(); } @@ -987,13 +956,13 @@ namespace EMStudio NodePort* GraphNode::FindPort(int32 x, int32 y, AZ::u16* outPortNr, bool* outIsInputPort, bool includeInputPorts) { // 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; } @@ -1001,7 +970,7 @@ namespace EMStudio // check the input ports if (includeInputPorts) { - const AZ::u16 numInputPorts = aznumeric_caster(mInputPorts.size()); + const AZ::u16 numInputPorts = aznumeric_caster(m_inputPorts.size()); for (AZ::u16 i = 0; i < numInputPorts; ++i) { QRect rect = CalcInputPortRect(i); @@ -1009,13 +978,13 @@ namespace EMStudio { *outPortNr = i; *outIsInputPort = true; - return &mInputPorts[i]; + return &m_inputPorts[i]; } } } // check the output ports - const AZ::u16 numOutputPorts = aznumeric_caster(mOutputPorts.size()); + const AZ::u16 numOutputPorts = aznumeric_caster(m_outputPorts.size()); for (AZ::u16 i = 0; i < numOutputPorts; ++i) { QRect rect = CalcOutputPortRect(i); @@ -1023,7 +992,7 @@ namespace EMStudio { *outPortNr = i; *outIsInputPort = false; - return &mOutputPorts[i]; + return &m_outputPorts[i]; } } @@ -1033,12 +1002,12 @@ namespace EMStudio // remove a given connection bool GraphNode::RemoveConnection(const void* connection, bool removeFromMemory) { - const auto foundConnection = AZStd::find_if(begin(mConnections), end(mConnections), [match = connection](const NodeConnection* connection) + const auto foundConnection = AZStd::find_if(begin(m_connections), end(m_connections), [match = connection](const NodeConnection* connection) { return connection->GetModelIndex().data(AnimGraphModel::ROLE_POINTER).value() == match; }); - if (foundConnection == end(mConnections)) + if (foundConnection == end(m_connections)) { return false; } @@ -1047,7 +1016,7 @@ namespace EMStudio { delete *foundConnection; } - mConnections.erase(foundConnection); + m_connections.erase(foundConnection); return true; } @@ -1055,12 +1024,12 @@ namespace EMStudio // Remove a given connection by model index bool GraphNode::RemoveConnection(const QModelIndex& modelIndex, bool removeFromMemory) { - const auto foundConnection = AZStd::find_if(begin(mConnections), end(mConnections), [match = modelIndex](const NodeConnection* connection) + const auto foundConnection = AZStd::find_if(begin(m_connections), end(m_connections), [match = modelIndex](const NodeConnection* connection) { return connection->GetModelIndex() == match; }); - if (foundConnection == end(mConnections)) + if (foundConnection == end(m_connections)) { return false; } @@ -1069,7 +1038,7 @@ namespace EMStudio { delete *foundConnection; } - mConnections.erase(foundConnection); + m_connections.erase(foundConnection); return true; } @@ -1077,14 +1046,14 @@ namespace EMStudio // 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 125317408d..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 @@ -43,28 +43,28 @@ namespace EMStudio public: NodePort() - : mIsHighlighted(false) { mNode = nullptr; mNameID = MCORE_INVALIDINDEX32; mColor.setRgb(50, 150, 250); } - - 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; }; @@ -83,59 +83,58 @@ namespace EMStudio const QModelIndex& GetModelIndex() const { return m_modelIndex; } - MCORE_INLINE void UpdateNameAndPorts() { mNameAndPortsUpdated = false; } - MCORE_INLINE AZStd::vector& GetConnections() { return mConnections; } - MCORE_INLINE size_t GetNumConnections() { return mConnections.size(); } - MCORE_INLINE NodeConnection* GetConnection(size_t index) { return mConnections[index]; } - MCORE_INLINE NodeConnection* AddConnection(NodeConnection* con) { mConnections.emplace_back(con); return con; } - MCORE_INLINE void SetParentGraph(NodeGraph* graph) { mParentGraph = graph; } - MCORE_INLINE NodeGraph* GetParentGraph() { return mParentGraph; } - MCORE_INLINE NodePort* GetInputPort(AZ::u16 index) { return &mInputPorts[index]; } - MCORE_INLINE NodePort* GetOutputPort(AZ::u16 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; } - AZ::u16 GetNumInputPorts() const { return aznumeric_caster(mInputPorts.size()); } - AZ::u16 GetNumOutputPorts() const { return aznumeric_caster(mOutputPorts.size()); } + 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); @@ -180,11 +179,11 @@ namespace EMStudio 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() {} @@ -192,12 +191,12 @@ namespace EMStudio 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); @@ -208,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; - AZStd::vector 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; - - AZStd::vector mInputPortText; - AZStd::vector mOutputPortText; - - int32 mRequiredWidth; - bool mNameAndPortsUpdated; - - NodeGraph* mParentGraph; - AZStd::vector mInputPorts; - AZStd::vector 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; - - int mMaxInputWidth; // will be calculated automatically in CalcRequiredWidth() - int 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 cefbb0d0af..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 @@ -21,18 +21,18 @@ namespace EMStudio : 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 2e305dbd0c..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 @@ -60,71 +60,71 @@ namespace EMStudio bool GetIsSelected() const; - MCORE_INLINE bool GetIsVisible() { return mIsVisible; } + MCORE_INLINE bool GetIsVisible() { return m_isVisible; } - MCORE_INLINE AZ::u16 GetInputPortNr() const { return mPortNr; } - MCORE_INLINE AZ::u16 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(AZ::u16 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; - AZ::u16 mPortNr; // input port where this is connected to - AZ::u16 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 37ec2cfd8b..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 @@ -42,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 = InvalidIndex16; - 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); } @@ -99,7 +99,7 @@ namespace EMStudio { m_graphNodeByModelIndex.clear(); - delete mFontMetrics; + delete m_fontMetrics; } AZStd::vector NodeGraph::GetSelectedGraphNodes() const @@ -213,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); @@ -222,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); } } @@ -411,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); @@ -429,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); } } } @@ -656,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); } @@ -693,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; @@ -706,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 @@ -744,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) @@ -791,7 +788,7 @@ 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); @@ -815,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(); @@ -969,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 @@ -986,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); @@ -995,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) @@ -1025,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) @@ -1292,8 +1287,8 @@ namespace EMStudio } else { - mScrollOffset = offset; - mScale = 1.0f; + m_scrollOffset = offset; + m_scale = 1.0f; } } else @@ -1309,7 +1304,7 @@ namespace EMStudio } else { - mScrollOffset = offset; + m_scrollOffset = offset; } // set the zoom factor so it exactly fits @@ -1333,7 +1328,7 @@ namespace EMStudio if (animate == false) { - mScale = MCore::Min(widthZoom, heightZoom); + m_scale = MCore::Min(widthZoom, heightZoom); } else { @@ -1346,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(); } @@ -1358,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(); } @@ -1376,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; @@ -1400,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); } @@ -1410,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; @@ -1426,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; @@ -1440,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(); } @@ -1462,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); } @@ -1500,20 +1493,20 @@ namespace EMStudio // start creating a connection 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, 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() ); } @@ -1521,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; } @@ -1575,11 +1568,11 @@ namespace EMStudio // reset members void NodeGraph::StopRelinkConnection() { - mConPortNr = InvalidIndex16; - mConNode = nullptr; - mRelinkConnection = nullptr; - mConIsValid = false; - mTargetPort = nullptr; + m_conPortNr = InvalidIndex16; + m_conNode = nullptr; + m_relinkConnection = nullptr; + m_conIsValid = false; + m_targetPort = nullptr; } @@ -1587,12 +1580,12 @@ namespace EMStudio // reset members void NodeGraph::StopCreateConnection() { - mConPortNr = InvalidIndex16; - 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; } @@ -1672,7 +1665,7 @@ namespace EMStudio 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(); @@ -1686,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)); } @@ -1780,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)); } @@ -1967,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); } @@ -2489,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 11490d8b49..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,43 +49,43 @@ 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; } - AZ::u16 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, AZ::u16 outputPortNr, GraphNode* targetNode, AZ::u16 inputPortNr) const; NodeConnection* FindInputConnection(GraphNode* targetNode, AZ::u16 targetPortNr) const; @@ -121,7 +121,7 @@ namespace EMStudio 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); @@ -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; - AZ::u16 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 d7afe634a1..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; 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; } @@ -805,29 +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; 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->SetIsDashed(true); UpdateMouseCursor(mousePos, globalPos); - mActiveGraph->StartRelinkConnection(connection, portNr, portNode); + m_activeGraph->StartRelinkConnection(connection, portNr, portNode); return; } @@ -839,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; } @@ -847,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) { @@ -860,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; } } @@ -883,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 @@ -917,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); } } @@ -969,7 +962,7 @@ namespace EMStudio const QPoint globalPos = LocalToGlobal(mousePos); SetMousePos(globalPos); - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return; } @@ -977,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; @@ -1003,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; @@ -1027,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()) { 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 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); @@ -1146,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; @@ -1160,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; } } @@ -1275,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; } @@ -1291,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(); } } @@ -1304,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(); @@ -1326,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; } @@ -1344,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(); @@ -1360,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 @@ -1407,7 +1398,7 @@ namespace EMStudio 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) @@ -1427,7 +1418,7 @@ namespace EMStudio 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) @@ -1454,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); } @@ -1470,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; } } @@ -1495,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; } } @@ -1529,15 +1520,15 @@ 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; } } @@ -1545,9 +1536,9 @@ namespace EMStudio // return the number of selected nodes size_t NodeGraphWidget::CalcNumSelectedNodes() const { - if (mActiveGraph) + if (m_activeGraph) { - return mActiveGraph->CalcNumSelectedNodes(); + return m_activeGraph->CalcNumSelectedNodes(); } return 0; } @@ -1559,12 +1550,12 @@ namespace EMStudio 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 @@ -1574,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; } 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 d8b73ee5be..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,16 +48,16 @@ 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; } size_t CalcNumSelectedNodes() const; @@ -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 3183bc8a0f..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 @@ -52,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"); @@ -68,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 @@ -99,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 size_t numNodeGroups = mAnimGraph->GetNumNodeGroups(); + 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(""); } } @@ -137,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 ); @@ -158,25 +153,25 @@ namespace EMStudio NodeGroupWindow::NodeGroupWindow(AnimGraphPlugin* plugin) : QWidget() { - mPlugin = plugin; - mTableWidget = nullptr; - mAddAction = nullptr; + 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; } @@ -283,7 +276,7 @@ namespace EMStudio 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 int numSelectedItems = selectedItems.count(); @@ -293,7 +286,7 @@ namespace EMStudio for (int i = 0; i < numSelectedItems; ++i) { const int rowIndex = selectedItems[i]->row(); - const AZStd::string nodeGroupName = FromQtString(mTableWidget->item(rowIndex, 2)->text()); + const AZStd::string nodeGroupName = FromQtString(m_tableWidget->item(rowIndex, 2)->text()); if (AZStd::find(begin(selectedNodeGroups), end(selectedNodeGroups), nodeGroupName) == end(selectedNodeGroups)) { selectedNodeGroups.emplace_back(nodeGroupName); @@ -301,28 +294,28 @@ namespace EMStudio } // clear the lookup array - mWidgetTable.clear(); + 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 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 (int i = 0; i < numNodeGroups; ++i) @@ -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.emplace_back(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; } } @@ -455,18 +448,18 @@ namespace EMStudio // find the index for the given widget int NodeGroupWindow::FindGroupIndexByWidget(QObject* widget) const { - const auto foundGroup = AZStd::find_if(begin(mWidgetTable), end(mWidgetTable), [widget](const auto& tableEntry) + const auto foundGroup = AZStd::find_if(begin(m_widgetTable), end(m_widgetTable), [widget](const auto& tableEntry) { - return tableEntry.mWidget == widget; + return tableEntry.m_widget == widget; }); - return foundGroup != end(mWidgetTable) ? foundGroup->mGroupIndex : MCore::InvalidIndexT; + 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; @@ -504,7 +497,7 @@ 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; @@ -544,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); } @@ -559,14 +552,14 @@ 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 int numSelectedItems = selectedItems.count(); @@ -612,7 +605,7 @@ namespace EMStudio AZStd::string tempString; 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()); @@ -631,13 +624,13 @@ namespace EMStudio } // selected the next row - if (rowIndices[0] > (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]); } } @@ -646,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(); } @@ -658,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; @@ -715,7 +708,7 @@ 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 int numSelectedItems = selectedItems.count(); 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 e19b831790..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 @@ -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 @@ -98,22 +98,22 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandAnimGraphAdjustNodeGroupCallback); MCORE_DEFINECOMMANDCALLBACK(CommandAnimGraphRemoveNodeGroupCallback); - CommandAnimGraphAddNodeGroupCallback* mCreateCallback; - CommandAnimGraphAdjustNodeGroupCallback* mAdjustCallback; - CommandAnimGraphRemoveNodeGroupCallback* mRemoveCallback; + CommandAnimGraphAddNodeGroupCallback* m_createCallback; + CommandAnimGraphAdjustNodeGroupCallback* m_adjustCallback; + CommandAnimGraphRemoveNodeGroupCallback* m_removeCallback; struct WidgetLookup { - QObject* mWidget; - int mGroupIndex; + 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; - AZStd::vector 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 25e717f473..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(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); + * 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 9664011083..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) @@ -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) @@ -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 @@ -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]); } @@ -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")", 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 b7abf10da0..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) @@ -101,12 +101,12 @@ namespace EMStudio const size_t numNodeGroups = animGraph->GetNumNodeGroups(); const size_t numNodes = m_stateMachine->GetNumChildNodes(); const int numRows = aznumeric_caster(numNodeGroups + numNodes); - mTableWidget->setRowCount(numRows); + 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 0ce567c366..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,7 +817,7 @@ 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); @@ -833,7 +826,7 @@ namespace EMStudio 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(AZ::u16 portNr) @@ -841,16 +834,16 @@ namespace EMStudio 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); @@ -864,7 +857,7 @@ namespace EMStudio MCORE_UNUSED(bgColor2); QColor vizBorder; - if (mVisualize) + if (m_visualize) { vizBorder = Qt::black; } @@ -873,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 cee57b4a4f..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 @@ -58,7 +58,7 @@ namespace EMStudio 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; }; 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 78eab3d362..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 @@ -32,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(); @@ -51,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(); @@ -101,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(), &NodeHierarchyWidget::OnSelectionDone, this, &AttachmentNodesWindow::NodeSelectionFinished); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), &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); } @@ -120,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); @@ -136,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 int numAttachmentNodes = 0; // set the row count - const int numNodes = aznumeric_caster(mActor->GetNumNodes()); + 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++; @@ -160,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 (%d / %zu)", 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) @@ -182,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(); @@ -210,7 +210,7 @@ namespace EMStudio void AttachmentNodesWindow::SetActor(EMotionFX::Actor* actor) { // set the new actor - mActor = actor; + m_actor = actor; // update the interface UpdateInterface(); @@ -221,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 @@ -248,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 size_t numNodes = mActor->GetNumNodes(); + 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(); } @@ -274,11 +274,11 @@ namespace EMStudio // generate node list string AZStd::string nodeList; int lowestSelectedRow = AZStd::numeric_limits::max(); - const int numTableRows = mNodeTable->rowCount(); + 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; @@ -304,20 +304,20 @@ 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 > 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); } } @@ -342,7 +342,7 @@ namespace EMStudio // 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()); @@ -353,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().empty())); + 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 3a3c3f096e..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 @@ -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 536ff16f57..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,7 +69,7 @@ namespace EMStudio void AttachmentsHierarchyWindow::ReInit() { // clear the tree - mHierarchy->clear(); + m_hierarchy->clear(); // get the number of actor instances and iterate through them const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); @@ -88,12 +88,12 @@ 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 size_t numAttachments = actorInstance->GetNumAttachments(); 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 4b971f9c32..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 @@ -40,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); } @@ -58,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 @@ -114,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(), &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(); @@ -222,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(); @@ -238,15 +238,15 @@ namespace EMStudio } // the number of existing attachments - const int numAttachments = aznumeric_caster(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 (int i = 0; i < numAttachments; ++i) { - EMotionFX::Attachment* attachment = mActorInstance->GetAttachment(i); + EMotionFX::Attachment* attachment = m_actorInstance->GetAttachment(i); if (attachment == nullptr) { continue; @@ -254,7 +254,7 @@ namespace EMStudio EMotionFX::ActorInstance* attachmentInstance = attachment->GetAttachmentActorInstance(); EMotionFX::Actor* attachmentActor = attachmentInstance->GetActor(); - EMotionFX::Actor* attachedToActor = mActorInstance->GetActor(); + EMotionFX::Actor* attachedToActor = m_actorInstance->GetActor(); EMotionFX::Node* attachedToNode = !attachment->GetIsInfluencedByMultipleJoints() ? attachedToNode = attachedToActor->GetSkeleton()->GetNode( @@ -262,14 +262,14 @@ namespace EMStudio : 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("%zu", 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) @@ -279,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); } @@ -290,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 @@ -312,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); } @@ -321,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(); @@ -340,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; @@ -355,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."); } @@ -411,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; @@ -447,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); @@ -485,7 +485,7 @@ namespace EMStudio const int id = GetIDFromTableRow(item->row()); const AZStd::string nodeName = GetNodeNameFromTableRow(item->row()); - group.AddCommandString(AZStd::string::format("RemoveAttachment -attachmentID %d -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 @@ -499,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; } @@ -534,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; @@ -550,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); @@ -583,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) @@ -598,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); @@ -615,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; @@ -653,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); } } @@ -670,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()) @@ -686,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()) @@ -702,7 +701,7 @@ namespace EMStudio void AttachmentsWindow::OnRemoveButtonClicked() { int lowestSelectedRow = AZStd::numeric_limits::max(); - const QList selectedItems = mTableWidget->selectedItems(); + const QList selectedItems = m_tableWidget->selectedItems(); for (const QTableWidgetItem* selectedItem : selectedItems) { if (selectedItem->row() < lowestSelectedRow) @@ -713,13 +712,13 @@ namespace EMStudio RemoveTableItems(selectedItems); - if (lowestSelectedRow > (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); } } @@ -727,8 +726,8 @@ namespace EMStudio // remove all attachments void AttachmentsWindow::OnClearButtonClicked() { - mTableWidget->selectAll(); - RemoveTableItems(mTableWidget->selectedItems()); + m_tableWidget->selectAll(); + RemoveTableItems(m_tableWidget->selectedItems()); } @@ -746,14 +745,14 @@ 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(); } @@ -767,7 +766,7 @@ namespace EMStudio 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) { @@ -788,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); @@ -799,7 +798,7 @@ namespace EMStudio // get the selected node name AZStd::string AttachmentsWindow::GetSelectedNodeName() { - const QList items = mTableWidget->selectedItems(); + const QList items = m_tableWidget->selectedItems(); const size_t numItems = items.length(); if (numItems < 1) { @@ -834,7 +833,7 @@ 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::InvalidIndexT; @@ -850,7 +849,7 @@ 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 {}; @@ -864,13 +863,13 @@ namespace EMStudio int AttachmentsWindow::GetRowContainingWidget(const QWidget* widget) { // loop trough the table items and search for widget - const int numRows = mTableWidget->rowCount(); - const int numCols = mTableWidget->columnCount(); + const int numRows = m_tableWidget->rowCount(); + const int numCols = m_tableWidget->columnCount(); for (int i = 0; i < numRows; ++i) { for (int j = 0; j < numCols; ++j) { - if (mTableWidget->cellWidget(i, j) == widget) + if (m_tableWidget->cellWidget(i, j) == widget) { return i; } @@ -891,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 b3bd45fb22..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(); @@ -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 (); // init the max second column width - mMaxSecondColumnWidth = 0; + m_maxSecondColumnWidth = 0; // init the table setColumnCount(2); @@ -47,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); @@ -113,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 @@ -145,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(); @@ -159,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 { @@ -191,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(); @@ -205,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 { @@ -263,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); } } @@ -345,7 +345,7 @@ namespace EMStudio { setRowCount(0); setColumnWidth(1, 0); - mMaxSecondColumnWidth = 0; + m_maxSecondColumnWidth = 0; } 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 a9a7c6a174..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,7 +28,7 @@ namespace EMStudio LogWindowPlugin::~LogWindowPlugin() { // remove the callback from the log manager (automatically deletes from memory as well) - const size_t index = MCore::GetLogManager().FindLogCallback(mLogCallback); + 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 a53ed94909..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 %zu -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 aee88f9394..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 %zu -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 %zu -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 %zu -name \"%s\" -weight %f -manualMode %s", - mActorInstance->GetID(), - mActorInstance->GetLODLevel(), + 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 %zu -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 5619398c67..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,7 +128,7 @@ 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()); } @@ -140,11 +140,11 @@ namespace EMStudio 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,35 +300,35 @@ 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 size_t numMorphTargets = mMorphSetup->GetNumMorphTargets(); - const uint32 numPhonemeSets = mMorphTarget->GetNumAvailablePhonemeSets(); + const size_t numMorphTargets = m_morphSetup->GetNumMorphTargets(); + const uint32 numPhonemeSets = m_morphTarget->GetNumAvailablePhonemeSets(); int insertPosition = 0; for (int i = 1; i < numPhonemeSets; ++i) { @@ -336,7 +336,7 @@ namespace EMStudio bool phonemeSetFound = false; 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 int numSelectedPhonemeSets = aznumeric_caster(splittedPhonemeSets.size()); - mSelectedPhonemeSetsTable->setRowCount(numSelectedPhonemeSets); + 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); } @@ -426,15 +426,15 @@ namespace EMStudio // disable/enable buttons bool selected = !table->selectedItems().empty(); - if (table == mPossiblePhonemeSetsTable) + 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 @@ -461,7 +461,7 @@ namespace EMStudio // removes the selected phoneme sets void PhonemeSelectionWindow::RemoveSelectedPhonemeSets() { - QList selectedItems = mSelectedPhonemeSetsTable->selectedItems(); + QList selectedItems = m_selectedPhonemeSetsTable->selectedItems(); if (selectedItems.empty()) { return; @@ -475,7 +475,7 @@ namespace EMStudio } // call command to remove selected the phoneme sets - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %zu -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)) @@ -484,7 +484,7 @@ namespace EMStudio } else { - mDirtyFlag = true; + m_dirtyFlag = true; } } @@ -492,7 +492,7 @@ namespace EMStudio // adds the selected phoneme sets void PhonemeSelectionWindow::AddSelectedPhonemeSets() { - QList selectedItems = mSelectedPhonemeSetsTable->selectedItems(); + QList selectedItems = m_selectedPhonemeSetsTable->selectedItems(); if (selectedItems.empty()) { return; @@ -506,7 +506,7 @@ namespace EMStudio } // call command to add the selected phoneme sets - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %zu -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)) @@ -515,7 +515,7 @@ namespace EMStudio } else { - mDirtyFlag = true; + m_dirtyFlag = true; } } @@ -523,7 +523,7 @@ namespace EMStudio // clear the selected phoneme sets void PhonemeSelectionWindow::ClearSelectedPhonemeSets() { - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %zu -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)) @@ -532,7 +532,7 @@ namespace EMStudio } else { - mDirtyFlag = true; + m_dirtyFlag = true; } } @@ -590,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 a6bffffb75..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; }; @@ -138,23 +138,23 @@ namespace EMStudio private: // the morph target - EMotionFX::Actor* mActor; - EMotionFX::MorphTarget* mMorphTarget; - size_t 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 5943263e3d..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 @@ -120,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"); @@ -132,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 @@ -171,15 +165,13 @@ 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 { @@ -196,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)) @@ -229,7 +219,7 @@ namespace EMStudio MotionSetManagementWindow::MotionSetManagementWindow(MotionSetsWindowPlugin* parentPlugin, QWidget* parent) : QWidget(parent) { - mPlugin = parentPlugin; + m_plugin = parentPlugin; } @@ -248,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"); @@ -311,7 +301,7 @@ namespace EMStudio toolBar->addWidget(m_searchWidget); layout->addWidget(toolBar); - layout->addWidget(mMotionSetsTree); + layout->addWidget(m_motionSetsTree); ReInit(); UpdateInterface(); @@ -373,7 +363,7 @@ namespace EMStudio void MotionSetManagementWindow::ReInit() { // Get the selected items in the motion set tree widget.. - const QList selectedItems = mMotionSetsTree->selectedItems(); + const QList selectedItems = m_motionSetsTree->selectedItems(); const int numSelectedItems = selectedItems.size(); // Create and fill an array containing ids of all selected motion sets. @@ -385,11 +375,11 @@ namespace EMStudio }); // 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; @@ -409,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"))); @@ -418,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()) @@ -459,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 QList selectedItems = m_motionSetsTree->selectedItems(); const size_t numSelected = selectedItems.count(); if (numSelected != 1) { - mPlugin->SetSelectedSet(nullptr); + m_plugin->SetSelectedSet(nullptr); } else { @@ -481,7 +471,7 @@ namespace EMStudio if (selectedSet) { - mPlugin->SetSelectedSet(selectedSet); + m_plugin->SetSelectedSet(selectedSet); } } } @@ -498,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 @@ -537,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 @@ -562,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) { @@ -611,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); @@ -624,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) @@ -639,7 +629,7 @@ namespace EMStudio } ++it; } - connect(mMotionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); + connect(m_motionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); if (selectionChanged) { OnSelectionChanged(); @@ -649,7 +639,7 @@ 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 QList selectedItems = m_motionSetsTree->selectedItems(); outSelectedMotionSets.resize(selectedItems.size()); @@ -721,7 +711,7 @@ namespace EMStudio void MotionSetManagementWindow::OnRemoveSelectedMotionSets() { - const QList selectedItems = mMotionSetsTree->selectedItems(); + const QList selectedItems = m_motionSetsTree->selectedItems(); if (selectedItems.empty()) { return; @@ -752,7 +742,7 @@ namespace EMStudio 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); @@ -785,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; } @@ -880,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 @@ -915,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 @@ -996,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 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 368f5bd9c7..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 @@ -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 3fd928c60c..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 @@ -124,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"); @@ -136,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); @@ -169,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)) @@ -202,7 +200,7 @@ namespace EMStudio MotionSetWindow::MotionSetWindow(MotionSetsWindowPlugin* parentPlugin, QWidget* parent) : QWidget(parent) { - mPlugin = parentPlugin; + m_plugin = parentPlugin; } @@ -253,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); @@ -328,11 +326,11 @@ namespace EMStudio void MotionSetWindow::ReInit() { - EMotionFX::MotionSet* selectedSet = mPlugin->GetSelectedSet(); + 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 { @@ -344,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; } @@ -373,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); } @@ -386,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); } @@ -416,9 +410,9 @@ namespace EMStudio 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); } @@ -811,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); @@ -866,7 +860,7 @@ namespace EMStudio void MotionSetWindow::OnAddNewEntry() { - EMotionFX::MotionSet* selectedSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* selectedSet = m_plugin->GetSelectedSet(); if (!selectedSet) { return; @@ -903,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; @@ -1068,7 +1062,7 @@ namespace EMStudio void MotionSetWindow::OnRemoveMotions() { - EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (!motionSet) { return; @@ -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; @@ -1412,7 +1406,7 @@ namespace EMStudio 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; @@ -1442,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; @@ -1603,7 +1597,7 @@ namespace EMStudio : QTableWidget(parent) { // keep the parent plugin - mPlugin = parentPlugin; + m_plugin = parentPlugin; // enable drop only setAcceptDrops(true); @@ -1620,7 +1614,7 @@ namespace EMStudio void MotionSetTableWidget::dropEvent(QDropEvent* event) { - mPlugin->GetMotionSetWindow()->dropEvent(event); + m_plugin->GetMotionSetWindow()->dropEvent(event); } @@ -1639,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; @@ -1682,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"); @@ -1701,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); @@ -1823,13 +1817,13 @@ namespace EMStudio // add each command AZStd::string commandString; - for (size_t validID : mValids) + for (size_t validID : m_valids) { // get the motion ID and the modified ID - AZStd::string& motionID = mMotionIDs[validID]; - const AZStd::string& modifiedID = mModifiedMotionIDs[mMotionToModifiedMap[validID]]; + 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 @@ -1844,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); } @@ -1904,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) @@ -1916,59 +1910,59 @@ 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; } // 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 (const AZStd::string& motionID : mMotionIDs) + 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) @@ -1976,7 +1970,7 @@ namespace EMStudio case 0: { tempString = motionID.c_str(); - AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */); + AzFramework::StringFunc::Replace(tempString, m_stringALineEdit->text().toUtf8().data(), m_stringBLineEdit->text().toUtf8().data(), true /* case sensitive */); newMotionID = tempString.c_str(); break; } @@ -1984,7 +1978,7 @@ namespace EMStudio case 1: { tempString = motionID.c_str(); - AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, true /* replace first */, false /* replace last */); + 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; } @@ -1992,21 +1986,21 @@ namespace EMStudio case 2: { tempString = motionID.c_str(); - AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, false /* replace first */, true /* replace last */); + 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(), motionID); - const size_t modifiedIndex = iterator - mModifiedMotionIDs.begin(); - mModifiedMotionIDs[modifiedIndex] = newMotionID; - mMotionToModifiedMap.push_back(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; @@ -2015,18 +2009,18 @@ namespace EMStudio 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 size_t itemFoundCounter = 0; - const size_t numMotionEntries = mMotionSet->GetNumMotionEntries(); + 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) @@ -2045,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(aznumeric_caster(i), 0, beforeTableWidgetItem); - mTableWidget->setItem(aznumeric_caster(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.empty()) && (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); } } } @@ -2102,7 +2096,7 @@ namespace EMStudio return nullptr; } - const EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + const EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (!motionSet) { return nullptr; 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 33b3828e5a..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; }; @@ -187,7 +187,7 @@ namespace EMStudio 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 3860edd009..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 @@ -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) == InvalidIndex) + 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) == InvalidIndex) + 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(); } 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 419535da81..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(), &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(); @@ -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,51 +205,51 @@ 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. @@ -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); @@ -388,8 +388,8 @@ namespace EMStudio return; } - mMotionExtractionNodeSelectionWindow->Update(actorInstance->GetID()); - mMotionExtractionNodeSelectionWindow->show(); + m_motionExtractionNodeSelectionWindow->Update(actorInstance->GetID()); + m_motionExtractionNodeSelectionWindow->show(); } 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 cb7371a74d..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 @@ -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 c909098dae..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 int rowIndex = 0; - mMotionTable->insertRow(rowIndex); - mMotionTable->setRowHeight(rowIndex, 21); + 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,7 +314,7 @@ namespace EMStudio uint32 MotionListWindow::FindRowByMotionID(uint32 motionID) { // iterate through the rows and compare the motion IDs - const int rowCount = mMotionTable->rowCount(); + 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,10 +463,10 @@ 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 size_t numSelectedMotions = selectionList.GetNumSelectedMotions(); @@ -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,7 +528,7 @@ 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 int numSelectedItems = selectedItems.count(); @@ -546,20 +546,20 @@ namespace EMStudio } // clear the selected motion IDs - mSelectedMotionIDs.clear(); + m_selectedMotionIDs.clear(); // get the number of selected items and iterate through them - mSelectedMotionIDs.reserve(rowIndices.size()); + m_selectedMotionIDs.reserve(rowIndices.size()); for (const int rowIndex : rowIndices) { - mSelectedMotionIDs.push_back(GetMotionID(rowIndex)); + m_selectedMotionIDs.push_back(GetMotionID(rowIndex)); } // unselect all motions GetCommandManager()->GetCurrentSelection().ClearMotionSelection(); // get the number of selected motions and iterate through them - for (uint32 selectedMotionID : mSelectedMotionIDs) + for (uint32 selectedMotionID : m_selectedMotionIDs) { // find the motion by name in the motion library and select it EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(selectedMotionID); @@ -570,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(); @@ -748,7 +748,7 @@ namespace EMStudio MotionTableWidget::MotionTableWidget(MotionWindowPlugin* parentPlugin, QWidget* parent) : QTableWidget(parent) { - mPlugin = parentPlugin; + m_plugin = parentPlugin; // enable dragging setDragEnabled(true); 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 6596a7c868..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); } @@ -70,21 +62,21 @@ namespace EMStudio 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 @@ -111,8 +103,7 @@ namespace EMStudio const size_t numSelectedMotions = selection.GetNumSelectedMotions(); const bool isEnabled = (numSelectedMotions != 0); - mMotionRetargetingButton->setEnabled(isEnabled); - //mRenderMotionBindPose->setEnabled(isEnabled); + m_motionRetargetingButton->setEnabled(isEnabled); if (isEnabled == false) { @@ -122,17 +113,17 @@ namespace EMStudio // iterate through the selected motions 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 1452d0ac93..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 @@ -40,7 +40,7 @@ namespace EMStudio public: SaveDirtyMotionFilesCallback(MotionWindowPlugin* plugin) - : SaveDirtyFilesCallback() { mPlugin = plugin; } + : SaveDirtyFilesCallback() { m_plugin = plugin; } ~SaveDirtyMotionFilesCallback() {} enum @@ -72,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); } } @@ -87,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; } @@ -110,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 @@ -144,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(); } @@ -180,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); @@ -194,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); } @@ -294,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(); } } @@ -355,7 +355,7 @@ namespace EMStudio // find the lowest row selected int lowestRowSelected = AZStd::numeric_limits::max(); - const QList selectedItems = mMotionListWindow->GetMotionTable()->selectedItems(); + const QList selectedItems = m_motionListWindow->GetMotionTable()->selectedItems(); for (const QTableWidgetItem* selectedItem : selectedItems) { lowestRowSelected = AZStd::min(lowestRowSelected, selectedItem->row()); @@ -366,19 +366,19 @@ namespace EMStudio CommandSystem::RemoveMotions(motionsToRemove, &failedRemoveMotions); // selected the next row - if (lowestRowSelected > (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(); } } @@ -422,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); } } } @@ -434,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); } @@ -471,15 +471,15 @@ 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 - AZStd::erase_if(mMotionEntries, [](MotionTableEntry* entry) + AZStd::erase_if(m_motionEntries, [](MotionTableEntry* entry) { // 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) == InvalidIndex) + if (EMotionFX::GetMotionManager().FindMotionIndexByID(entry->m_motionId) == InvalidIndex) { delete entry; return true; @@ -488,13 +488,13 @@ namespace EMStudio }); // update the motion list window - mMotionListWindow->ReInit(); + m_motionListWindow->ReInit(); } void MotionWindowPlugin::UpdateMotions() { - mMotionRetargetingWindow->UpdateMotions(); + m_motionRetargetingWindow->UpdateMotions(); } @@ -518,30 +518,30 @@ 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); } - 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(); } } @@ -558,7 +558,7 @@ namespace EMStudio const size_t numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); const size_t numSelectedMotions = selectionList.GetNumSelectedMotions(); - mInternalMotionInstanceSelection.clear(); + s_internalMotionInstanceSelection.clear(); for (size_t i = 0; i < numSelectedActorInstances; ++i) { @@ -575,23 +575,23 @@ namespace EMStudio 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 auto foundEntry = AZStd::find_if(begin(mMotionEntries), end(mMotionEntries), [motionID](const MotionTableEntry* entry) + const auto foundEntry = AZStd::find_if(begin(m_motionEntries), end(m_motionEntries), [motionID](const MotionTableEntry* entry) { - return entry->mMotionID == motionID; + return entry->m_motionId == motionID; }); - return foundEntry != end(mMotionEntries) ? *foundEntry : nullptr; + return foundEntry != end(m_motionEntries) ? *foundEntry : nullptr; } @@ -613,9 +613,9 @@ namespace EMStudio 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); @@ -655,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); } @@ -669,7 +669,7 @@ 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) @@ -682,8 +682,8 @@ namespace EMStudio // constructor MotionWindowPlugin::MotionTableEntry::MotionTableEntry(EMotionFX::Motion* motion) { - mMotionID = motion->GetID(); - mMotion = motion; + m_motionId = motion->GetID(); + m_motion = motion; } @@ -829,7 +829,7 @@ namespace EMStudio { MCORE_UNUSED(commandLine); CommandSystem::CommandImportMotion* importMotionCommand = static_cast(command); - return CallbackAddMotionByID(importMotionCommand->mOldMotionID); + return CallbackAddMotionByID(importMotionCommand->m_oldMotionId); } @@ -847,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 1a95899c32..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 @@ -33,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(); @@ -52,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(); @@ -116,7 +103,7 @@ namespace EMStudio tableLayout->setMargin(0); tableLayout->addLayout(buttonLayout); - tableLayout->addWidget(mNodeTable); + tableLayout->addWidget(m_nodeTable); layout->addLayout(tableLayout); //layout->addLayout( editLayout ); @@ -125,12 +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(mNodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &NodeGroupWidget::NodeSelectionFinished); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), &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); } @@ -138,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 / %zu)", ((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) @@ -189,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); } @@ -213,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(); @@ -231,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(); @@ -243,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 @@ -270,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; } @@ -299,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()); @@ -308,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), @@ -321,13 +305,13 @@ 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); } } @@ -352,12 +336,12 @@ 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), - /*nodeAction=*/ mNodeAction + /*nodeAction=*/ m_nodeAction ); if (EMStudio::GetCommandManager()->ExecuteCommand(command, outResult) == false) { @@ -369,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 6861e77756..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 @@ -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/NodeInfo.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeInfo.cpp index a402dc869e..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 @@ -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,9 +53,9 @@ 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(); } } 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 7b47b8cb43..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,11 +278,11 @@ 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(); 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 582e9e9eac..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,12 +76,12 @@ 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::string m_string; + AZStd::string m_tempGroupName; AZStd::unordered_set m_visibleNodeIndices; AZStd::unordered_set m_selectedNodeIndices; 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 4e8e51b601..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,13 +118,13 @@ 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 size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); for (size_t i = 0; i < numActorInstances; ++i) @@ -132,15 +132,15 @@ namespace EMStudio 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,23 +196,23 @@ namespace EMStudio m_excludeFromBoundsBrowseEdit->setEnabled(true); AZStd::vector jointsExcludedFromBounds; - if (mActorInstance) + if (m_actorInstance) { - const size_t numNodes = mActor->GetNumNodes(); + 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()); + m_nameEdit->setEnabled(true); + m_nameEdit->setText(m_actor->GetName()); } void ActorPropertiesWindow::GetNodeName(const AZStd::vector& joints, AZStd::string* outNodeName, uint32* outActorID) @@ -226,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) @@ -299,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; @@ -315,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 @@ -329,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)) @@ -353,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) @@ -395,7 +395,7 @@ namespace EMStudio EMotionFX::Actor* actor = actorInstance->GetActor(); EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); - const size_t numJoints = mActor->GetNumNodes(); + const size_t numJoints = m_actor->GetNumNodes(); // Include all joints first. for (size_t i = 0; i < numJoints; ++i) @@ -417,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 67568d80b0..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 @@ -69,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/MirrorSetupWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.cpp index fc01f68efe..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,7 +315,7 @@ 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()); @@ -336,12 +329,12 @@ namespace EMStudio // 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,18 +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); - AZStd::fill(mMap.begin(), mMap.end(), InvalidIndex); + m_map.resize(numNodes); + AZStd::fill(m_map.begin(), m_map.end(), InvalidIndex); } } @@ -481,7 +474,7 @@ namespace EMStudio { if (!actor) { - mCurrentList->setRowCount(0); + m_currentList->setRowCount(0); return; } @@ -499,7 +492,7 @@ namespace EMStudio numRows++; } } - mCurrentList->setRowCount(numRows); + m_currentList->setRowCount(numRows); // fill the rows int rowIndex = 0; @@ -510,34 +503,34 @@ namespace EMStudio if (currentName.contains(filterString, Qt::CaseInsensitive) || filterString.isEmpty()) { // mark if there is a mapping or not - const bool mapped = (mMap[node->GetNodeIndex()] != InvalidIndex); + 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 (AZStd::find(begin(mCurrentBoneList), end(mCurrentBoneList), node->GetNodeIndex()) != end(mCurrentBoneList)) + 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; } } @@ -549,7 +542,7 @@ namespace EMStudio { if (!actor) { - mSourceList->setRowCount(0); + m_sourceList->setRowCount(0); return; } @@ -567,7 +560,7 @@ namespace EMStudio numRows++; } } - mSourceList->setRowCount(numRows); + m_sourceList->setRowCount(numRows); // fill the rows int rowIndex = 0; @@ -578,34 +571,34 @@ namespace EMStudio 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; } } @@ -617,7 +610,7 @@ namespace EMStudio { if (!currentActor) { - mMappingTable->setRowCount(0); + m_mappingTable->setRowCount(0); return; } @@ -625,24 +618,24 @@ namespace EMStudio QString currentName; QString sourceName; const int numNodes = aznumeric_caster(currentActor->GetNumNodes()); - mMappingTable->setRowCount(numNodes); + 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] != InvalidIndex) + 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()); } } } @@ -651,24 +644,24 @@ namespace EMStudio // 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; @@ -692,21 +685,21 @@ namespace EMStudio EMotionFX::Actor* currentActor = GetSelectedActor(); // update the map - const size_t 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 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 == InvalidIndex) @@ -715,25 +708,25 @@ namespace EMStudio } else { - mappedItem->setIcon(*mMappedIcon); + mappedItem->setIcon(*m_mappedIcon); } } // update source table 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 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) @@ -742,7 +735,7 @@ namespace EMStudio } else { - mappedItem->setIcon(*mMappedIcon); + mappedItem->setIcon(*m_mappedIcon); } } } @@ -750,18 +743,18 @@ namespace EMStudio { 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 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) @@ -770,18 +763,18 @@ namespace EMStudio } else { - mappedItem->setIcon(*mMappedIcon); + mappedItem->setIcon(*m_mappedIcon); } } } } // update the mapping table - QTableWidgetItem* item = mMappingTable->item(aznumeric_caster(currentNodeIndex), 1); + QTableWidgetItem* item = m_mappingTable->item(aznumeric_caster(currentNodeIndex), 1); if (!item && sourceNodeIndex != InvalidIndex) { item = new QTableWidgetItem(); - mMappingTable->setItem(aznumeric_caster(currentNodeIndex), 1, item); + m_mappingTable->setItem(aznumeric_caster(currentNodeIndex), 1, item); } if (sourceNodeIndex == InvalidIndex) @@ -827,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); @@ -881,7 +874,7 @@ namespace EMStudio // now update our mapping data const size_t numNodes = currentActor->GetNumNodes(); - AZStd::fill(mMap.begin(), AZStd::next(mMap.begin(), numNodes), InvalidIndex); + 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 size_t numEntries = nodeMap->GetNumEntries(); @@ -902,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 @@ -952,7 +945,7 @@ namespace EMStudio for (size_t i = 0; i < numNodes; ++i) { // skip unmapped entries - if (mMap[i] == InvalidIndex) + if (m_map[i] == InvalidIndex) { continue; } @@ -960,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()); } } @@ -1018,7 +1011,7 @@ namespace EMStudio } const size_t numNodes = currentActor->GetNumNodes(); - return AZStd::all_of(mMap.begin(), AZStd::next(mMap.begin(), numNodes), [](const size_t nodeIndex) + return AZStd::all_of(m_map.begin(), AZStd::next(m_map.begin(), numNodes), [](const size_t nodeIndex) { return nodeIndex != InvalidIndex; }); @@ -1037,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); } @@ -1054,7 +1047,7 @@ 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; @@ -1066,15 +1059,15 @@ namespace EMStudio for (size_t i = 0; i < numNodes; ++i) { // skip already setup mappings - if (mMap[i] != InvalidIndex) + 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++; } } @@ -1117,19 +1110,19 @@ namespace EMStudio { 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] = InvalidIndex; + m_map[i] = InvalidIndex; } } else { - mMap[i] = InvalidIndex; + m_map[i] = InvalidIndex; } } } @@ -1149,7 +1142,7 @@ namespace EMStudio AZStd::string commandString = AZStd::string::format("AdjustActor -actorID %d -mirrorSetup \"", currentActor->GetID()); for (size_t i = 0; i < currentActor->GetNumNodes(); ++i) { - size_t sourceNode = mMap[i]; + size_t sourceNode = m_map[i]; if (sourceNode != InvalidIndex && sourceNode != i) { commandString += currentActor->GetSkeleton()->GetNode(i)->GetName(); 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 660359ba4a..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 @@ -63,25 +63,25 @@ 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; - AZStd::vector 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); 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 61b6c44dbb..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 @@ -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); } } @@ -52,13 +52,13 @@ namespace EMStudio for (const ObjectPointer& objPointer : objects) { // get the current object pointer and skip directly if the type check fails - 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; } @@ -72,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; } @@ -177,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; } @@ -221,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; } @@ -281,7 +281,7 @@ namespace EMStudio void SceneManagerPlugin::ReInit() { // reinit the actors window - mActorsWindow->ReInit(); + m_actorsWindow->ReInit(); // update the interface UpdateInterface(); @@ -292,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/PlaybackOptionsGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackOptionsGroup.cpp index 14e2c79b88..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 @@ -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 c1c440d0d8..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 @@ -19,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)); } @@ -52,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(); @@ -68,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); @@ -105,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 || @@ -117,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 || @@ -137,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; } @@ -147,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); } @@ -163,26 +161,26 @@ namespace EMStudio { if (delFromMem) { - for (TimeTrackElement* element : mElements) + for (TimeTrackElement* element : m_elements) { delete element; } } - mElements.clear(); + m_elements.clear(); } // get the track element at a given pixel TimeTrackElement* TimeTrack::GetElementAt(int32 x, int32 y) const { - if (mVisible == false) + if (m_visible == false) { return nullptr; } // for all elements - for (TimeTrackElement* element : mElements) + for (TimeTrackElement* element : m_elements) { // check if its inside if (element->GetIsVisible() == false) @@ -203,12 +201,12 @@ namespace EMStudio // calculate the number of selected elements size_t TimeTrack::CalcNumSelectedElements() const { - if (mVisible == false) + if (m_visible == false) { return 0; } - return AZStd::accumulate(begin(mElements), end(mElements), size_t{0}, [](size_t total, const TimeTrackElement* element) + return AZStd::accumulate(begin(m_elements), end(m_elements), size_t{0}, [](size_t total, const TimeTrackElement* element) { return total + element->GetIsSelected(); }); @@ -218,16 +216,16 @@ namespace EMStudio // find and return the first of the selected elements TimeTrackElement* TimeTrack::GetFirstSelectedElement() const { - if (mVisible == false) + if (m_visible == false) { return nullptr; } - const auto foundElement = AZStd::find_if(begin(mElements), end(mElements), [](const TimeTrackElement* element) + const auto foundElement = AZStd::find_if(begin(m_elements), end(m_elements), [](const TimeTrackElement* element) { return element->GetIsSelected(); }); - return foundElement != end(mElements) ? *foundElement : nullptr; + return foundElement != end(m_elements) ? *foundElement : nullptr; } @@ -239,11 +237,11 @@ namespace EMStudio 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) @@ -262,7 +260,7 @@ namespace EMStudio void TimeTrack::SelectElementsInRect(const QRect& rect, bool overwriteCurSelection, bool select, bool toggleMode) { // get the number of elements and iterate through them - for (TimeTrackElement* element : mElements) + for (TimeTrackElement* element : m_elements) { // get the current element and the corresponding rect QRect elementRect = element->CalcRect(); 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 55dcae73c3..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,20 +37,20 @@ 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 size_t GetNumElements() const { return mElements.size(); } - MCORE_INLINE TimeTrackElement* GetElement(size_t index) const { return mElements[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; @@ -60,14 +60,14 @@ namespace EMStudio { 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); } size_t CalcNumSelectedElements() const; @@ -75,42 +75,42 @@ namespace EMStudio 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) const { 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) 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 78e911eb0a..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, 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 1e0d38486b..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 @@ -38,25 +38,25 @@ namespace EMStudio 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 size_t 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(size_t 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; - size_t 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 6f8ab95891..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,11 +103,11 @@ namespace EMStudio RemoveAllTracks(); // get rid of the cursors - delete mZoomInCursor; - delete mZoomOutCursor; + delete m_zoomInCursor; + delete m_zoomOutCursor; // get rid of the motion infos - for (MotionInfo* motionInfo : mMotionInfos) + for (MotionInfo* motionInfo : m_motionInfos) { delete motionInfo; } @@ -162,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; } } @@ -196,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); @@ -242,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; @@ -284,7 +284,7 @@ namespace EMStudio // add a new track void TimeViewPlugin::AddTrack(TimeTrack* track) { - mTracks.emplace_back(track); + m_tracks.emplace_back(track); SetRedrawFlag(); } @@ -293,18 +293,18 @@ namespace EMStudio void TimeViewPlugin::RemoveAllTracks() { // get the number of time tracks and iterate through them - for (TimeTrack* track : mTracks) + for (TimeTrack* track : m_tracks) { delete track; } - mTracks.clear(); + m_tracks.clear(); SetRedrawFlag(); } TimeTrack* TimeViewPlugin::FindTrackByElement(TimeTrackElement* element) const { - const auto foundTrack = AZStd::find_if(begin(mTracks), end(mTracks), [element](const TimeTrack* timeTrack) + const auto foundTrack = AZStd::find_if(begin(m_tracks), end(m_tracks), [element](const TimeTrack* timeTrack) { // get the number of time track elements and iterate through them const size_t numElements = timeTrack->GetNumElements(); @@ -317,15 +317,15 @@ namespace EMStudio } return false; }); - return foundTrack != end(mTracks) ? *foundTrack : nullptr; + return foundTrack != end(m_tracks) ? *foundTrack : nullptr; } AZ::Outcome TimeViewPlugin::FindTrackIndex(const TimeTrack* track) const { - const auto foundTrack = AZStd::find(begin(mTracks), end(mTracks), track); - if (foundTrack != end(mTracks)) + const auto foundTrack = AZStd::find(begin(m_tracks), end(m_tracks), track); + if (foundTrack != end(m_tracks)) { - return AZ::Success(static_cast(AZStd::distance(begin(mTracks), foundTrack))); + return AZ::Success(static_cast(AZStd::distance(begin(m_tracks), foundTrack))); } return AZ::Failure(); } @@ -378,7 +378,7 @@ namespace EMStudio } if (outFrameNr) { - *outFrameNr = aznumeric_cast(timeValue / (double)mFPS); + *outFrameNr = aznumeric_cast(timeValue / (double)m_fps); } } @@ -388,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) { @@ -411,7 +411,7 @@ namespace EMStudio } if (outFrameNr) { - *outFrameNr = aznumeric_cast(pixelTime / (double)mFPS); + *outFrameNr = aznumeric_cast(pixelTime / (double)m_fps); } } @@ -423,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; } } @@ -436,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 { @@ -462,10 +461,10 @@ namespace EMStudio TimeTrackElement* TimeViewPlugin::GetElementAt(int32 x, int32 y) { // for all tracks - for (const TimeTrack* track : mTracks) + for (const TimeTrack* track : m_tracks) { // check if the absolute pixel is inside - TimeTrackElement* result = track->GetElementAt(aznumeric_cast(x + mScrollX), y); + TimeTrackElement* result = track->GetElementAt(aznumeric_cast(x + m_scrollX), y); if (result) { return result; @@ -480,11 +479,11 @@ namespace EMStudio TimeTrack* TimeViewPlugin::GetTrackAt(int32 y) { // for all tracks - const auto foundTrack = AZStd::find_if(begin(mTracks), end(mTracks), [y](const TimeTrack* track) + const auto foundTrack = AZStd::find_if(begin(m_tracks), end(m_tracks), [y](const TimeTrack* track) { return track->GetIsInside(y); }); - return foundTrack != end(mTracks) ? *foundTrack : nullptr; + return foundTrack != end(m_tracks) ? *foundTrack : nullptr; } @@ -492,7 +491,7 @@ namespace EMStudio void TimeViewPlugin::UnselectAllElements() { // for all tracks - for (TimeTrack* track : mTracks) + for (TimeTrack* track : m_tracks) { // for all elements, deselect it const size_t numElems = track->GetNumElements(); @@ -510,7 +509,7 @@ namespace EMStudio // return the time of the current time marker, in seconds double TimeViewPlugin::GetCurrentTime() const { - return mCurTime; + return m_curTime; } @@ -518,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 @@ -563,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; } @@ -583,7 +582,7 @@ namespace EMStudio } // for all tracks - for (TimeTrack* track : mTracks) + for (TimeTrack* track : m_tracks) { if (track->GetIsVisible() == false || track->GetIsEnabled() == false) { @@ -624,7 +623,7 @@ namespace EMStudio void TimeViewPlugin::RenderElementTimeHandles(QPainter& painter, uint32 dataWindowHeight, const QPen& pen) { // for all tracks - for (const TimeTrack* track : mTracks) + for (const TimeTrack* track : m_tracks) { if (track->GetIsVisible() == false) { @@ -658,7 +657,7 @@ namespace EMStudio void TimeViewPlugin::DisableAllToolTips() { // for all tracks - for (const TimeTrack* track : mTracks) + for (const TimeTrack* track : m_tracks) { // for all elements const size_t numElems = track->GetNumElements(); @@ -676,7 +675,7 @@ namespace EMStudio bool TimeViewPlugin::FindResizePoint(int32 x, int32 y, TimeTrackElement** outElement, uint32* outID) { // for all tracks - for (const TimeTrack* track : mTracks) + for (const TimeTrack* track : m_tracks) { if (track->GetIsVisible() == false) { @@ -720,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; @@ -817,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); } @@ -843,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); } } @@ -867,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; } @@ -885,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(); } @@ -900,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(); @@ -937,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) { @@ -988,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; } @@ -1020,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; @@ -1031,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(); @@ -1065,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; @@ -1076,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(); @@ -1106,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(); @@ -1116,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); @@ -1131,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(); } } @@ -1140,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); @@ -1150,14 +1103,14 @@ namespace EMStudio void TimeViewPlugin::UpdateSelection() { - mSelectedEvents.clear(); - 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 size_t numTracks = GetNumTracks(); @@ -1189,10 +1142,10 @@ namespace EMStudio if (element->GetIsSelected()) { EventSelectionItem selectionItem; - selectionItem.mMotion = mMotion; - selectionItem.mTrackNr = trackNr.GetValue(); - selectionItem.mEventNr = element->GetElementNumber(); - mSelectedEvents.emplace_back(selectionItem); + selectionItem.m_motion = m_motion; + selectionItem.m_trackNr = trackNr.GetValue(); + selectionItem.m_eventNr = element->GetElementNumber(); + m_selectedEvents.emplace_back(selectionItem); } } } @@ -1201,10 +1154,10 @@ namespace EMStudio void TimeViewPlugin::ReInit() { - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == InvalidIndex) + 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 @@ -1217,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(); @@ -1268,14 +1221,14 @@ namespace EMStudio timeTrack->AddElement(element); } - // Select the element if in mSelectedEvents. - for (const EventSelectionItem& selectionItem : mSelectedEvents) + // Select the element if in m_selectedEvents. + for (const EventSelectionItem& selectionItem : m_selectedEvents) { - if (mMotion != selectionItem.mMotion) + if (m_motion != selectionItem.m_motion) { continue; } - if (selectionItem.mTrackNr == trackIndex && selectionItem.mEventNr == eventIndex) + if (selectionItem.m_trackNr == trackIndex && selectionItem.m_eventNr == eventIndex) { element->SetIsSelected(true); break; @@ -1367,7 +1320,7 @@ namespace EMStudio timeTrack->SetElementCount(numMotionEvents); } } - else // mMotion == nullptr + else // m_motion == nullptr { const size_t numEventTracks = GetNumTracks(); for (size_t trackIndex = 0; trackIndex < numEventTracks; ++trackIndex) @@ -1385,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; } } @@ -1416,27 +1368,27 @@ namespace EMStudio // find the motion info for the given motion id TimeViewPlugin::MotionInfo* TimeViewPlugin::FindMotionInfo(uint32 motionID) { - const auto foundMotionInfo = AZStd::find_if(begin(mMotionInfos), end(mMotionInfos), [motionID](const MotionInfo* motionInfo) + const auto foundMotionInfo = AZStd::find_if(begin(m_motionInfos), end(m_motionInfos), [motionID](const MotionInfo* motionInfo) { - return motionInfo->mMotionID == motionID; + return motionInfo->m_motionId == motionID; }); - if (foundMotionInfo != end(mMotionInfos)) + 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.emplace_back(motionInfo); + motionInfo->m_motionId = motionID; + motionInfo->m_initialized = false; + m_motionInfos.emplace_back(motionInfo); return motionInfo; } void TimeViewPlugin::Select(const AZStd::vector& selection) { - mSelectedEvents = selection; + m_selectedEvents = selection; // get the number of tracks in the time view and iterate through them const size_t numTracks = GetNumTracks(); @@ -1455,8 +1407,8 @@ namespace EMStudio for (const EventSelectionItem& selectionItem : selection) { - TimeTrack* track = GetTrack(selectionItem.mTrackNr); - TimeTrackElement* element = track->GetElement(selectionItem.mEventNr); + TimeTrack* track = GetTrack(selectionItem.m_trackNr); + TimeTrackElement* element = track->GetElement(selectionItem.m_eventNr); element->SetIsSelected(true); } @@ -1472,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; } @@ -1496,7 +1448,7 @@ namespace EMStudio void TimeViewPlugin::AddMotionEvent(int32 x, int32 y) { - if (mMotion == nullptr) + if (m_motion == nullptr) { return; } @@ -1560,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) { @@ -1575,7 +1527,7 @@ namespace EMStudio // adjust the motion event AZStd::string outResult, command; - command = AZStd::string::format("AdjustMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu -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()); @@ -1589,23 +1541,23 @@ 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) == InvalidIndex) + if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex) { return; } // get the motion event table - // MotionEventTable& eventTable = mMotion->GetEventTable(); + // MotionEventTable& eventTable = m_motion->GetEventTable(); AZStd::vector eventNumbers; // get the number of tracks in the time view and iterate through them @@ -1653,18 +1605,17 @@ namespace EMStudio AZStd::string result; MCore::CommandGroup commandGroup("Remove motion events"); - if (mMotion == nullptr) + if (m_motion == nullptr) { return; } - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == InvalidIndex) + if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex) { return; } // get the motion event table - // MotionEventTable& eventTable = mMotion->GetEventTable(); AZStd::vector eventNumbers; // get the number of tracks in the time view and iterate through them @@ -1732,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) { @@ -1770,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); } @@ -1786,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) @@ -1808,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()); } @@ -1820,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; } } @@ -1838,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(); @@ -1851,7 +1802,7 @@ namespace EMStudio 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(); @@ -1860,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; } @@ -1868,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; @@ -1889,17 +1840,17 @@ namespace EMStudio } else { - if (mMotion) + if (m_motion) { - for (const TimeTrack* track : mTracks) + for (const TimeTrack* track : m_tracks) { if (track->GetIsVisible() == false) { continue; } - mMaxHeight += track->GetHeight(); - mMaxHeight += 1; + m_maxHeight += track->GetHeight(); + m_maxHeight += 1; } } } @@ -1910,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); } } @@ -1950,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); } } @@ -1960,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; } } @@ -2070,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(); @@ -2078,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) @@ -2120,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; @@ -2136,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 e6af4e1ae1..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 @@ -39,9 +39,9 @@ namespace EMStudio EMotionFX::MotionEvent* GetMotionEvent(); EMotionFX::MotionEventTrack* GetEventTrack(); - size_t 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 @@ -88,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); @@ -108,15 +108,15 @@ 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(size_t index) { return mTracks[index]; } - size_t GetNumTracks() const { return mTracks.size(); } + 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; @@ -132,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); @@ -151,12 +151,12 @@ namespace EMStudio void ZoomRect(const QRect& rect); - size_t GetNumSelectedEvents() { return mSelectedEvents.size(); } - EventSelectionItem GetSelectedEvent(size_t 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 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; @@ -205,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; - AZStd::vector 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(); - AZStd::vector mMotionInfos; - AZStd::vector 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 618d5f2bf5..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: { @@ -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(); @@ -221,10 +221,10 @@ namespace EMStudio 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; } @@ -251,10 +251,10 @@ namespace EMStudio 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; } @@ -294,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 @@ -326,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(); } } @@ -347,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(); @@ -377,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()); } @@ -397,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()); } @@ -437,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); @@ -446,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 30fa3a741e..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 @@ -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 06569b3bf3..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)); @@ -201,9 +201,9 @@ namespace EMStudio 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 @@ -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 AZStd::vector& 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,27 +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(); for (EMotionFX::Recorder::NodeHistoryItem* curItem : historyItems) { - 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 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); @@ -402,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; @@ -435,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)); @@ -449,13 +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 int offset = 0; - for (const EMotionFX::Recorder::ExtractedNodeHistoryItem& activeItem : mActiveItems) + for (const EMotionFX::Recorder::ExtractedNodeHistoryItem& activeItem : m_activeItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = activeItem.mNodeHistoryItem; + EMotionFX::Recorder::NodeHistoryItem* curItem = activeItem.m_nodeHistoryItem; if (curItem == nullptr) { continue; @@ -463,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.empty()) + 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", activeItem.mValue); + m_tempString += AZStd::string::format(" = %.4f", activeItem.m_value); } else { - mTempString = AZStd::string::format("%.4f", activeItem.mValue); + m_tempString = AZStd::string::format("%.4f", activeItem.m_value); } - const AZ::Color colorCode = (useNodeColors) ? activeItem.mNodeHistoryItem->mTypeColor : activeItem.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()); } } @@ -512,10 +512,10 @@ namespace EMStudio } // get the history items shortcut - const AZStd::vector& 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); @@ -526,8 +526,8 @@ namespace EMStudio QPointF tickPoints[6]; for (const EMotionFX::Recorder::EventHistoryItem* curItem : historyItems) { - 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) @@ -537,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); @@ -556,7 +556,7 @@ namespace EMStudio } } - if (mPlugin->mEventHistoryItem == curItem) + if (m_plugin->m_eventHistoryItem == curItem) { borderColor = QColor(255, 128, 0); color = borderColor; @@ -607,64 +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 AZStd::vector& 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 int 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 int nodeContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); + const int nodeContentsCode = m_plugin->m_trackHeaderWidget->m_nodeContentsComboBox->currentIndex(); // for all history items QRectF itemRect; for (EMotionFX::Recorder::NodeHistoryItem* curItem : historyItems) { // 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 size_t trackIndex = mTrackRemap[ curItem->mTrackIndex ]; + const size_t trackIndex = m_trackRemap[ curItem->m_trackIndex ]; itemRect.setLeft(startTimePixel); itemRect.setRight(endTimePixel - 1); - itemRect.setTop((mNodeRectsStartHeight + (aznumeric_cast(trackIndex) * (mNodeHistoryItemHeight + 3)) + 3)); - 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; @@ -688,24 +688,24 @@ namespace EMStudio int32 widthInPixels = aznumeric_cast(endTimePixel - startTimePixel); if (widthInPixels > 0) { - const 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) { @@ -720,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); @@ -737,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)); } @@ -758,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.empty()) + 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); @@ -793,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 size_t numTracks = mPlugin->GetNumTracks(); + 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) @@ -812,7 +812,7 @@ 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 size_t numElements = track->GetNumElements(); @@ -844,7 +844,7 @@ namespace EMStudio } } - EMotionFX::Motion* motion = mPlugin->GetMotion(); + EMotionFX::Motion* motion = m_plugin->GetMotion(); if (motion) { // get the motion length @@ -852,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; @@ -861,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); @@ -888,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 @@ -909,16 +909,16 @@ 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 - for (TimeTrack* track : mPlugin->mTracks) + for (TimeTrack* track : m_plugin->m_tracks) { 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 size_t numElements = track->GetNumElements(); @@ -928,7 +928,7 @@ namespace EMStudio } // get the number of copy elements and check if ours is in - for (const CopyElement& copyElement : mCopyElements) + for (const CopyElement& copyElement : m_copyElements) { // get the copy element and make sure we're in the right track if (copyElement.m_trackName != track->GetName()) @@ -958,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)); } @@ -990,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) { @@ -1014,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: @@ -1162,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; } @@ -1171,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 { @@ -1271,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); @@ -1282,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) @@ -1291,7 +1291,7 @@ namespace EMStudio } else { - mPlugin->DisableAllToolTips(); + m_plugin->DisableAllToolTips(); } // do not allow any editing in case the track is not enabled @@ -1302,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 { @@ -1324,7 +1324,7 @@ namespace EMStudio // when the mouse is pressed void TrackDataWidget::mousePressEvent(QMouseEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); QPoint mousePos = event->pos(); @@ -1333,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 { @@ -1370,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 @@ -1407,15 +1407,15 @@ 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 @@ -1443,28 +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 - mResizing = mResizeElement && mResizeID != InvalidIndex32; + 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) { @@ -1473,7 +1473,7 @@ namespace EMStudio if (isZooming) { - setCursor(*(mPlugin->GetZoomInCursor())); + setCursor(*(m_plugin->GetZoomInCursor())); } } @@ -1481,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; @@ -1541,7 +1541,7 @@ namespace EMStudio // zoom in on the rect if (selectRect.isEmpty() == false) { - mPlugin->ZoomRect(selectRect); + m_plugin->ZoomRect(selectRect); } } else @@ -1553,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); @@ -1563,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 @@ -1637,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(); @@ -1654,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)); } @@ -1666,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) { @@ -1693,26 +1691,26 @@ 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); size_t numElements = 0; size_t numSelectedElements = 0; // calculate the number of selected and total events - const size_t numTracks = mPlugin->GetNumTracks(); + 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; @@ -1751,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"); @@ -1840,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); } } @@ -1850,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; @@ -1887,9 +1885,9 @@ 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; @@ -1913,7 +1911,7 @@ namespace EMStudio // remove the motion events CommandSystem::CommandHelperRemoveMotionEvents(timeTrack->GetName(), eventNumbers); - mPlugin->UnselectAllElements(); + m_plugin->UnselectAllElements(); ClearState(); } @@ -1921,9 +1919,9 @@ 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; @@ -1941,19 +1939,19 @@ namespace EMStudio // 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()); @@ -1963,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; @@ -1974,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; @@ -2004,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(), @@ -2018,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; } @@ -2080,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; @@ -2091,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,10 +2144,10 @@ namespace EMStudio } } - 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 (const CopyElement& copyElement : mCopyElements) + for (const CopyElement& copyElement : m_copyElements) { float startTime = copyElement.m_startTime + offset; float endTime = copyElement.m_endTime + offset; @@ -2171,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) { @@ -2189,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(); } @@ -2203,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 size_t numTracks = mPlugin->GetNumTracks(); + 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; @@ -2262,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); @@ -2291,20 +2289,20 @@ namespace EMStudio const EMotionFX::Recorder::ActorInstanceData* actorInstanceData = FindActorInstanceData(); // if we recorded node history - mNodeHistoryRect = QRect(); - if (actorInstanceData && !actorInstanceData->mNodeHistoryItems.empty()) + m_nodeHistoryRect = QRect(); + if (actorInstanceData && !actorInstanceData->m_nodeHistoryItems.empty()) { - const int height = aznumeric_caster((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.empty()) + m_eventHistoryTotalHeight = 0; + if (actorInstanceData && !actorInstanceData->m_eventHistoryItems.empty()) { - mEventHistoryTotalHeight = aznumeric_caster((recorder.CalcMaxEventHistoryTrackIndex(*actorInstanceData) + 1) * 20); + m_eventHistoryTotalHeight = aznumeric_caster((recorder.CalcMaxEventHistoryTrackIndex(*actorInstanceData) + 1) * 20); } } @@ -2322,22 +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 int 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 AZStd::vector& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; QRect rect; for (EMotionFX::Recorder::NodeHistoryItem* curItem : historyItems) { // 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) { @@ -2346,8 +2344,8 @@ namespace EMStudio rect.setLeft(aznumeric_cast(startTimePixel)); rect.setRight(aznumeric_cast(endTimePixel)); - rect.setTop((mNodeRectsStartHeight + (aznumeric_cast(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)) { @@ -2387,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); @@ -2397,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 @@ -2411,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 @@ -2425,15 +2423,15 @@ 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) { AZStd::vector nodePath; @@ -2476,13 +2474,13 @@ namespace EMStudio } // motion name - if (item->mMotionID != InvalidIndex32 && !item->mMotionFileName.empty()) + 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; @@ -2525,14 +2523,14 @@ namespace EMStudio return nullptr; } - const AZStd::vector& historyItems = actorInstanceData->mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_eventHistoryItems; const float tickHalfWidth = 7; const float tickHeight = 16; for (EMotionFX::Recorder::EventHistoryItem* curItem : historyItems) { - float height = aznumeric_caster((curItem->mTrackIndex * 20) + mEventsStartHeight); - double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); + 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))) @@ -2550,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) @@ -2574,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; } @@ -2601,18 +2599,18 @@ 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(""); @@ -2696,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 48effb92d0..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 @@ -73,8 +73,8 @@ namespace EMStudio 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; - - AZStd::vector mActiveItems; - AZStd::vector 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 5b21d8c7b5..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); - if (mPlugin->mTracks.empty()) + 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); - const size_t numTracks = mPlugin->mTracks.size(); + 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, 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 size_t numTracks = mPlugin->GetNumTracks(); + 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 dae551d2bb..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 @@ -48,14 +48,14 @@ namespace EMStudio public: HeaderTrackWidget(QWidget* parent, TimeViewPlugin* parentPlugin, TrackHeaderWidget* trackHeaderWidget, TimeTrack* timeTrack, size_t trackIndex); - QCheckBox* mEnabledCheckbox; - QLabel* mNameLabel; - QLineEdit* mNameEdit; - QPushButton* mRemoveButton; - TimeTrack* mTrack; - size_t 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(); @@ -93,7 +93,7 @@ namespace EMStudio void ReInit(); void UpdateDataContents(); - QWidget* GetAddTrackWidget() { return mAddTrackWidget; } + QWidget* GetAddTrackWidget() { return m_addTrackWidget; } public slots: void OnAddTrackButtonClicked() { CommandSystem::CommandAddEventTrack(); } @@ -104,17 +104,17 @@ namespace EMStudio 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/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/AlignedArray.h b/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h index ef1d157e03..5ffaac2e40 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h +++ b/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h @@ -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. @@ -52,12 +52,12 @@ namespace MCore * @param memCategory The memory category the array is in. */ MCORE_INLINE explicit AlignedArray(T* elems, size_t num, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : mLength(num) - , mMaxLength(AllocSize(num)) - , mMemCategory(memCategory) + : 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 (size_t 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]); } @@ -69,15 +69,15 @@ namespace MCore * @param memCategory The memory category the array is in. */ MCORE_INLINE explicit AlignedArray(size_t initSize, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : mData(nullptr) - , mLength(initSize) - , mMaxLength(initSize) - , mMemCategory(memCategory) + : 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 (size_t 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. @@ -119,13 +119,13 @@ namespace MCore */ ~AlignedArray() { - for (size_t 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(size_t 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(size_t 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(size_t 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 size_t 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,7 +224,7 @@ namespace MCore * This purely has to do with pre-allocating, to reduce the number of reallocs. * @result The maximum array length. */ - MCORE_INLINE size_t GetMaxLength() const { return mMaxLength; } + MCORE_INLINE size_t GetMaxLength() const { return m_maxLength; } /** * Calculates the memory usage used by this array. @@ -233,7 +233,7 @@ namespace MCore */ MCORE_INLINE size_t CalcMemoryUsage(bool includeMembers = true) const { - size_t 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(size_t 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,8 +266,8 @@ namespace MCore */ MCORE_INLINE void Add(const AlignedArray& a) { - size_t l = mLength; - Grow(mLength + a.mLength); + 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,19 +277,19 @@ 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(0); } @@ -300,9 +300,9 @@ namespace MCore */ MCORE_INLINE void RemoveLast() { - if (mLength > 0) + if (m_length > 0) { - Destruct(--mLength); + Destruct(--m_length); } } @@ -310,14 +310,14 @@ 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(size_t 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(size_t 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. @@ -326,11 +326,11 @@ namespace MCore 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--; } /** @@ -344,8 +344,8 @@ namespace MCore { Destruct(i); } - MoveElements(pos, pos + num, mLength - pos - num); - mLength -= num; + MoveElements(pos, pos + num, m_length - pos - num); + m_length -= num; } /** @@ -375,12 +375,12 @@ namespace MCore 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 /** @@ -403,11 +403,11 @@ namespace MCore */ MCORE_INLINE void Clear(bool clearMem = true) { - for (size_t 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(); @@ -420,11 +420,11 @@ namespace MCore */ MCORE_INLINE void AssureSize(size_t newLength) { - if (mLength >= newLength) + if (m_length >= newLength) { return; } - size_t oldLen = mLength; + size_t oldLen = m_length; Grow(newLength); for (size_t i = oldLen; i < newLength; ++i) { @@ -438,7 +438,7 @@ namespace MCore */ 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); } /** @@ -471,9 +471,9 @@ namespace MCore */ MCORE_INLINE size_t Find(const T& x) const { - for (size_t 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; } @@ -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,7 +526,7 @@ 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. @@ -540,7 +540,7 @@ namespace MCore { if (last == InvalidIndex) { - last = mLength - 1; + last = m_length - 1; } InnerSort(first, last, cmp); } @@ -565,17 +565,17 @@ namespace MCore // resize in a fast way that doesn't call constructors or destructors 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; } /** @@ -585,16 +585,16 @@ namespace MCore */ 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 size_t oldLen = mLength; + const size_t oldLen = m_length; GrowExact(newLength); for (size_t i = oldLen; i < newLength; ++i) { @@ -604,12 +604,12 @@ namespace MCore else { // shrinking array, destruct elements at end of array - for (size_t i = newLength; i < mLength; ++i) + for (size_t i = newLength; i < m_length; ++i) { Destruct(i); } - mLength = newLength; + m_length = newLength; } } @@ -624,20 +624,20 @@ namespace MCore { 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 (size_t 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 (size_t 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,35 +661,35 @@ 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[](size_t index) { MCORE_ASSERT(index < mLength); return mData[index]; } - MCORE_INLINE const T& operator[](size_t 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. */ - size_t mLength; /**< The number of used elements in the array. */ - size_t 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(size_t newLength) { - mLength = newLength; - if (mMaxLength >= newLength) + m_length = newLength; + if (m_maxLength >= newLength) { return; } @@ -697,14 +697,14 @@ namespace MCore } MCORE_INLINE void GrowExact(size_t newLength) { - mLength = newLength; - if (mMaxLength < newLength) + m_length = newLength; + if (m_maxLength < newLength) { Realloc(newLength); } } MCORE_INLINE size_t AllocSize(size_t num) { return 1 + num /*+num/8*/; } - MCORE_INLINE void Alloc(size_t num) { mData = (T*)AlignedAllocate(num * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } + 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) @@ -712,43 +712,43 @@ namespace MCore 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(size_t index, const T& original) { ::new(mData + index)T(original); } // copy-construct an element at which is a copy of - MCORE_INLINE void Construct(size_t index) { ::new(mData + index)T; } // construct an element at place + 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/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 416d493453..ac6772e44e 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp @@ -13,7 +13,7 @@ namespace MCore { 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 3b9b4459aa..e1ea970044 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Attribute.h +++ b/Gems/EMotionFX/Code/MCore/Source/Attribute.h @@ -55,7 +55,7 @@ namespace MCore virtual Attribute* Clone() const = 0; virtual const char* GetTypeString() const = 0; - MCORE_INLINE AZ::u32 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; @@ -67,7 +67,7 @@ namespace MCore virtual void NetworkSerialize(EMotionFX::Network::AnimGraphSnapshotChunkSerializer&) {}; protected: - AZ::u32 mTypeID; /**< The unique type ID of the attribute class. */ + AZ::u32 m_typeId; /**< The unique type ID of the attribute class. */ Attribute(AZ::u32 typeID); }; 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 3be04c3ce1..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 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; } + 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 4ad488af47..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 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; } + 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 53b91dbb98..860d067671 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp @@ -41,13 +41,13 @@ namespace MCore { if (delFromMem) { - for (Attribute* attribute : mRegistered) + for (Attribute* attribute : m_registered) { delete attribute; } } - mRegistered.clear(); + m_registered.clear(); } @@ -57,11 +57,11 @@ namespace MCore 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); } @@ -77,21 +77,21 @@ namespace MCore if (delFromMem) { - delete mRegistered[attribIndex]; + delete m_registered[attribIndex]; } - mRegistered.erase(mRegistered.begin() + attribIndex); + m_registered.erase(m_registered.begin() + attribIndex); } size_t AttributeFactory::FindAttributeIndexByType(size_t typeID) const { - const auto foundAttribute = AZStd::find_if(begin(mRegistered), end(mRegistered), [typeID](const Attribute* registeredAttribute) + const auto foundAttribute = AZStd::find_if(begin(m_registered), end(m_registered), [typeID](const Attribute* registeredAttribute) { return registeredAttribute->GetType() == typeID; }); - return foundAttribute != end(mRegistered) ? AZStd::distance(begin(mRegistered), foundAttribute) : InvalidIndex; + return foundAttribute != end(m_registered) ? AZStd::distance(begin(m_registered), foundAttribute) : InvalidIndex; } @@ -103,13 +103,13 @@ namespace MCore 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 02bd5b0e1b..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(size_t index) const { return mRegistered[index]; } + size_t GetNumRegisteredAttributes() const { return m_registered.size(); } + Attribute* GetRegisteredAttribute(size_t index) const { return m_registered[index]; } 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 fee4494ba5..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 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; } + 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 b1fd1da686..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 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; } + 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 98eb5f602b..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,7 +48,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 { MCORE_UNUSED(valueString); MCORE_ASSERT(false); return false; } // currently unsupported @@ -57,14 +57,14 @@ namespace MCore 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 39d9243197..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 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; } + 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 a05c057023..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 size_t GetRawDataSize() const { return 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; } + 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 826899186a..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 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; } + 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 066962fb8f..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 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; } + 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 7b20e92a6b..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 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); } + 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 959cebe16d..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; } } @@ -49,10 +49,10 @@ namespace MCore 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; } @@ -82,20 +82,20 @@ namespace MCore 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 8845e7c278..d53477b1e1 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Command.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Command.cpp @@ -17,8 +17,8 @@ namespace MCore // constructor Command::Callback::Callback(bool executePreUndo, bool executePreCommand) { - mPreUndoExecute = executePreUndo; - mPreCommandExecute = executePreCommand; + m_preUndoExecute = executePreUndo; + m_preCommandExecute = executePreCommand; } @@ -30,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)) { } @@ -59,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; } @@ -84,25 +84,25 @@ namespace MCore size_t Command::GetNumCallbacks() const { - return 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; @@ -112,21 +112,21 @@ 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 size_t Command::CalcNumPreCommandCallbacks() const { - return AZStd::accumulate(begin(mCallbacks), end(mCallbacks), size_t{0}, [](size_t total, const Callback* callback) + return AZStd::accumulate(begin(m_callbacks), end(m_callbacks), size_t{0}, [](size_t total, const Callback* callback) { return callback->GetExecutePreCommand() ? total + 1 : total; }); @@ -136,6 +136,6 @@ namespace MCore // calculate the number of registered post-execute callbacks size_t Command::CalcNumPostCommandCallbacks() const { - return mCallbacks.size() - CalcNumPreCommandCallbacks(); + 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 d6bfb3a0d7..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,7 +273,7 @@ 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. @@ -298,7 +298,7 @@ namespace MCore * @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(size_t 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 ae536101e6..a55d066cdc 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp @@ -34,14 +34,14 @@ namespace MCore } // 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; } @@ -57,14 +57,14 @@ namespace MCore } // 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(); } @@ -79,13 +79,13 @@ namespace MCore } // 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()); } @@ -100,13 +100,13 @@ namespace MCore } // 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()); } @@ -121,13 +121,13 @@ namespace MCore } // 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()); } @@ -142,14 +142,14 @@ namespace MCore } // 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()); } @@ -164,13 +164,13 @@ namespace MCore } // 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()); } @@ -186,7 +186,7 @@ namespace MCore } // return the parameter value - *outResult = m_parameters[paramIndex].mValue; + *outResult = m_parameters[paramIndex].m_value; } @@ -201,7 +201,7 @@ namespace MCore 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(); @@ -218,7 +218,7 @@ namespace MCore } // return the parameter value - return m_parameters[paramIndex].mValue; + return m_parameters[paramIndex].m_value; } @@ -241,7 +241,7 @@ namespace MCore } // 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 @@ -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()); } @@ -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()); } @@ -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()); } @@ -332,7 +332,7 @@ 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()); } @@ -346,14 +346,14 @@ namespace MCore // get the parameter name for a given parameter 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(size_t nr) const { - return m_parameters[nr].mValue; + return m_parameters[nr].m_value; } @@ -368,7 +368,7 @@ namespace MCore } // 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); } @@ -378,7 +378,7 @@ namespace MCore // compare all parameter names on a non-case sensitive way const auto foundParameter = AZStd::find_if(begin(m_parameters), end(m_parameters), [paramName](const Parameter& parameter) { - return AzFramework::StringFunc::Equal(parameter.mName, paramName, false /* no case */); + return AzFramework::StringFunc::Equal(parameter.m_name, paramName, false /* no case */); }); return foundParameter != end(m_parameters) ? AZStd::distance(begin(m_parameters), foundParameter) : InvalidIndex; @@ -542,7 +542,7 @@ namespace MCore LogInfo("Command line '%s' has %d parameters", debugName, numParameters); 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 8a4e5172e8..07b22ce9e5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandLine.h +++ b/Gems/EMotionFX/Code/MCore/Source/CommandLine.h @@ -271,8 +271,8 @@ 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. */ diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp index fb10da4eb4..0bc228898c 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp @@ -68,21 +68,21 @@ namespace MCore // check if this param is a required one or not 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(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(size_t index) const { - return m_parameters[index].mDescription.c_str(); + return m_parameters[index].m_description.c_str(); } @@ -95,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"; @@ -129,7 +129,7 @@ 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; } @@ -145,7 +145,7 @@ namespace MCore { const auto foundParameter = AZStd::find_if(begin(m_parameters), end(m_parameters), [parameter](const Parameter& p) { - return AzFramework::StringFunc::Equal(p.mName, parameter, false /* no case */); + return AzFramework::StringFunc::Equal(p.m_name, parameter, false /* no case */); }); return foundParameter != end(m_parameters) ? AZStd::distance(begin(m_parameters), foundParameter) : InvalidIndex; } @@ -154,7 +154,7 @@ namespace MCore // get the default value for a given parameter const AZStd::string& CommandSyntax::GetDefaultValue(size_t index) const { - return m_parameters[index].mDefaultValue; + return m_parameters[index].m_defaultValue; } @@ -163,7 +163,7 @@ namespace MCore 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; @@ -180,7 +180,7 @@ namespace MCore return false; } - outDefaultValue = m_parameters[index].mDefaultValue; + outDefaultValue = m_parameters[index].m_defaultValue; return true; } @@ -203,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 size_t paramIndex = commandLine.FindParameterIndex(parameter.mName.c_str()); + 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())) { @@ -233,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())) { @@ -242,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())) { @@ -251,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) { @@ -260,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())) { @@ -269,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())) { @@ -302,8 +302,8 @@ namespace MCore // find the longest command name size_t offset = AZStd::minmax_element(begin(m_parameters), end(m_parameters), [](const Parameter& left, const Parameter& right) { - return left.mName.size() < right.mName.size(); - }).second->mName.size(); + return left.m_name.size() < right.m_name.size(); + }).second->m_name.size(); size_t offset2 = offset; size_t offset3 = offset; @@ -330,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 730dd9047a..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: 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/DiskFile.cpp b/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp index 27e94489e6..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,7 +38,7 @@ 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(); } @@ -65,27 +65,27 @@ namespace MCore }(); // 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; } } @@ -93,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; } @@ -139,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; } @@ -154,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; } @@ -169,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/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/IDGenerator.cpp b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp index 7e4ff9b16e..dc25288c19 100644 --- a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp @@ -15,7 +15,7 @@ namespace MCore { // constructor IDGenerator::IDGenerator() - : mNextID{0} + : m_nextId{0} { } @@ -29,7 +29,7 @@ namespace MCore // get a unique id size_t IDGenerator::GenerateID() { - const size_t result = mNextID++; + const size_t result = m_nextId++; MCORE_ASSERT(result != InvalidIndex); // reached the limit return result; } diff --git a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h index 1418b7d3d1..5c392e45b1 100644 --- a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h +++ b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h @@ -31,7 +31,7 @@ namespace MCore size_t GenerateID(); private: - AZStd::atomic 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 ecf4eb9168..0621926fb2 100644 --- a/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp @@ -13,21 +13,21 @@ 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(); } @@ -75,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.emplace_back(callback); + m_logCallbacks.emplace_back(callback); // collect the enabled log levels InitLogLevels(); @@ -88,14 +88,14 @@ namespace MCore // remove a specific log callback from the stack void LogManager::RemoveLogCallback(size_t index) { - MCORE_ASSERT(index < mLogCallbacks.size()); - 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.erase(AZStd::next(begin(mLogCallbacks), index)); + m_logCallbacks.erase(AZStd::next(begin(m_logCallbacks), index)); // collect the enabled log levels InitLogLevels(); @@ -104,10 +104,10 @@ namespace MCore // remove all given log callbacks by type void LogManager::RemoveAllByType(uint32 type) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); // Put all the callbacks of the type to be removed at the end of the vector - mLogCallbacks.erase(AZStd::remove_if(begin(mLogCallbacks), end(mLogCallbacks), [type](const LogCallback* callback) + m_logCallbacks.erase(AZStd::remove_if(begin(m_logCallbacks), end(m_logCallbacks), [type](const LogCallback* callback) { if (callback->GetType() == type) { @@ -125,15 +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 - for (auto* logCallback : mLogCallbacks) + for (auto* logCallback : m_logCallbacks) { delete logCallback; } - mLogCallbacks.clear(); + m_logCallbacks.clear(); // collect the enabled log levels InitLogLevels(); @@ -143,13 +143,13 @@ namespace MCore // retrieve a pointer to the given log callback LogCallback* LogManager::GetLogCallback(size_t index) { - return mLogCallbacks[index]; + return m_logCallbacks[index]; } // return number of log callbacks in the stack size_t LogManager::GetNumLogCallbacks() const { - return mLogCallbacks.size(); + return m_logCallbacks.size(); } // collect all enabled log levels @@ -159,12 +159,12 @@ namespace MCore int32 logLevels = LogCallback::LOGLEVEL_NONE; // enable all log levels that are enabled by any of the callbacks - for (auto* logCallback : mLogCallbacks) + for (auto* logCallback : m_logCallbacks) { logLevels |= (int32)logCallback->GetLogLevels(); } - mLogLevels = (LogCallback::ELogLevel)logLevels; + m_logLevels = (LogCallback::ELogLevel)logLevels; } @@ -172,23 +172,23 @@ namespace MCore void LogManager::SetLogLevels(LogCallback::ELogLevel logLevels) { // iterate through all log callbacks and set it to the given log levels - for (auto* logCallback : mLogCallbacks) + for (auto* logCallback : m_logCallbacks) { 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 - for (auto* logCallback : mLogCallbacks) + for (auto* logCallback : m_logCallbacks) { if (logCallback->GetLogLevels() & logLevel) { @@ -202,9 +202,9 @@ namespace MCore size_t LogManager::FindLogCallback(LogCallback* callback) const { // iterate through all callbacks - for (size_t i = 0; i < mLogCallbacks.size(); ++i) + for (size_t i = 0; i < m_logCallbacks.size(); ++i) { - if (mLogCallbacks[i] == callback) + if (m_logCallbacks[i] == callback) { return i; } @@ -216,7 +216,7 @@ namespace MCore 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) @@ -236,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) @@ -256,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) @@ -276,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) @@ -296,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) @@ -316,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) @@ -335,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 d5e2316436..864aa50219 100644 --- a/Gems/EMotionFX/Code/MCore/Source/LogManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/LogManager.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. */ }; //---------------------------------------------------------------------------- @@ -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: - AZStd::vector 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 657c5e0303..5cdd9c2600 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp @@ -17,15 +17,14 @@ namespace MCore { 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, size_t historyItemNr) @@ -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); } @@ -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; @@ -700,7 +699,7 @@ namespace MCore 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); } @@ -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,22 +778,22 @@ 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); } @@ -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=%zu", i, mCommandHistory[i].mExecutedCommand->GetName(), mCommandHistory[i].mParameters.GetNumParameters()); - if (i == 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(size_t maxItems) { maxItems = AZStd::max(size_t{1}, maxItems); - mMaxHistoryEntries = 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; } 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(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 566c3d17fd..d59639dee5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.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. @@ -55,9 +55,9 @@ namespace MCore 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). */ + 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. */ }; @@ -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,13 +296,13 @@ 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. */ - ptrdiff_t mHistoryIndex; /**< The command history iterator. The current position in the undo/redo history. */ + 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 09021a105a..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); + 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 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 mUsedLength; + 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/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 a4fe6eaa10..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,14 @@ 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; }; @@ -109,14 +109,14 @@ namespace MCore public: MCORE_INLINE AtomicSizeT() { SetValue(0); } - MCORE_INLINE void SetValue(size_t value) { mAtomic.store(value); } - MCORE_INLINE size_t GetValue() const { size_t value = mAtomic.load(); return value; } + 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 mAtomic++; } - MCORE_INLINE size_t Decrement() { return mAtomic--; } + MCORE_INLINE size_t Increment() { return m_atomic++; } + MCORE_INLINE size_t Decrement() { return m_atomic--; } private: - AZStd::atomic mAtomic; + AZStd::atomic m_atomic; }; @@ -127,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/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/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/StringIdPool.cpp b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp index dc08f628fe..643258373b 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp @@ -29,13 +29,13 @@ namespace MCore { Lock(); - for (AZStd::basic_string*& string : mStrings) + for (AZStd::basic_string*& string : m_strings) { delete string; } - mStrings.clear(); + m_strings.clear(); - mStringToIndex.clear(); + m_stringToIndex.clear(); Unlock(); } @@ -43,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, aznumeric_caster(mStrings.size())); + auto iterator = m_stringToIndex.emplace(objectName, aznumeric_caster(m_strings.size())); if (!iterator.second) { // could not insert, we have the element @@ -52,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; @@ -72,7 +72,7 @@ namespace MCore { Lock(); MCORE_ASSERT(id != InvalidIndex32); - const AZStd::string* stringAddress = mStrings[id]; + const AZStd::string* stringAddress = m_strings[id]; Unlock(); return *stringAddress; } @@ -81,7 +81,7 @@ namespace MCore void StringIdPool::Reserve(size_t numStrings) { Lock(); - mStrings.reserve(numStrings); + m_strings.reserve(numStrings); Unlock(); } @@ -89,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())); } } } diff --git a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h index 9f58adf028..75bbc1b010 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h +++ b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h @@ -66,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(); diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp index 6a6d540519..27f83b07a3 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp @@ -60,15 +60,15 @@ namespace MysticQt 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); } @@ -82,7 +82,7 @@ namespace MysticQt void DialogStack::Clear() { // destroy the dialogs - mDialogs.clear(); + m_dialogs.clear(); // update the scroll bars UpdateScrollBars(); @@ -103,10 +103,10 @@ namespace MysticQt // add the dialog widget // the splitter is hierarchical : {a, {b, c}} DialogStackSplitter* dialogSplitter; - if (mDialogs.empty()) + if (m_dialogs.empty()) { // add the dialog widget - dialogSplitter = mRootSplitter; + dialogSplitter = m_rootSplitter; dialogSplitter->addWidget(dialogWidget); // stretch if needed @@ -118,10 +118,10 @@ namespace MysticQt else { // check if one space is free on the last splitter - if (mDialogs.back().mSplitter->count() == 1) + if (m_dialogs.back().m_splitter->count() == 1) { // add the dialog widget - dialogSplitter = mDialogs.back().mSplitter; + dialogSplitter = m_dialogs.back().m_splitter; dialogSplitter->addWidget(dialogWidget); // stretch if needed @@ -131,16 +131,16 @@ namespace MysticQt } // less space used by the splitter when the last dialog is closed - if (mDialogs.back().mFrame->isHidden()) + if (m_dialogs.back().m_frame->isHidden()) { - mDialogs.back().mSplitter->handle(1)->setFixedHeight(1); - mDialogs.back().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.back().mFrame->isHidden()) + if (m_dialogs.back().m_frame->isHidden()) { - mDialogs.back().mSplitter->handle(1)->setDisabled(true); + m_dialogs.back().m_splitter->handle(1)->setDisabled(true); } } else // already two dialogs in the splitter @@ -151,24 +151,24 @@ namespace MysticQt dialogSplitter->setChildrenCollapsible(false); // add the current last dialog and the new dialog after - dialogSplitter->addWidget(mDialogs.back().mDialogWidget); + dialogSplitter->addWidget(m_dialogs.back().m_dialogWidget); dialogSplitter->addWidget(dialogWidget); // stretch if needed - if (mDialogs.back().mMaximizeSize && mDialogs.back().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.back().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.back().mFrame->isHidden()) + if (m_dialogs.back().m_frame->isHidden()) { dialogSplitter->handle(1)->setDisabled(true); } @@ -180,27 +180,27 @@ namespace MysticQt } // replace the last dialog by the new splitter - mDialogs.back().mSplitter->addWidget(dialogSplitter); + m_dialogs.back().m_splitter->addWidget(dialogSplitter); // disable the splitter - if (mDialogs.size() > 1) + if (m_dialogs.size() > 1) { - const auto previousDialogIt = mDialogs.end() - 2; - if (previousDialogIt->mFrame->isHidden()) + const auto previousDialogIt = m_dialogs.end() - 2; + if (previousDialogIt->m_frame->isHidden()) { - mDialogs.back().mSplitter->handle(1)->setDisabled(true); + m_dialogs.back().m_splitter->handle(1)->setDisabled(true); } // stretch the splitter if needed // the correct behavior is found after experimentations - if ((mDialogs.back().mMaximizeSize && mDialogs.back().mStretchWhenMaximize) || (previousDialogIt->mMaximizeSize && previousDialogIt->mStretchWhenMaximize == false)) + if ((m_dialogs.back().m_maximizeSize && m_dialogs.back().m_stretchWhenMaximize) || (previousDialogIt->m_maximizeSize && previousDialogIt->m_stretchWhenMaximize == false)) { - mDialogs.back().mSplitter->setStretchFactor(1, 1); + m_dialogs.back().m_splitter->setStretchFactor(1, 1); } } // set the new splitter of the last dialog - mDialogs.back().mSplitter = dialogSplitter; + m_dialogs.back().m_splitter = dialogSplitter; } } @@ -263,19 +263,19 @@ namespace MysticQt dialogWidget->adjustSize(); // register it, so that we know which frame is linked to which header button - mDialogs.emplace_back(Dialog{ - /*.mButton =*/ headerButton, - /*.mFrame =*/ frame, - /*.mWidget =*/ widget, - /*.mDialogWidget =*/ dialogWidget, - /*.mSplitter =*/ dialogSplitter, - /*.mClosable =*/ closable, - /*.mMaximizeSize =*/ maximizeSize, - /*.mStretchWhenMaximize =*/ stretchWhenMaximize, - /*.mMinimumHeightBeforeClose =*/ 0, - /*.mMaximumHeightBeforeClose =*/ 0, - /*.mLayout =*/ layout, - /*.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 @@ -305,12 +305,12 @@ namespace MysticQt bool DialogStack::Remove(QWidget* widget) { - const auto foundDialog = AZStd::find_if(begin(mDialogs), end(mDialogs), [widget](const Dialog& dialog) + const auto foundDialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [widget](const Dialog& dialog) { - return dialog.mFrame->layout()->indexOf(widget) != -1; + return dialog.m_frame->layout()->indexOf(widget) != -1; }); - if (foundDialog == end(mDialogs)) + if (foundDialog == end(m_dialogs)) { return false; } @@ -318,9 +318,9 @@ namespace MysticQt // 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->mDialogWidget->hide(); - foundDialog->mDialogWidget->deleteLater(); - mDialogs.erase(foundDialog); + foundDialog->m_dialogWidget->hide(); + foundDialog->m_dialogWidget->deleteLater(); + m_dialogs.erase(foundDialog); // update the scroll bars UpdateScrollBars(); @@ -334,7 +334,7 @@ namespace MysticQt { QPushButton* button = (QPushButton*)sender(); const size_t dialogIndex = FindDialog(button); - if (mDialogs[dialogIndex].mFrame->isHidden()) + if (m_dialogs[dialogIndex].m_frame->isHidden()) { Open(button); } @@ -348,83 +348,83 @@ namespace MysticQt // find the dialog that goes with the given button size_t DialogStack::FindDialog(QPushButton* pushButton) { - const auto foundDialog = AZStd::find_if(begin(mDialogs), end(mDialogs), [pushButton](const Dialog& dialog) + const auto foundDialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [pushButton](const Dialog& dialog) { - return dialog.mButton == pushButton; + return dialog.m_button == pushButton; }); - return foundDialog != end(mDialogs) ? AZStd::distance(begin(mDialogs), foundDialog) : MCore::InvalidIndex; + return foundDialog != end(m_dialogs) ? AZStd::distance(begin(m_dialogs), foundDialog) : MCore::InvalidIndex; } // open the dialog void DialogStack::Open(QPushButton* button) { - const auto dialog = AZStd::find_if(begin(mDialogs), end(mDialogs), [button](const Dialog& dialog) + const auto dialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [button](const Dialog& dialog) { - return dialog.mButton == button; + return dialog.m_button == button; }); - if (dialog == end(mDialogs)) + if (dialog == end(m_dialogs)) { return; } // show the widget inside the dialog - dialog->mFrame->show(); + dialog->m_frame->show(); // set the previous minimum and maximum height before closed - dialog->mDialogWidget->setMinimumHeight(dialog->mMinimumHeightBeforeClose); - dialog->mDialogWidget->setMaximumHeight(dialog->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 (dialog != mDialogs.end() - 1) + if (dialog != m_dialogs.end() - 1) { - dialog->mSplitter->handle(1)->setFixedHeight(4); - dialog->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 (dialog != mDialogs.end() - 1) + if (dialog != m_dialogs.end() - 1) { - dialog->mSplitter->handle(1)->setEnabled(true); + dialog->m_splitter->handle(1)->setEnabled(true); } // maximize the size if it's needed - if (mDialogs.size() > 1) + if (m_dialogs.size() > 1) { - if (dialog->mMaximizeSize) + if (dialog->m_maximizeSize) { // special case if it's the first dialog - if (dialog == mDialogs.begin()) + 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 (dialog->mStretchWhenMaximize == false && (dialog + 1)->mMaximizeSize && (dialog + 1)->mFrame->isHidden() == false) + if (dialog->m_stretchWhenMaximize == false && (dialog + 1)->m_maximizeSize && (dialog + 1)->m_frame->isHidden() == false) { - static_cast(dialog->mSplitter)->MoveFirstSplitterToMin(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMin(); } else { - static_cast(dialog->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 ((dialog - 1)->mFrame->isHidden() || (dialog - 1)->mMaximizeSize == false || ((dialog - 1)->mMaximizeSize && (dialog - 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((dialog - 1)->mSplitter)->MoveFirstSplitterToMin(); + static_cast((dialog - 1)->m_splitter)->MoveFirstSplitterToMin(); } // special case if it's not the last dialog - if (dialog != mDialogs.end() - 1) + if (dialog != m_dialogs.end() - 1) { // if the next dialog is closed, it's needed to expand to the max too - if ((dialog + 1)->mFrame->isHidden()) + if ((dialog + 1)->m_frame->isHidden()) { - static_cast(dialog->mSplitter)->MoveFirstSplitterToMax(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMax(); } } } @@ -439,58 +439,58 @@ namespace MysticQt // close the dialog void DialogStack::Close(QPushButton* button) { - const auto dialog = AZStd::find_if(begin(mDialogs), end(mDialogs), [button](const Dialog& dialog) + const auto dialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [button](const Dialog& dialog) { - return dialog.mButton == button; + return dialog.m_button == button; }); - if (dialog == end(mDialogs)) + if (dialog == end(m_dialogs)) { return; } // only closable dialog can be closed - if (dialog->mClosable == false) + if (dialog->m_closable == false) { return; } // keep the min and max height before close - dialog->mMinimumHeightBeforeClose = dialog->mDialogWidget->minimumHeight(); - dialog->mMaximumHeightBeforeClose = dialog->mDialogWidget->maximumHeight(); + dialog->m_minimumHeightBeforeClose = dialog->m_dialogWidget->minimumHeight(); + dialog->m_maximumHeightBeforeClose = dialog->m_dialogWidget->maximumHeight(); // hide the widget inside the dialog - dialog->mFrame->hide(); + dialog->m_frame->hide(); // set the widget to fixed size to not have it possible to resize - dialog->mDialogWidget->setMinimumHeight(dialog->mButton->height()); - dialog->mDialogWidget->setMaximumHeight(dialog->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 (dialog < mDialogs.end() - 1) + if (dialog < m_dialogs.end() - 1) { - dialog->mSplitter->handle(1)->setFixedHeight(1); - dialog->mSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); - dialog->mSplitter->handle(1)->setDisabled(true); - static_cast(dialog->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; - for (auto curDialog = dialog + 1; curDialog != mDialogs.end(); ++curDialog) + for (auto curDialog = dialog + 1; curDialog != m_dialogs.end(); ++curDialog) { - if (curDialog->mMaximizeSize && curDialog->mFrame->isHidden() == false) + if (curDialog->m_maximizeSize && curDialog->m_frame->isHidden() == false) { - if (curDialog != (mDialogs.end() - 1) && (curDialog + 1)->mFrame->isHidden()) + if (curDialog != (m_dialogs.end() - 1) && (curDialog + 1)->m_frame->isHidden()) { - static_cast(curDialog->mSplitter)->MoveFirstSplitterToMax(); + static_cast(curDialog->m_splitter)->MoveFirstSplitterToMax(); } else { - static_cast((curDialog - 1)->mSplitter)->MoveFirstSplitterToMin(); + static_cast((curDialog - 1)->m_splitter)->MoveFirstSplitterToMin(); } findPreviousMaximizedDialogNeeded = false; break; @@ -498,11 +498,11 @@ namespace MysticQt } if (findPreviousMaximizedDialogNeeded) { - for (auto curDialog = AZStd::make_reverse_iterator(dialog) + 1; curDialog != mDialogs.rend(); ++curDialog) + for (auto curDialog = AZStd::make_reverse_iterator(dialog) + 1; curDialog != m_dialogs.rend(); ++curDialog) { - if (curDialog->mMaximizeSize && curDialog->mFrame->isHidden() == false) + if (curDialog->m_maximizeSize && curDialog->m_frame->isHidden() == false) { - static_cast(curDialog->mSplitter)->MoveFirstSplitterToMax(); + static_cast(curDialog->m_splitter)->MoveFirstSplitterToMax(); break; } } @@ -519,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)) @@ -566,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; @@ -576,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(); } @@ -606,15 +606,15 @@ namespace MysticQt QScrollArea::resizeEvent(event); // maximize the first dialog needed - if (mDialogs.empty() || mDialogs.size() == 1) + if (m_dialogs.empty() || m_dialogs.size() == 1) { return; } - for (auto dialog = mDialogs.rbegin() + 1; dialog != mDialogs.rend(); ++dialog) + for (auto dialog = m_dialogs.rbegin() + 1; dialog != m_dialogs.rend(); ++dialog) { - if (dialog->mMaximizeSize && dialog->mFrame->isHidden() == false) + if (dialog->m_maximizeSize && dialog->m_frame->isHidden() == false) { - static_cast(dialog->mSplitter)->MoveFirstSplitterToMax(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMax(); break; } } @@ -624,54 +624,54 @@ namespace MysticQt // replace an internal widget void DialogStack::ReplaceWidget(QWidget* oldWidget, QWidget* newWidget) { - for (auto dialog = mDialogs.begin(); dialog != mDialogs.end(); ++dialog) + for (auto dialog = m_dialogs.begin(); dialog != m_dialogs.end(); ++dialog) { // go next if the widget is not the same - if (dialog->mWidget != oldWidget) + if (dialog->m_widget != oldWidget) { continue; } // replace the widget - dialog->mFrame->layout()->replaceWidget(oldWidget, newWidget); - dialog->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 (dialog->mMaximizeSize == false) + if (dialog->m_maximizeSize == false) { // get margins - const QMargins frameMargins = dialog->mLayout->contentsMargins(); - const QMargins dialogMargins = dialog->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 - dialog->mFrame->setFixedHeight(newWidget->height() + frameMarginTopBottom); + dialog->m_frame->setFixedHeight(newWidget->height() + frameMarginTopBottom); // compute the dialog height - const int dialogHeight = newWidget->height() + allMarginsTopBottom + dialog->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 (dialog->mFrame->isHidden() == false) + if (dialog->m_frame->isHidden() == false) { // set the dialog height - dialog->mDialogWidget->setFixedHeight(dialogHeight); + dialog->m_dialogWidget->setFixedHeight(dialogHeight); // set the first splitter to the min if needed - if (dialog != mDialogs.end() - 1) + if (dialog != m_dialogs.end() - 1) { - static_cast(dialog->mSplitter)->MoveFirstSplitterToMin(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMin(); } } else // dialog closed { // update the minimum and maximum stored height - dialog->mMinimumHeightBeforeClose = dialogHeight; - dialog->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 6bf810b281..bf93b5d23f 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h @@ -62,18 +62,18 @@ namespace MysticQt private: struct Dialog { - QPushButton* mButton = nullptr; - QWidget* mFrame = nullptr; - QWidget* mWidget = nullptr; - QWidget* mDialogWidget = nullptr; - DialogStackSplitter* mSplitter = nullptr; - bool mClosable = true; - bool mMaximizeSize = false; - bool mStretchWhenMaximize = false; - int mMinimumHeightBeforeClose = 0; - int mMaximumHeightBeforeClose = 0; - QLayout* mLayout = nullptr; - QLayout* mDialogLayout = nullptr; + 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: @@ -83,10 +83,10 @@ namespace MysticQt void UpdateScrollBars(); private: - DialogStackSplitter* mRootSplitter; - AZStd::vector 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/MysticQtManager.cpp b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp index 3386e1a0d2..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,11 +30,11 @@ namespace MysticQt MysticQtManager::~MysticQtManager() { // get the number of icons and destroy them - for (IconData* icon : mIcons) + for (IconData* icon : m_icons) { delete icon; } - mIcons.clear(); + m_icons.clear(); } @@ -42,33 +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 - for (IconData* icon : mIcons) + for (IconData* icon : m_icons) { - if (AzFramework::StringFunc::Equal(icon->mFileName.c_str(), filename, false /* no case */)) + if (AzFramework::StringFunc::Equal(icon->m_fileName.c_str(), filename, false /* no case */)) { - return *(icon->mIcon); + return *(icon->m_icon); } } // we haven't found it IconData* iconData = new IconData(filename); - mIcons.emplace_back(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 e0be07796e..9c8a73b92f 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h @@ -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; - AZStd::vector 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/ColliderContainerWidget.cpp b/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp index ef76629780..fea4f23c6a 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp @@ -617,12 +617,12 @@ namespace EMotionFX const MCore::RGBAColor& colliderColor) { const size_t nodeIndex = node->GetNodeIndex(); - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + 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,7 +677,7 @@ namespace EMotionFX return; } - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + MCommon::RenderUtil* renderUtil = renderInfo->m_renderUtil; const bool oldLightingEnabled = renderUtil->GetLightingEnabled(); renderUtil->EnableLighting(false); 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 93c4e2cb67..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,7 +432,7 @@ namespace EMotionFX return; } - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + MCommon::RenderUtil* renderUtil = renderInfo->m_renderUtil; const bool oldLightingEnabled = renderUtil->GetLightingEnabled(); renderUtil->EnableLighting(false); @@ -539,8 +539,8 @@ namespace EMotionFX 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 bd57e24d08..a2b23e3268 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp @@ -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(); @@ -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 @@ -553,7 +553,7 @@ namespace EMotionFX 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 8cbee5924b..9883b06e23 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/ActorGoalNodeHandler.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/ActorGoalNodeHandler.cpp @@ -131,7 +131,7 @@ 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; 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."); 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/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 9f996f46fd..303a7e118b 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -526,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); ) } } @@ -663,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; } } @@ -780,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; } @@ -792,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; } @@ -804,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; } 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/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 78aa3b4426..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)) { @@ -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/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/AnimGraphMotionNodeTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp index 2a199f5e8b..121f438d82 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp @@ -118,16 +118,16 @@ namespace EMotionFX } protected: - size_t m_l_handIndex = InvalidIndex; - size_t m_l_loArmIndex = InvalidIndex; - size_t m_l_loLegIndex = InvalidIndex; - size_t m_l_ankleIndex = InvalidIndex; - size_t m_r_handIndex = InvalidIndex; - size_t m_r_loArmIndex = InvalidIndex; - size_t m_r_loLegIndex = InvalidIndex; - size_t m_r_ankleIndex = InvalidIndex; - size_t m_jack_rootIndex = InvalidIndex; - size_t m_bip01__pelvisIndex = InvalidIndex; + 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,12 +343,12 @@ 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 (size_t i = 0; i < 4; i++) @@ -357,12 +357,12 @@ namespace EMotionFX 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,10 +379,10 @@ 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 (size_t i = 0; i < 4; i++) @@ -391,11 +391,11 @@ namespace EMotionFX 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); @@ -429,11 +429,11 @@ namespace EMotionFX 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 (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; } @@ -478,11 +478,11 @@ namespace EMotionFX // In sequential index mode, motions should increase its index each time and wrap around. Basically iterating over the list of motions. 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 eb1da8f0a3..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. @@ -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/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 d23638c9ea..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, @@ -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, 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/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 609d291800..2f62365dd8 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp @@ -142,8 +142,8 @@ namespace EMotionFX 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); } @@ -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 e63fd2c2c7..b86041c7aa 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp @@ -72,7 +72,7 @@ namespace EMotionFX 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); } } @@ -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 9851409a94..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 @@ -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/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 df2f644eb4..a4ec05746a 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp @@ -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 820e6d9fa4..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()); @@ -148,10 +148,10 @@ namespace EMotionFX // Remeber specific joint's original position to compare with its new position later const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); size_t testJointIndex; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); - const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; + 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); @@ -188,26 +188,26 @@ namespace EMotionFX const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); size_t testJointIndex; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); - const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; + 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(); 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,10 +224,10 @@ 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()); @@ -237,12 +237,12 @@ namespace EMotionFX size_t testJointIndex; size_t linkedJoint0Index; size_t 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; + 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); @@ -288,10 +288,10 @@ namespace EMotionFX const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); size_t testJointIndex; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); - const AZ::Quaternion testJointRotation = jackPose->GetModelSpaceTransform(testJointIndex).mRotation; + 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,20 +315,20 @@ 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); @@ -336,28 +336,28 @@ namespace EMotionFX Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); size_t testBendJointIndex; size_t testJointIndex; - AZStd::string& bendLoArm = m_param.linkedJointNames[0]; + 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,14 +382,14 @@ 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); @@ -397,48 +397,48 @@ namespace EMotionFX const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); size_t testJointIndex; size_t testBendJointIndex; - AZStd::string& bendLoArm = m_param.linkedJointNames[0]; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); + 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 9d2e1a11c6..6214005a71 100644 --- a/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp @@ -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/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 d50b72cb4d..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 @@ -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(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(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/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/MorphTargetRuntimeTests.cpp b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp index 10f735ca24..02c17702a2 100644 --- a/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp @@ -82,7 +82,7 @@ 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, /*convertUnitType=*/false); diff --git a/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp b/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp index a857efb2ca..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) { @@ -195,7 +195,7 @@ namespace EMotionFX { 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 85c0e4201f..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: - size_t m_jack_rootIndex = InvalidIndex; - size_t m_jack_hipIndex = InvalidIndex; + 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 (size_t 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 (size_t 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 (size_t 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 02256e1e12..09a4e46b84 100644 --- a/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp +++ b/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp @@ -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 0dd592cda7..ed14da5354 100644 --- a/Gems/EMotionFX/Code/Tests/PoseTests.cpp +++ b/Gems/EMotionFX/Code/Tests/PoseTests.cpp @@ -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)); } /////////////////////////////////////////////////////////////////////////// @@ -747,16 +747,16 @@ namespace EMotionFX 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."; ) } @@ -786,7 +786,7 @@ namespace EMotionFX 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); } @@ -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); } } @@ -827,7 +827,7 @@ namespace EMotionFX 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); @@ -844,7 +844,7 @@ namespace EMotionFX 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); @@ -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); } } @@ -1030,7 +1030,7 @@ namespace EMotionFX { 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())); } } @@ -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); ) } @@ -1257,7 +1257,7 @@ namespace EMotionFX 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/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/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/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/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/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/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/CanMorphManyShapes.cpp b/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp index 2ed0407d53..f47ad20d23 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp @@ -66,7 +66,7 @@ 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, /*convertUnitType=*/false); @@ -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/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/UniformMotionDataTests.cpp b/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp index 7433a403e1..e82d10097b 100644 --- a/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp +++ b/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp @@ -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/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. From 4b68e6c7666cc034b3b56d9541c1c17e95e49106 Mon Sep 17 00:00:00 2001 From: AMZN-AlexOteiza <82234181+AMZN-AlexOteiza@users.noreply.github.com> Date: Tue, 10 Aug 2021 09:08:16 +0100 Subject: [PATCH 209/251] Added support for pytest marks, including skipping of tests (#2353) Signed-off-by: Garcia Ruiz Co-authored-by: Garcia Ruiz --- .../ly_test_tools/o3de/editor_test.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) 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 From c2a2d1c5c79b8c41211e2156dac7a98ba1a9a3d5 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 10 Aug 2021 14:20:46 +0100 Subject: [PATCH 210/251] Add changes from TIF/Feature branch. Signed-off-by: John --- .../Source/TestImpactCommandLineOptions.cpp | 56 +- .../Source/TestImpactCommandLineOptions.h | 24 +- .../Code/Source/TestImpactConsoleMain.cpp | 178 +++-- ...tImpactConsoleTestSequenceEventHandler.cpp | 58 +- ...estImpactConsoleTestSequenceEventHandler.h | 9 +- .../TestImpactRuntimeConfigurationFactory.cpp | 21 +- .../TestImpactClientSequenceReport.h | 508 ++++++++++++--- ...TestImpactClientSequenceReportSerializer.h | 28 + .../TestImpactClientTestRun.h | 131 ++-- .../TestImpactConfiguration.h | 2 +- .../TestImpactFramework/TestImpactPolicy.h | 81 +++ .../TestImpactFramework/TestImpactRuntime.h | 30 +- .../TestImpactSequenceReportException.h | 22 + .../TestImpactTestSequence.h | 114 +--- ...estImpactFileUtils.h => TestImpactUtils.h} | 65 +- .../TestImpactTestTargetMetaMapFactory.cpp | 4 +- .../TestImpactDynamicDependencyMap.cpp | 2 - .../TestImpactDynamicDependencyMap.h | 2 +- .../TestImpactTestSelectorAndPrioritizer.h | 2 +- .../Enumeration/TestImpactTestEnumerator.cpp | 2 +- .../Run/TestImpactInstrumentedTestRunner.cpp | 2 +- .../TestEngine/Run/TestImpactTestRunner.cpp | 2 +- .../TestEngine/TestImpactTestEngine.cpp | 2 +- .../Source/TestImpactClientSequenceReport.cpp | 318 ++++----- ...stImpactClientSequenceReportSerializer.cpp | 606 ++++++++++++++++++ .../Code/Source/TestImpactClientTestRun.cpp | 116 ++-- .../Runtime/Code/Source/TestImpactRuntime.cpp | 492 +++++++++----- .../Code/Source/TestImpactRuntimeUtils.cpp | 2 +- .../Code/Source/TestImpactRuntimeUtils.h | 56 +- .../Runtime/Code/Source/TestImpactUtils.cpp | 244 +++++++ .../testimpactframework_runtime_files.cmake | 7 +- .../ConsoleFrontendConfig.in | 6 +- .../LYTestImpactFramework.cmake | 9 +- .../build/Platform/Windows/build_config.json | 2 +- scripts/build/TestImpactAnalysis/git_utils.py | 77 ++- .../build/TestImpactAnalysis/mars_utils.py | 452 +++++++++++++ scripts/build/TestImpactAnalysis/tiaf.py | 436 +++++++------ .../build/TestImpactAnalysis/tiaf_driver.py | 130 +++- .../build/TestImpactAnalysis/tiaf_logger.py | 20 + .../tiaf_persistent_storage.py | 118 ++++ .../tiaf_persistent_storage_local.py | 56 ++ .../tiaf_persistent_storage_s3.py | 87 +++ 42 files changed, 3522 insertions(+), 1057 deletions(-) create mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h create mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactPolicy.h create mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactSequenceReportException.h rename Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/{TestImpactFileUtils.h => TestImpactUtils.h} (51%) create mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp create mode 100644 Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp create mode 100644 scripts/build/TestImpactAnalysis/mars_utils.py create mode 100644 scripts/build/TestImpactAnalysis/tiaf_logger.py create mode 100644 scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py create mode 100644 scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py create mode 100644 scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py 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 8027649a44..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,6 +52,20 @@ 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( const CommandLineOptions& options, @@ -88,35 +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 safeImpactAnalysisSequenceReport = runtime.SafeImpactAnalysisTestSequence( - changeList.value(), - options.GetTestPrioritizationPolicy(), - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - SafeImpactAnalysisTestSequenceStartCallback, - SafeImpactAnalysisTestSequenceCompleteCallback, - TestRunCompleteCallback); - - result = safeImpactAnalysisSequenceReport.GetResult(); + 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 - auto sequenceReport = runtime.RegularTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - TestSequenceStartCallback, - TestSequenceCompleteCallback, - TestRunCompleteCallback); - - result = sequenceReport.GetResult(); + return ConsumeSequenceReportAndGetReturnCode( + runtime.RegularTestSequence( + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + TestSequenceStartCallback, + RegularTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } else { @@ -139,20 +129,18 @@ namespace TestImpact throw(Exception("Unexpected sequence type")); } - auto impactAnalysisSequenceReport = runtime.ImpactAnalysisTestSequence( - changeList.value(), - options.GetTestPrioritizationPolicy(), - dynamicDependencyMapPolicy, - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - ImpactAnalysisTestSequenceStartCallback, - ImpactAnalysisTestSequenceCompleteCallback, - TestRunCompleteCallback); - - result = impactAnalysisSequenceReport.GetResult(); + 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. @@ -164,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(), @@ -208,25 +190,25 @@ namespace TestImpact { case TestSequenceType::Regular: { - const auto sequenceReport = runtime.RegularTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - TestSequenceStartCallback, - TestSequenceCompleteCallback, - TestRunCompleteCallback); - - return GetReturnCodeForTestSequenceResult(sequenceReport.GetResult()); + return ConsumeSequenceReportAndGetReturnCode( + runtime.RegularTestSequence( + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + TestSequenceStartCallback, + RegularTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } case TestSequenceType::Seed: { - const auto sequenceReport = runtime.SeededTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - TestSequenceStartCallback, - TestSequenceCompleteCallback, - TestRunCompleteCallback); - - return GetReturnCodeForTestSequenceResult(sequenceReport.GetResult()); + return ConsumeSequenceReportAndGetReturnCode( + runtime.SeededTestSequence( + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + TestSequenceStartCallback, + SeedTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } case TestSequenceType::ImpactAnalysisNoWrite: case TestSequenceType::ImpactAnalysis: @@ -241,14 +223,14 @@ namespace TestImpact } else { - const auto sequenceReport = runtime.SeededTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - TestSequenceStartCallback, - TestSequenceCompleteCallback, - TestRunCompleteCallback); - - return GetReturnCodeForTestSequenceResult(sequenceReport.GetResult()); + 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 da7052933c..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) @@ -36,69 +37,66 @@ namespace TestImpact { std::cout << "Sequence completed in " << (testRunReport.GetDuration().count() / 1000.f) << "s with"; - if (!testRunReport.GetExecutionFailureTests().empty() || - !testRunReport.GetFailingTests().empty() || - !testRunReport.GetTimedOutTests().empty() || - !testRunReport.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() - << testRunReport.GetFailingTests().size() + << testRunReport.GetFailingTestRuns().size() << ResetColor().c_str() << " test failures\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << testRunReport.GetExecutionFailureTests().size() + << testRunReport.GetExecutionFailureTestRuns().size() << ResetColor().c_str() << " execution failures\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << testRunReport.GetTimedOutTests().size() + << testRunReport.GetTimedOutTestRuns().size() << ResetColor().c_str() << " test timeouts\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << testRunReport.GetUnexecutedTests().size() + << testRunReport.GetUnexecutedTestRuns().size() << ResetColor().c_str() << " unexecuted tests\n"; - if (!testRunReport.GetFailingTests().empty()) + if (!testRunReport.GetFailingTestRuns().empty()) { std::cout << "\nTest failures:\n"; - for (const auto& testRunFailure : testRunReport.GetFailingTests()) + for (const auto& testRunFailure : testRunReport.GetFailingTestRuns()) { - for (const auto& testCaseFailure : testRunFailure.GetTestCaseFailures()) + for (const auto& test : testRunFailure.GetTests()) { - for (const auto& testFailure : testCaseFailure.GetTestFailures()) + if (test.GetResult() == Client::TestResult::Failed) { - std::cout << " " - << testRunFailure.GetTargetName().c_str() - << "." << testCaseFailure.GetName().c_str() - << "." << testFailure.GetName().c_str() << "\n"; + std::cout << " " << test.GetName().c_str() << "\n"; } } } } - if (!testRunReport.GetExecutionFailureTests().empty()) + if (!testRunReport.GetExecutionFailureTestRuns().empty()) { std::cout << "\nExecution failures:\n"; - for (const auto& executionFailure : testRunReport.GetExecutionFailureTests()) + for (const auto& executionFailure : testRunReport.GetExecutionFailureTestRuns()) { std::cout << " " << executionFailure.GetTargetName().c_str() << "\n"; std::cout << executionFailure.GetCommandString().c_str() << "\n"; } } - if (!testRunReport.GetTimedOutTests().empty()) + if (!testRunReport.GetTimedOutTestRuns().empty()) { std::cout << "\nTimed out tests:\n"; - for (const auto& testTimeout : testRunReport.GetTimedOutTests()) + for (const auto& testTimeout : testRunReport.GetTimedOutTestRuns()) { std::cout << " " << testTimeout.GetTargetName().c_str() << "\n"; } } - if (!testRunReport.GetUnexecutedTests().empty()) + if (!testRunReport.GetUnexecutedTestRuns().empty()) { std::cout << "\nUnexecuted tests:\n"; - for (const auto& unexecutedTest : testRunReport.GetUnexecutedTests()) + for (const auto& unexecutedTest : testRunReport.GetUnexecutedTestRuns()) { std::cout << " " << unexecutedTest.GetTargetName().c_str() << "\n"; } @@ -106,7 +104,7 @@ namespace TestImpact } else { - std::cout << SetColor(Foreground::White, Background::Green).c_str() << " \100% passes!\n" << ResetColor().c_str() << "\n"; + std::cout << " " << SetColor(Foreground::White, Background::Green).c_str() << "100% passes!\n" << ResetColor().c_str() << "\n"; } } } @@ -149,13 +147,17 @@ namespace TestImpact draftedTests.size()); } - void TestSequenceCompleteCallback(const Client::SequenceReport& sequenceReport) + void RegularTestSequenceCompleteCallback(const Client::RegularSequenceReport& sequenceReport) { - Output::FailureReport(sequenceReport.GetSelectedTestRunReport()); std::cout << "Updating and serializing the test impact analysis data, this may take a moment...\n"; } + void SeedTestSequenceCompleteCallback(const Client::SeedSequenceReport& sequenceReport) + { + Output::FailureReport(sequenceReport.GetSelectedTestRunReport()); + } + void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& sequenceReport) { std::cout << "Selected test run:\n"; @@ -181,7 +183,7 @@ namespace TestImpact std::cout << "Updating and serializing the test impact analysis data, this may take a moment...\n"; } - void TestRunCompleteCallback(const Client::TestRun& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns) + void TestRunCompleteCallback(const Client::TestRunBase& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns) { const auto progress = AZStd::string::format("(%03u/%03u)", numTestRunsCompleted, totalNumTestRuns, testRun.GetTargetName().c_str()); diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h index ff757b2d5a..8f28d60617 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h @@ -38,8 +38,11 @@ namespace TestImpact const Client::TestRunSelection& discardedTests, const AZStd::vector& draftedTests); - //! Handler for TestSequenceCompleteCallback event. - void TestSequenceCompleteCallback(const Client::SequenceReport& sequenceReport); + //! Handler for RegularTestSequenceCompleteCallback event. + void RegularTestSequenceCompleteCallback(const Client::RegularSequenceReport& sequenceReport); + + //! Handler for SeedTestSequenceCompleteCallback event. + void SeedTestSequenceCompleteCallback(const Client::SeedSequenceReport& sequenceReport); //! Handler for ImpactAnalysisTestSequenceCompleteCallback event. void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& sequenceReport); @@ -48,6 +51,6 @@ namespace TestImpact void SafeImpactAnalysisTestSequenceCompleteCallback(const Client::SafeImpactAnalysisSequenceReport& sequenceReport); //! Handler for TestRunCompleteCallback event. - void TestRunCompleteCallback(const Client::TestRun& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns); + 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/TestImpactClientSequenceReport.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h index 73f3827fae..e86123ddc7 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h @@ -1,6 +1,7 @@ /* - * 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. - * + * 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 * */ @@ -11,10 +12,25 @@ #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 { @@ -23,20 +39,20 @@ namespace TestImpact //! @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 passingTests The set of test runs that executed successfully with no failing tests. - //! @param failing tests The set of test runs that executed successfully but had one or more failing tests. - //! @param executionFailureTests The set of test runs that failed to execute. - //! @param timedOutTests The set of test runs that executed successfully but were terminated prematurely due to timing out. - //! @param unexecutedTests The set of test runs that were queued up for execution but did not get the opportunity to execute. + //! @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&& passingTests, - AZStd::vector&& failingTests, - AZStd::vector&& executionFailureTests, - AZStd::vector&& timedOutTests, - AZStd::vector&& unexecutedTests); + 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; @@ -50,190 +66,478 @@ namespace TestImpact //! 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 GetNumPassingTests() const; + size_t GetNumPassingTestRuns() const; //! Returns the number of failing test runs. - size_t GetNumFailingTests() const; + 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 GetNumTimedOutTests() const; + size_t GetNumTimedOutTestRuns() const; //! Returns the number of unexecuted test runs. - size_t GetNumUnexecutedTests() const; + 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& GetPassingTests() const; + const AZStd::vector& GetPassingTestRuns() const; //! Returns the set of test runs that executed successfully but had one or more failing tests. - const AZStd::vector& GetFailingTests() const; + const AZStd::vector& GetFailingTestRuns() const; //! Returns the set of test runs that failed to execute. - const AZStd::vector& GetExecutionFailureTests() const; + 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& GetTimedOutTests() const; + 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& GetUnexecutedTests() const; + const AZStd::vector& GetUnexecutedTestRuns() const; private: - TestSequenceResult m_result; + TestSequenceResult m_result = TestSequenceResult::Success; AZStd::chrono::high_resolution_clock::time_point m_startTime; - AZStd::chrono::milliseconds m_duration; - AZStd::vector m_passingTests; - AZStd::vector m_failingTests; - AZStd::vector m_executionFailureTests; - AZStd::vector m_timedOutTests; - AZStd::vector m_unexecutedTests; + 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; }; - //! Report detailing a test run sequence of selected tests. - class SequenceReport + //! 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 selectedTests The target names of the selected tests. + //! @param selectedTestRuns The target names of the selected test runs. //! @param selectedTestRunReport The report for the set of selected test runs. - SequenceReport(SuiteType suiteType, const TestRunSelection& selectedTests, TestRunReport&& selectedTestRunReport); + 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 GetSelectedTests() const; + TestRunSelection GetSelectedTestRuns() const + { + return m_selectedTestRuns; + } //! Returns the report for the selected test runs. - TestRunReport GetSelectedTestRunReport() const; + TestRunReport GetSelectedTestRunReport() const + { + return m_selectedTestRunReport; + } //! Returns the start time of the sequence. - AZStd::chrono::high_resolution_clock::time_point GetStartTime() const; + 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; - - //! Returns the result of the sequence. - virtual TestSequenceResult GetResult() const; + 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; - - //! Get the total number of tests in the sequence that passed. - virtual size_t GetTotalNumPassingTests() const; - - //! Get the total number of tests in the sequence that contain one or more test failures. - virtual size_t GetTotalNumFailingTests() const; - - //! Get the total number of tests in the sequence that timed out whilst in flight. - virtual size_t GetTotalNumTimedOutTests() const; - - //! Get the total number of tests in the sequence that were queued for execution but did not get the oppurtunity to execute. - virtual size_t GetTotalNumUnexecutedTests() const; + 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: - SuiteType m_suite; - TestRunSelection m_selectedTests; + 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. - class DraftingSequenceReport - : public SequenceReport + template + class DraftingSequenceReportBase + : public SequenceReportBase { public: - //! Constructs the report for a sequence of selected and drafted tests. + //! 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 selectedTests The target names of the selected tests. - //! @param draftedTests The target names of the drafted tests. + //! @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. - DraftingSequenceReport( + DraftingSequenceReportBase( + SequenceReportType type, + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const PolicyStateType& policyState, SuiteType suiteType, - const TestRunSelection& selectedTests, - const AZStd::vector& draftedTests, + const TestRunSelection& selectedTestRuns, + const AZStd::vector& draftedTestRuns, TestRunReport&& selectedTestRunReport, - TestRunReport&& draftedTestRunReport); - - // SequenceReport overrides ... - TestSequenceResult GetResult() const override; - AZStd::chrono::milliseconds GetDuration() const override; - size_t GetTotalNumPassingTests() const override; - size_t GetTotalNumFailingTests() const override; - size_t GetTotalNumTimedOutTests() const override; - size_t GetTotalNumUnexecutedTests() const override; - - //! Returns the tests drafted for running in the sequence. - const AZStd::vector& GetDraftedTests() const; + 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; + 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_draftedTests; + AZStd::vector m_draftedTestRuns; TestRunReport m_draftedTestRunReport; }; //! Report detailing an impact analysis sequence of selected, discarded and drafted tests. class ImpactAnalysisSequenceReport - : public DraftingSequenceReport + : public DraftingSequenceReportBase { public: - //! Constructs the report for a sequence of selected and drafted tests. + //! 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 selectedTests The target names of the selected tests. - //! @param discardedTests The target names of the discarded tests. - //! @param draftedTests The target names of the drafted tests. + //! @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& selectedTests, - const AZStd::vector& discardedTests, - const AZStd::vector& draftedTests, + const TestRunSelection& selectedTestRuns, + const AZStd::vector& discardedTestRuns, + const AZStd::vector& draftedTestRuns, TestRunReport&& selectedTestRunReport, TestRunReport&& draftedTestRunReport); - //! Returns the tests discarded from running in the sequence. - const AZStd::vector& GetDiscardedTests() const; + //! Returns the test runs discarded from running in the sequence. + const AZStd::vector& GetDiscardedTestRuns() const; private: - AZStd::vector m_discardedTests; + AZStd::vector m_discardedTestRuns; }; - //! Report detailing an impact analysis sequence of selected, discarded and drafted tests. + //! Report detailing an impact analysis sequence of selected, discarded and drafted test runs. class SafeImpactAnalysisSequenceReport - : public DraftingSequenceReport + : public DraftingSequenceReportBase { public: - //! Constructs the report for a sequence of selected and drafted tests. + //! 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 selectedTests The target names of the selected tests. - //! @param discardedTests The target names of the discarded tests. - //! @param draftedTests The target names of the drafted tests. + //! @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& selectedTests, - const TestRunSelection& discardedTests, - const AZStd::vector& draftedTests, + const TestRunSelection& selectedTestRuns, + const TestRunSelection& discardedTestRuns, + const AZStd::vector& draftedTestRuns, TestRunReport&& selectedTestRunReport, TestRunReport&& discardedTestRunReport, TestRunReport&& draftedTestRunReport); - // DraftingSequenceReport overrides ... - TestSequenceResult GetResult() const override; + // 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 GetTotalNumTimedOutTests() const override; - size_t GetTotalNumUnexecutedTests() 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 GetDiscardedTests() const; + const TestRunSelection GetDiscardedTestRuns() const; //! Returns the report for the discarded test runs. TestRunReport GetDiscardedTestRunReport() const; private: - TestRunSelection m_discardedTests; + TestRunSelection m_discardedTestRuns; TestRunReport m_discardedTestRunReport; }; } // namespace Client 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 4b7715bf1d..f22963b5e6 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestRun.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestRun.h @@ -26,8 +26,8 @@ namespace TestImpact AllTestsPass //!< The test run completed its run and all tests passed. }; - //! Representation of a completed test run. - class TestRun + //! Representation of a test run. + class TestRunBase { public: //! Constructs the client facing representation of a given test target's run. @@ -36,13 +36,15 @@ namespace TestImpact //! @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. - TestRun( + 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; @@ -69,75 +71,120 @@ namespace TestImpact AZStd::chrono::milliseconds m_duration; }; - //! Represents an individual test of a test target that failed. - class TestFailure + //! Representation of a test run that failed to execute. + class TestRunWithExecutionFailure + : public TestRunBase { public: - TestFailure(const AZStd::string& testName, const AZStd::string& errorMessage); + using TestRunBase::TestRunBase; + TestRunWithExecutionFailure(TestRunBase&& testRun); + }; - //! Returns the name of the test that failed. - const AZStd::string& GetName() const; + //! 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); + }; - //! Returns the error message of the test that failed. - const AZStd::string& GetErrorMessage() const; + //! Representation of a test run that was not executed. + class UnexecutedTestRun + : public TestRunBase + { + public: + using TestRunBase::TestRunBase; + UnexecutedTestRun(TestRunBase&& testRun); + }; - private: - AZStd::string m_name; - AZStd::string m_errorMessage; + // Result of a test executed during a test run. + enum class TestResult : AZ::u8 + { + Passed, + Failed, + NotRun }; - //! Represents a collection of tests that failed. - //! @note Only the failing tests are included in the collection. - class TestCaseFailure + //! Representation of a single test in a test target. + class Test { public: - TestCaseFailure(const AZStd::string& testCaseName, AZStd::vector&& testFailures); + //! Constructs the test with the specified name and result. + Test(const AZStd::string& testName, TestResult result); - //! Returns the name of the test case containing the failing tests. + //! Returns the name of this test. const AZStd::string& GetName() const; - //! Returns the collection of tests in this test case that failed. - const AZStd::vector& GetTestFailures() const; + //! Returns the result of executing this test. + TestResult GetResult() const; private: AZStd::string m_name; - AZStd::vector m_testFailures; + TestResult m_result; }; - //! Representation of a test run's failing tests. - class TestRunWithTestFailures - : public TestRun + //! Representation of a test run that completed with or without test failures. + class CompletedTestRun + : public TestRunBase { public: - //! 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. + //! 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 the run. - //! @param testFailures The failing tests for this test run. - TestRunWithTestFailures( + //! @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&& testFailures); + AZStd::vector&& tests); - //! Constructs the client facing representation of a given test target's run. - //! @param testRun The test run this run is to be derived from. - //! @param testFailures The failing tests for this run. - TestRunWithTestFailures(TestRun&& testRun, AZStd::vector&& testFailures); + //! 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 failing tests in this run. - size_t GetNumTestFailures() const; + //! Returns the total number of passing tests in the run. + size_t GetTotalNumPassingTests() const; - //! Returns the test cases in this run containing failing tests. - const AZStd::vector& GetTestCaseFailures() 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_testCaseFailures; - size_t m_numTestFailures = 0; + 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/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 69feb48749..ec8d88eaad 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRuntime.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRuntime.h @@ -78,7 +78,7 @@ namespace TestImpact //! @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; + using TestRunCompleteCallback = AZStd::function; //! The API exposed to the client responsible for all test runs and persistent data management. class Runtime @@ -86,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. @@ -94,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, @@ -112,11 +114,11 @@ namespace TestImpact //! @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 The test run and sequence report for the selected test sequence. - Client::SequenceReport RegularTestSequence( + 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. @@ -164,11 +166,11 @@ namespace TestImpact //! @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 The test run and sequence report for the selected test sequence. - Client::SequenceReport SeededTestSequence( + 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). @@ -184,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); @@ -204,8 +206,22 @@ 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; + RepoPath m_sparTiaFile; SuiteType m_suiteFilter; Policy::ExecutionFailure m_executionFailurePolicy; Policy::FailedTestCoverage m_failedTestCoveragePolicy; 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 226301d444..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 diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp index ba3a479fdf..3f4656758a 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp @@ -1,6 +1,7 @@ /* - * 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. - * + * 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 * */ @@ -11,7 +12,6 @@ namespace TestImpact { namespace Client { - //! Calculates the final sequence result for a composite of multiple sequences. TestSequenceResult CalculateMultiTestSequenceResult(const AZStd::vector& results) { // Order of precedence: @@ -19,14 +19,12 @@ namespace TestImpact // 2. TestSequenceResult::Timeout // 3. TestSequenceResult::Success - if (const auto it = AZStd::find(results.begin(), results.end(), TestSequenceResult::Failure); - it != results.end()) + 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()) + + if (const auto it = AZStd::find(results.begin(), results.end(), TestSequenceResult::Timeout); it != results.end()) { return TestSequenceResult::Timeout; } @@ -38,20 +36,32 @@ namespace TestImpact TestSequenceResult result, AZStd::chrono::high_resolution_clock::time_point startTime, AZStd::chrono::milliseconds duration, - AZStd::vector&& passingTests, - AZStd::vector&& failingTests, - AZStd::vector&& executionFailureTests, - AZStd::vector&& timedOutTests, - AZStd::vector&& unexecutedTests) + 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_passingTests(AZStd::move(passingTests)) - , m_failingTests(AZStd::move(failingTests)) - , m_executionFailureTests(AZStd::move(executionFailureTests)) - , m_timedOutTests(AZStd::move(timedOutTests)) - , m_unexecutedTests(AZStd::move(unexecutedTests)) + , 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 @@ -74,234 +84,238 @@ namespace TestImpact return m_duration; } - size_t TestRunReport::GetNumPassingTests() const - { - return m_passingTests.size(); - } - - size_t TestRunReport::GetNumFailingTests() const - { - return m_failingTests.size(); - } - - size_t TestRunReport::GetNumTimedOutTests() const - { - return m_timedOutTests.size(); - } - - size_t TestRunReport::GetNumUnexecutedTests() const + size_t TestRunReport::GetTotalNumTestRuns() const { - return m_unexecutedTests.size(); + return + GetNumPassingTestRuns() + + GetNumFailingTestRuns() + + GetNumExecutionFailureTestRuns() + + GetNumTimedOutTestRuns() + + GetNumUnexecutedTestRuns(); } - const AZStd::vector& TestRunReport::GetPassingTests() const + size_t TestRunReport::GetNumPassingTestRuns() const { - return m_passingTests; + return m_passingTestRuns.size(); } - const AZStd::vector& TestRunReport::GetFailingTests() const + size_t TestRunReport::GetNumFailingTestRuns() const { - return m_failingTests; + return m_failingTestRuns.size(); } - const AZStd::vector& TestRunReport::GetExecutionFailureTests() const + size_t TestRunReport::GetNumExecutionFailureTestRuns() const { - return m_executionFailureTests; + return m_executionFailureTestRuns.size(); } - const AZStd::vector& TestRunReport::GetTimedOutTests() const + size_t TestRunReport::TestRunReport::GetNumTimedOutTestRuns() const { - return m_timedOutTests; + return m_timedOutTestRuns.size(); } - const AZStd::vector& TestRunReport::GetUnexecutedTests() const + size_t TestRunReport::GetNumUnexecutedTestRuns() const { - return m_unexecutedTests; + return m_unexecutedTestRuns.size(); } - SequenceReport::SequenceReport(SuiteType suiteType, const TestRunSelection& selectedTests, TestRunReport&& selectedTestRunReport) - : m_suite(suiteType) - , m_selectedTests(selectedTests) - , m_selectedTestRunReport(AZStd::move(selectedTestRunReport)) + const AZStd::vector& TestRunReport::GetPassingTestRuns() const { + return m_passingTestRuns; } - TestSequenceResult SequenceReport::GetResult() const + const AZStd::vector& TestRunReport::GetFailingTestRuns() const { - return m_selectedTestRunReport.GetResult(); + return m_failingTestRuns; } - AZStd::chrono::high_resolution_clock::time_point SequenceReport::GetStartTime() const + const AZStd::vector& TestRunReport::GetExecutionFailureTestRuns() const { - return m_selectedTestRunReport.GetStartTime(); + return m_executionFailureTestRuns; } - AZStd::chrono::high_resolution_clock::time_point SequenceReport::GetEndTime() const + const AZStd::vector& TestRunReport::GetTimedOutTestRuns() const { - return GetStartTime() + GetDuration(); + return m_timedOutTestRuns; } - AZStd::chrono::milliseconds SequenceReport::GetDuration() const + const AZStd::vector& TestRunReport::GetUnexecutedTestRuns() const { - return m_selectedTestRunReport.GetDuration(); + return m_unexecutedTestRuns; } - TestRunSelection SequenceReport::GetSelectedTests() const + size_t TestRunReport::GetTotalNumPassingTests() const { - return m_selectedTests; + return m_totalNumPassingTests; } - TestRunReport SequenceReport::GetSelectedTestRunReport() const + size_t TestRunReport::GetTotalNumFailingTests() const { - return m_selectedTestRunReport; + return m_totalNumFailingTests; } - size_t SequenceReport::GetTotalNumPassingTests() const + size_t TestRunReport::GetTotalNumDisabledTests() const { - return m_selectedTestRunReport.GetNumPassingTests(); + return m_totalNumDisabledTests; } - size_t SequenceReport::GetTotalNumFailingTests() const - { - return m_selectedTestRunReport.GetNumFailingTests(); - } - - size_t SequenceReport::GetTotalNumTimedOutTests() const + 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)) { - return m_selectedTestRunReport.GetNumTimedOutTests(); } - size_t SequenceReport::GetTotalNumUnexecutedTests() const + 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)) { - return m_selectedTestRunReport.GetNumUnexecutedTests(); } - DraftingSequenceReport::DraftingSequenceReport( + ImpactAnalysisSequenceReport::ImpactAnalysisSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const ImpactAnalysisSequencePolicyState& policyState, SuiteType suiteType, - const TestRunSelection& selectedTests, - const AZStd::vector& draftedTests, + const TestRunSelection& selectedTestRuns, + const AZStd::vector& discardedTestRuns, + const AZStd::vector& draftedTestRuns, TestRunReport&& selectedTestRunReport, TestRunReport&& draftedTestRunReport) - : SequenceReport(suiteType, selectedTests, AZStd::move(selectedTestRunReport)) - , m_draftedTests(draftedTests) - , m_draftedTestRunReport(AZStd::move(draftedTestRunReport)) - { - } - - TestSequenceResult DraftingSequenceReport::GetResult() const - { - return CalculateMultiTestSequenceResult({SequenceReport::GetResult(), m_draftedTestRunReport.GetResult()}); - } - - AZStd::chrono::milliseconds DraftingSequenceReport::GetDuration() const - { - return SequenceReport::GetDuration() + m_draftedTestRunReport.GetDuration(); - } - - size_t DraftingSequenceReport::GetTotalNumPassingTests() const + : DraftingSequenceReportBase( + SequenceReportType::ImpactAnalysisSequence, + maxConcurrency, + testTargetTimeout, + globalTimeout, + policyState, + suiteType, + selectedTestRuns, + draftedTestRuns, + AZStd::move(selectedTestRunReport), + AZStd::move(draftedTestRunReport)) + , m_discardedTestRuns(discardedTestRuns) { - return SequenceReport::GetTotalNumPassingTests() + m_draftedTestRunReport.GetNumPassingTests(); } - size_t DraftingSequenceReport::GetTotalNumFailingTests() const + const AZStd::vector& ImpactAnalysisSequenceReport::GetDiscardedTestRuns() const { - return SequenceReport::GetTotalNumFailingTests() + m_draftedTestRunReport.GetNumFailingTests(); + return m_discardedTestRuns; } - size_t DraftingSequenceReport::GetTotalNumTimedOutTests() const + 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)) { - return SequenceReport::GetTotalNumTimedOutTests() + m_draftedTestRunReport.GetNumTimedOutTests(); } - size_t DraftingSequenceReport::GetTotalNumUnexecutedTests() const + TestSequenceResult SafeImpactAnalysisSequenceReport::GetResult() const { - return SequenceReport::GetTotalNumUnexecutedTests() + m_draftedTestRunReport.GetNumUnexecutedTests(); + return CalculateMultiTestSequenceResult({ DraftingSequenceReportBase::GetResult(), m_discardedTestRunReport.GetResult() }); } - const AZStd::vector& DraftingSequenceReport::GetDraftedTests() const + AZStd::chrono::milliseconds SafeImpactAnalysisSequenceReport::GetDuration() const { - return m_draftedTests; + return DraftingSequenceReportBase::GetDuration() + m_discardedTestRunReport.GetDuration(); } - TestRunReport DraftingSequenceReport::GetDraftedTestRunReport() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumTestRuns() const { - return m_draftedTestRunReport; + return DraftingSequenceReportBase::GetTotalNumTestRuns() + m_discardedTestRunReport.GetTotalNumTestRuns(); } - ImpactAnalysisSequenceReport::ImpactAnalysisSequenceReport( - SuiteType suiteType, - const TestRunSelection& selectedTests, - const AZStd::vector& discardedTests, - const AZStd::vector& draftedTests, - TestRunReport&& selectedTestRunReport, - TestRunReport&& draftedTestRunReport) - : DraftingSequenceReport( - suiteType, - selectedTests, - draftedTests, - AZStd::move(selectedTestRunReport), - AZStd::move(draftedTestRunReport)) - , m_discardedTests(discardedTests) - { - } - - const AZStd::vector& ImpactAnalysisSequenceReport::GetDiscardedTests() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumPassingTests() const { - return m_discardedTests; + return DraftingSequenceReportBase::GetTotalNumPassingTests() + m_discardedTestRunReport.GetTotalNumPassingTests(); } - SafeImpactAnalysisSequenceReport::SafeImpactAnalysisSequenceReport( - SuiteType suiteType, - const TestRunSelection& selectedTests, - const TestRunSelection& discardedTests, - const AZStd::vector& draftedTests, - TestRunReport&& selectedTestRunReport, - TestRunReport&& discardedTestRunReport, - TestRunReport&& draftedTestRunReport) - : DraftingSequenceReport( - suiteType, - selectedTests, - draftedTests, - AZStd::move(selectedTestRunReport), - AZStd::move(draftedTestRunReport)) - , m_discardedTests(discardedTests) - , m_discardedTestRunReport(AZStd::move(discardedTestRunReport)) + size_t SafeImpactAnalysisSequenceReport::GetTotalNumFailingTests() const { + return DraftingSequenceReportBase::GetTotalNumFailingTests() + m_discardedTestRunReport.GetTotalNumFailingTests(); } - TestSequenceResult SafeImpactAnalysisSequenceReport::GetResult() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumDisabledTests() const { - return CalculateMultiTestSequenceResult({ DraftingSequenceReport::GetResult(), m_discardedTestRunReport.GetResult() }); + return DraftingSequenceReportBase::GetTotalNumDisabledTests() + m_discardedTestRunReport.GetTotalNumDisabledTests(); } - AZStd::chrono::milliseconds SafeImpactAnalysisSequenceReport::GetDuration() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumPassingTestRuns() const { - return DraftingSequenceReport::GetDuration() + m_discardedTestRunReport.GetDuration(); + return DraftingSequenceReportBase::GetTotalNumPassingTestRuns() + m_discardedTestRunReport.GetNumPassingTestRuns(); } - size_t SafeImpactAnalysisSequenceReport::GetTotalNumPassingTests() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumFailingTestRuns() const { - return DraftingSequenceReport::GetTotalNumPassingTests() + m_discardedTestRunReport.GetNumPassingTests(); + return DraftingSequenceReportBase::GetTotalNumFailingTestRuns() + m_discardedTestRunReport.GetNumFailingTestRuns(); } - size_t SafeImpactAnalysisSequenceReport::GetTotalNumFailingTests() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumExecutionFailureTestRuns() const { - return DraftingSequenceReport::GetTotalNumFailingTests() + m_discardedTestRunReport.GetNumFailingTests(); + return DraftingSequenceReportBase::GetTotalNumExecutionFailureTestRuns() + m_discardedTestRunReport.GetNumExecutionFailureTestRuns(); } - size_t SafeImpactAnalysisSequenceReport::GetTotalNumTimedOutTests() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumTimedOutTestRuns() const { - return DraftingSequenceReport::GetTotalNumTimedOutTests() + m_discardedTestRunReport.GetNumTimedOutTests(); + return DraftingSequenceReportBase::GetTotalNumTimedOutTestRuns() + m_discardedTestRunReport.GetNumTimedOutTestRuns(); } - size_t SafeImpactAnalysisSequenceReport::GetTotalNumUnexecutedTests() const + size_t SafeImpactAnalysisSequenceReport::GetTotalNumUnexecutedTestRuns() const { - return DraftingSequenceReport::GetTotalNumUnexecutedTests() + m_discardedTestRunReport.GetNumUnexecutedTests(); + return DraftingSequenceReportBase::GetTotalNumUnexecutedTestRuns() + m_discardedTestRunReport.GetNumUnexecutedTestRuns(); } - const TestRunSelection SafeImpactAnalysisSequenceReport::GetDiscardedTests() const + const TestRunSelection SafeImpactAnalysisSequenceReport::GetDiscardedTestRuns() const { - return m_discardedTests; + return m_discardedTestRuns; } TestRunReport SafeImpactAnalysisSequenceReport::GetDiscardedTestRunReport() const 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 0a258c5dac..6f50145716 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp @@ -8,11 +8,13 @@ #include +#include + namespace TestImpact { namespace Client { - TestRun::TestRun( + TestRunBase::TestRunBase( const AZStd::string& name, const AZStd::string& commandString, AZStd::chrono::high_resolution_clock::time_point startTime, @@ -26,107 +28,145 @@ namespace TestImpact { } - const AZStd::string& TestRun::GetTargetName() const + const AZStd::string& TestRunBase::GetTargetName() const { return m_targetName; } - const AZStd::string& TestRun::GetCommandString() const + const AZStd::string& TestRunBase::GetCommandString() const { return m_commandString; } - AZStd::chrono::high_resolution_clock::time_point TestRun::GetStartTime() const + AZStd::chrono::high_resolution_clock::time_point TestRunBase::GetStartTime() const { return m_startTime; } - AZStd::chrono::high_resolution_clock::time_point TestRun::GetEndTime() const + AZStd::chrono::high_resolution_clock::time_point TestRunBase::GetEndTime() const { return m_startTime + m_duration; } - AZStd::chrono::milliseconds TestRun::GetDuration() const + AZStd::chrono::milliseconds TestRunBase::GetDuration() const { return m_duration; } - TestRunResult TestRun::GetResult() const + TestRunResult TestRunBase::GetResult() const { return m_result; } - TestFailure::TestFailure(const AZStd::string& testName, const AZStd::string& errorMessage) - : m_name(testName) - , m_errorMessage(errorMessage) + TestRunWithExecutionFailure::TestRunWithExecutionFailure(TestRunBase&& testRun) + : TestRunBase(AZStd::move(testRun)) { } - const AZStd::string& TestFailure::GetName() const + TimedOutTestRun::TimedOutTestRun(TestRunBase&& testRun) + : TestRunBase(AZStd::move(testRun)) { - return m_name; } - const AZStd::string& TestFailure::GetErrorMessage() const + UnexecutedTestRun::UnexecutedTestRun(TestRunBase&& testRun) + : TestRunBase(AZStd::move(testRun)) { - return m_errorMessage; } - TestCaseFailure::TestCaseFailure(const AZStd::string& testCaseName, AZStd::vector&& testFailures) - : m_name(testCaseName) - , m_testFailures(AZStd::move(testFailures)) + Test::Test(const AZStd::string& testName, TestResult result) + : m_name(testName) + , m_result(result) { } - const AZStd::string& TestCaseFailure::GetName() const + const AZStd::string& Test::GetName() const { return m_name; } - const AZStd::vector& TestCaseFailure::GetTestFailures() const + TestResult Test::GetResult() const { - return m_testFailures; + return m_result; } - static size_t CalculateNumTestRunFailures(const AZStd::vector& testFailures) + AZStd::tuple CalculateTestCaseMetrics(const AZStd::vector& tests) { - size_t numTestFailures = 0; - for (const auto& testCase : testFailures) + size_t totalNumPassingTests = 0; + size_t totalNumFailingTests = 0; + size_t totalNumDisabledTests = 0; + + for (const auto& test : tests) { - numTestFailures += testCase.GetTestFailures().size(); + if (test.GetResult() == Client::TestResult::Passed) + { + totalNumPassingTests++; + } + else if (test.GetResult() == Client::TestResult::Failed) + { + totalNumFailingTests++; + } + else + { + totalNumDisabledTests++; + } } - return numTestFailures; + return { totalNumPassingTests, totalNumFailingTests, totalNumDisabledTests }; } - TestRunWithTestFailures::TestRunWithTestFailures( + 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&& testFailures) - : TestRun(name, commandString, startTime, duration, result) - , m_testCaseFailures(AZStd::move(testFailures)) + 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 { - m_numTestFailures = CalculateNumTestRunFailures(m_testCaseFailures); + return m_totalNumDisabledTests; } - TestRunWithTestFailures::TestRunWithTestFailures(TestRun&& testRun, AZStd::vector&& testFailures) - : TestRun(AZStd::move(testRun)) - , m_testCaseFailures(AZStd::move(testFailures)) + const AZStd::vector& CompletedTestRun::GetTests() const { - m_numTestFailures = CalculateNumTestRunFailures(m_testCaseFailures); + return m_tests; } - size_t TestRunWithTestFailures::GetNumTestFailures() const + PassingTestRun::PassingTestRun(TestRunBase&& testRun, AZStd::vector&& tests) + : CompletedTestRun(AZStd::move(testRun), AZStd::move(tests)) { - return m_numTestFailures; } - const AZStd::vector& TestRunWithTestFailures::GetTestCaseFailures() const + FailingTestRun::FailingTestRun(TestRunBase&& testRun, AZStd::vector&& tests) + : CompletedTestRun(AZStd::move(testRun), AZStd::move(tests)) { - return m_testCaseFailures; } } // 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 478b63e8b2..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 @@ -81,7 +81,7 @@ namespace TestImpact { if (m_testCompleteCallback.has_value()) { - Client::TestRun testRun( + Client::TestRunBase testRun( testJob.GetTestTarget()->GetName(), testJob.GetCommandString(), testJob.GetStartTime(), @@ -110,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, @@ -151,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) @@ -186,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()); } } @@ -230,7 +357,7 @@ namespace TestImpact } } - AZStd::pair, AZStd::vector> Runtime::SelectCoveringTestTargetsAndUpdateEnumerationCache( + AZStd::pair, AZStd::vector> Runtime::SelectCoveringTestTargets( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy) { @@ -243,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()) { @@ -287,7 +411,7 @@ namespace TestImpact void Runtime::ClearDynamicDependencyMapAndRemoveExistingFile() { m_dynamicDependencyMap->ClearAllSourceCoverage(); - DeleteFile(m_sparTIAFile); + DeleteFile(m_sparTiaFile); } SourceCoveringTestsList Runtime::CreateSourceCoveringTestFromTestCoverages(const AZStd::vector& jobs) @@ -368,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) @@ -386,11 +510,42 @@ namespace TestImpact } } - Client::SequenceReport 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) { const Timer sequenceTimer; @@ -434,7 +589,11 @@ namespace TestImpact const auto testRunDuration = testRunTimer.GetElapsedMs(); // Generate the sequence report for the client - const auto sequenceReport = Client::SequenceReport( + const auto sequenceReport = Client::RegularSequenceReport( + m_maxConcurrency, + testTargetTimeout, + globalTimeout, + GenerateSequencePolicyState(), m_suiteFilter, selectedTests, GenerateTestRunReport(result, testRunTimer.GetStartTimePointRelative(sequenceTimer), testRunDuration, testJobs)); @@ -448,95 +607,6 @@ namespace TestImpact return sequenceReport; } - //! 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 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( - 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 globalTimeout, - AZStd::optional testSequenceStartCallback, - AZStd::optional> testSequenceEndCallback, - AZStd::optional testCompleteCallback, - AZStd::optional& jobs)>> updateCoverage) - { - 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); - - // Run the selected test targets and collect the test run results - const Timer selectedTestRunTimer; - const auto [selectedResult, selectedTestJobs] = testRunner(includedSelectedTestTargets, testRunCompleteHandler, globalTimeout); - const auto selectedTestRunDuration = selectedTestRunTimer.GetElapsedMs(); - - // Carry the remaining global sequence time over to the drafted test run - if (globalTimeout.has_value()) - { - const auto elapsed = selectedTestRunDuration; - sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); - } - - // Run the drafted test targets and collect the test run results - Timer draftedTestRunTimer; - const auto [draftedResult, draftedTestJobs] = testRunner(draftedTestTargets, testRunCompleteHandler, globalTimeout); - const auto draftedTestRunDuration = draftedTestRunTimer.GetElapsedMs(); - - // Generate the sequence report for the client - const auto sequenceReport = Client::ImpactAnalysisSequenceReport( - suiteType, - selectedTests, - discardedTests, - draftedTests, - GenerateTestRunReport(selectedResult, selectedTestRunTimer.GetStartTimePointRelative(sequenceTimer), selectedTestRunDuration, selectedTestJobs), - GenerateTestRunReport(draftedResult, draftedTestRunTimer.GetStartTimePointRelative(sequenceTimer), draftedTestRunDuration, draftedTestJobs)); - - // 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(selectedTestJobs, draftedTestJobs)); - } - - return sequenceReport; - } - Client::ImpactAnalysisSequenceReport Runtime::ImpactAnalysisTestSequence( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy, @@ -550,10 +620,30 @@ namespace TestImpact 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); + + const AZStd::unordered_set draftedTestTargetsSet(draftedTestTargets.begin(), draftedTestTargets.end()); + + AZStd::vector discardedNotDraftedTestTargets; + for (const auto* testTarget : discardedTestTargets) + { + if (!draftedTestTargetsSet.count(testTarget)) + { + discardedNotDraftedTestTargets.push_back(testTarget); + } + } + + return AZStd::pair{ selectedTestTargets, discardedNotDraftedTestTargets }; + }; + + 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); @@ -604,6 +694,8 @@ namespace TestImpact }; return ImpactAnalysisTestSequenceWrapper( + m_maxConcurrency, + GenerateImpactAnalysisSequencePolicyState(testPrioritizationPolicy, dynamicDependencyMapPolicy), m_suiteFilter, sequenceTimer, instrumentedTestRun, @@ -611,6 +703,7 @@ namespace TestImpact excludedSelectedTestTargets, discardedTestTargets, draftedTestTargets, + testTargetTimeout, globalTimeout, testSequenceStartCallback, testSequenceEndCallback, @@ -620,6 +713,8 @@ namespace TestImpact else { return ImpactAnalysisTestSequenceWrapper( + m_maxConcurrency, + GenerateImpactAnalysisSequencePolicyState(testPrioritizationPolicy, dynamicDependencyMapPolicy), m_suiteFilter, sequenceTimer, regularTestRun, @@ -627,6 +722,7 @@ namespace TestImpact excludedSelectedTestTargets, discardedTestTargets, draftedTestTargets, + testTargetTimeout, globalTimeout, testSequenceStartCallback, testSequenceEndCallback, @@ -645,13 +741,15 @@ namespace TestImpact AZStd::optional testCompleteCallback) { const Timer sequenceTimer; - auto sequenceTimeout = globalTimeout; + 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); @@ -675,71 +773,107 @@ namespace TestImpact // 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); + + // 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)); + }; - // Run the selected test targets and collect the test run results - const Timer selectedTestRunTimer; - const auto [selectedResult, selectedTestJobs] = m_testEngine->InstrumentedRun( - includedSelectedTestTargets, - m_testShardingPolicy, - m_executionFailurePolicy, - m_integrationFailurePolicy, - m_testFailurePolicy, - m_targetOutputCapture, - testTargetTimeout, - sequenceTimeout, - AZStd::ref(testRunCompleteHandler)); - const auto selectedTestRunDuration = selectedTestRunTimer.GetElapsedMs(); + // 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 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()) { - const auto elapsed = selectedTestRunDuration; - sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); - } + // Run the selected test targets and collect the test run results + gatherTestRunData(includedSelectedTestTargets, instrumentedTestRun, selectedTestRunData); - // Run the discarded test targets and collect the test run results - const Timer discardedTestRunTimer; - const auto [discardedResult, discardedTestJobs] = m_testEngine->RegularRun( - includedDiscardedTestTargets, - m_testShardingPolicy, - m_executionFailurePolicy, - m_testFailurePolicy, - m_targetOutputCapture, - testTargetTimeout, - sequenceTimeout, - AZStd::ref(testRunCompleteHandler)); - const auto discardedTestRunDuration = discardedTestRunTimer.GetElapsedMs(); + // 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); + } + } - // Carry the remaining global sequence time over to the drafted test run - if (globalTimeout.has_value()) + if (!includedDiscardedTestTargets.empty()) { - const auto elapsed = selectedTestRunDuration + discardedTestRunDuration; - sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + // 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); + } } - // Run the drafted test targets and collect the test run results - const Timer draftedTestRunTimer; - const auto [draftedResult, draftedTestJobs] = m_testEngine->InstrumentedRun( - draftedTestTargets, - m_testShardingPolicy, - m_executionFailurePolicy, - m_integrationFailurePolicy, - m_testFailurePolicy, - m_targetOutputCapture, - testTargetTimeout, - sequenceTimeout, - AZStd::ref(testRunCompleteHandler)); - const auto draftedTestRunDuration = draftedTestRunTimer.GetElapsedMs(); + 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(selectedResult, selectedTestRunTimer.GetStartTimePointRelative(sequenceTimer), selectedTestRunDuration, selectedTestJobs), - GenerateTestRunReport(discardedResult, discardedTestRunTimer.GetStartTimePointRelative(sequenceTimer), discardedTestRunDuration, discardedTestJobs), - GenerateTestRunReport(draftedResult, draftedTestRunTimer.GetStartTimePointRelative(sequenceTimer), draftedTestRunDuration, draftedTestJobs)); + 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()) @@ -747,15 +881,15 @@ namespace TestImpact (*testSequenceEndCallback)(sequenceReport); } - UpdateAndSerializeDynamicDependencyMap(ConcatenateVectors(selectedTestJobs, draftedTestJobs)); + UpdateAndSerializeDynamicDependencyMap(ConcatenateVectors(selectedTestRunData.m_jobs, draftedTestRunData.m_jobs)); return sequenceReport; } - Client::SequenceReport Runtime::SeededTestSequence( + Client::SeedSequenceReport Runtime::SeededTestSequence( AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional> testSequenceEndCallback, + AZStd::optional> testSequenceEndCallback, AZStd::optional testCompleteCallback) { const Timer sequenceTimer; @@ -799,7 +933,11 @@ namespace TestImpact const auto testRunDuration = testRunTimer.GetElapsedMs(); // Generate the sequence report for the client - const auto sequenceReport = Client::SequenceReport( + const auto sequenceReport = Client::SeedSequenceReport( + m_maxConcurrency, + testTargetTimeout, + globalTimeout, + GenerateSequencePolicyState(), m_suiteFilter, selectedTests, GenerateTestRunReport(result, testRunTimer.GetStartTimePointRelative(sequenceTimer), testRunDuration, testJobs)); diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp index 0c61c5f426..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 diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h index 33e15bfd20..23d78ee329 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h @@ -38,34 +38,44 @@ namespace TestImpact //! Extracts the name information from the specified test targets. 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 - AZStd::vector GenerateTestCaseFailures(const TestJob& testJob) + AZStd::vector GenerateClientTests(const TestJob& testJob) { - AZStd::vector testCaseFailures; + AZStd::vector tests; if (testJob.GetTestRun().has_value()) { 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 testCaseFailures; + return tests; } template @@ -75,11 +85,11 @@ namespace TestImpact AZStd::chrono::milliseconds duration, const AZStd::vector& testJobs) { - AZStd::vector passingTests; - AZStd::vector failingTests; - AZStd::vector executionFailureTests; - AZStd::vector timedOutTests; - AZStd::vector unexecutedTests; + AZStd::vector passingTests; + AZStd::vector failingTests; + AZStd::vector executionFailureTests; + AZStd::vector timedOutTests; + AZStd::vector unexecutedTests; for (const auto& testJob : testJobs) { @@ -88,7 +98,7 @@ namespace TestImpact AZStd::chrono::high_resolution_clock::time_point() + AZStd::chrono::duration_cast(testJob.GetStartTime() - startTime); - Client::TestRun clientTestRun( + Client::TestRunBase clientTestRun( testJob.GetTestTarget()->GetName(), testJob.GetCommandString(), relativeStartTime, testJob.GetDuration(), testJob.GetTestResult()); @@ -96,27 +106,27 @@ namespace TestImpact { case Client::TestRunResult::FailedToExecute: { - executionFailureTests.push_back(clientTestRun); + executionFailureTests.emplace_back(AZStd::move(clientTestRun)); break; } case Client::TestRunResult::NotRun: { - unexecutedTests.push_back(clientTestRun); + unexecutedTests.emplace_back(AZStd::move(clientTestRun)); break; } case Client::TestRunResult::Timeout: { - timedOutTests.push_back(clientTestRun); + timedOutTests.emplace_back(AZStd::move(clientTestRun)); break; } case Client::TestRunResult::AllTestsPass: { - passingTests.push_back(clientTestRun); + passingTests.emplace_back(AZStd::move(clientTestRun), GenerateClientTests(testJob)); break; } case Client::TestRunResult::TestFailures: { - failingTests.emplace_back(AZStd::move(clientTestRun), GenerateTestCaseFailures(testJob)); + failingTests.emplace_back(AZStd::move(clientTestRun), GenerateClientTests(testJob)); break; } default: 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 76673d9f40..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/TestImpactClientSequenceReport.h - Include/TestImpactFramework/TestImpactFileUtils.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 @@ -125,5 +128,7 @@ set(FILES Source/TestImpactClientTestRun.cpp Source/TestImpactClientSequenceReport.cpp Source/TestImpactChangeListSerializer.cpp + Source/TestImpactClientSequenceReportSerializer.cpp Source/TestImpactRepoPath.cpp + Source/TestImpactUtils.cpp ) 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/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..d25aafb664 --- /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 timestamp is None: + 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] is not None: + # 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..c368465ecc 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -6,237 +6,299 @@ # # -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 + + # 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 is not None: + 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 self._dst_branch is None 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 is not None: + 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 is not None: + 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 != None: + args.append(f"--ttimeout={test_timeout}") + logger.info(f"Test target timeout is set to {test_timeout} seconds.") + if global_timeout != 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([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..c44232a38e 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_driver.py +++ b/scripts/build/TestImpactAnalysis/tiaf_driver.py @@ -7,60 +7,136 @@ # import argparse +import mars_utils +import sys +import pathlib 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 is not None: + 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}'.") 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..750353651b --- /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 is not None: + 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 From 0005f2b9da7914fcbcac7a4eb799584bac7e81f4 Mon Sep 17 00:00:00 2001 From: AMZN-stankowi <4838196+AMZN-stankowi@users.noreply.github.com> Date: Tue, 10 Aug 2021 06:47:14 -0700 Subject: [PATCH 211/251] Updated skeleton logic: (#2957) Import all nodes as bones. O3DE's concept of a bone is different than AssImp's. Updated GetLocalSpaceBindPoseTransform to only use the offset matrix if the parent is also a bone. Results: All test assets I've tried match Blender's "Rest Position" when loaded in the Character tool. All test animations I've tried work generally as well as they worked before, and a few better. This resolves the issue that was originally opened, an internal test asset loaded the skeleton incorrectly. Signed-off-by: stankowi <4838196+AMZN-stankowi@users.noreply.github.com> --- .../SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp | 4 ---- .../SceneBuilder/Importers/AssImpImporterUtilities.cpp | 7 +------ 2 files changed, 1 insertion(+), 10 deletions(-) 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 81feff7d69..d416324240 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)); From 2bf64879daa2a3210647a3737613c876775ea022 Mon Sep 17 00:00:00 2001 From: John Jones-Steele Date: Tue, 10 Aug 2021 14:52:09 +0100 Subject: [PATCH 212/251] Fixed the SpinBox tests Signed-off-by: John Jones-Steele --- .../AzToolsFramework/Tests/SpinBoxTests.cpp | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) 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 From 2be043ca96ccd08dbd74d114d6ca98158d381f1d Mon Sep 17 00:00:00 2001 From: John Date: Tue, 10 Aug 2021 15:13:19 +0100 Subject: [PATCH 213/251] Fix None comparisons in TIAF scripts. Signed-off-by: John --- scripts/build/TestImpactAnalysis/mars_utils.py | 4 ++-- scripts/build/TestImpactAnalysis/tiaf.py | 14 ++++++++------ scripts/build/TestImpactAnalysis/tiaf_driver.py | 2 +- .../TestImpactAnalysis/tiaf_persistent_storage.py | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/scripts/build/TestImpactAnalysis/mars_utils.py b/scripts/build/TestImpactAnalysis/mars_utils.py index d25aafb664..69374512a3 100644 --- a/scripts/build/TestImpactAnalysis/mars_utils.py +++ b/scripts/build/TestImpactAnalysis/mars_utils.py @@ -100,7 +100,7 @@ class FilebeatClient(object): self._open_socket() def send_event(self, payload, index, timestamp=None, pipeline="filebeat"): - if timestamp is None: + if not timestamp: timestamp = datetime.datetime.utcnow().timestamp() event = { @@ -437,7 +437,7 @@ def transmit_report_to_mars(mars_index_prefix: str, tiaf_result: dict, driver_ar 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] is not None: + 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") diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index c368465ecc..c4d1449dbf 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -49,6 +49,8 @@ class TestImpact: 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"] @@ -72,7 +74,7 @@ class TestImpact: # Check whether or not a previous commit hash exists (no hash is not a failure) self._src_commit = last_commit_hash - if self._src_commit is not None: + 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 @@ -182,7 +184,7 @@ class TestImpact: logger.info(f"Dst branch: '{self._dst_branch}'.") # Source of truth (the branch from which the coverage data will be stored/retrieved from) - if self._dst_branch is None or self._src_branch == self._dst_branch: + 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 @@ -207,7 +209,7 @@ class TestImpact: logger.info("Test impact analysis is enabled.") try: # Persistent storage location - if s3_bucket is not None: + if s3_bucket: persistent_storage = PersistentStorageS3(self._config, suite, s3_bucket, self._source_of_truth_branch) else: persistent_storage = PersistentStorageLocal(self._config, suite) @@ -215,7 +217,7 @@ class TestImpact: logger.warning(f"The persistent storage encountered an irrecoverable error, test impact analysis will be disabled: '{e}'") persistent_storage = None - if persistent_storage is not 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) @@ -278,10 +280,10 @@ class TestImpact: logger.info(f"Test suite is set to '{suite}'.") # Timeouts - if test_timeout != None: + 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 != None: + if global_timeout is not None: args.append(f"--gtimeout={global_timeout}") logger.info(f"Global sequence timeout is set to {test_timeout} seconds.") diff --git a/scripts/build/TestImpactAnalysis/tiaf_driver.py b/scripts/build/TestImpactAnalysis/tiaf_driver.py index c44232a38e..99f9de6eb9 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_driver.py +++ b/scripts/build/TestImpactAnalysis/tiaf_driver.py @@ -129,7 +129,7 @@ if __name__ == "__main__": 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 is not None: + 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) diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py index 750353651b..18ea25091f 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py @@ -104,7 +104,7 @@ class PersistentStorage(ABC): """ historic_data_json = self._pack_historic_data(last_commit_hash) - if historic_data_json is not None: + if historic_data_json: self._store_historic_data(historic_data_json) else: logger.info("The historic data could not be successfully stored.") From e3221224bef798c5a51fd7d24b7f980173ef56a9 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 10 Aug 2021 15:34:27 +0100 Subject: [PATCH 214/251] Add traceback to tiaf exception handler. Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf_driver.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/build/TestImpactAnalysis/tiaf_driver.py b/scripts/build/TestImpactAnalysis/tiaf_driver.py index 99f9de6eb9..5ad16abaa0 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_driver.py +++ b/scripts/build/TestImpactAnalysis/tiaf_driver.py @@ -10,6 +10,7 @@ import argparse import mars_utils import sys import pathlib +import traceback from tiaf import TestImpact from tiaf_logger import get_logger @@ -140,3 +141,4 @@ if __name__ == "__main__": except Exception as e: # Non-gating will be removed from this script and handled at the job level in SPEC-7413 logger.error(f"Exception caught by TIAF driver: '{e}'.") + traceback.print_exc() From 5dbbb93a06b95670e2983f804495d76eb5dfafcb Mon Sep 17 00:00:00 2001 From: John Date: Tue, 10 Aug 2021 15:49:19 +0100 Subject: [PATCH 215/251] Fix path for subprocess Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index c4d1449dbf..3c94c2b5f4 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -290,7 +290,7 @@ class TestImpact: # Run sequence unpacked_args = " ".join(args) logger.info(f"Args: {unpacked_args}") - runtime_result = subprocess.run([self._tiaf_bin] + 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 From 44b053df58e135e087870910514b0dae3d8bbd76 Mon Sep 17 00:00:00 2001 From: SJ Date: Tue, 10 Aug 2021 08:10:37 -0700 Subject: [PATCH 216/251] [Mac] Building and running game projects from an SDK (#2943) * 1. Initial support for loading dylibs outside the bundle. 2. Child processes inherit parent's environment if no environment is explicitly specified(should change to append the parent's environment even if environment variables are explicitly specified). 3. Update some time functions to use system uptime instead of wall clock time when computing elapsed time. This fixes false timeouts when the OS goes to sleep. 4. Increase wait times for AssetBuilders and some Atom tools to connect to the AssetProcessor. This is needed because GateKeeper slows down first time bootup which results in asset processing failures. With this change we'll be able to run Editor and AssetProcessor from an install on Mac and we will also be able to build and run projects using the installed engine as an SDK. Signed-off-by: amzn-sj * 1. Remove debug messages. 2. Fix license 3. Pass parent's environment variables to child processes by default(on Mac). Signed-off-by: amzn-sj * 1. Add more detailed comments.2. Use a custom ly_copy for Mac and leave the default as is. Signed-off-by: amzn-sj * Address some feedback from review Signed-off-by: amzn-sj --- CMakeLists.txt | 2 +- Code/Editor/Platform/Mac/editor_mac.cmake | 24 ++++++ Code/Editor/Platform/Mac/gui_info.plist | 2 +- Code/Editor/Platform/Mac/main_dummy.cpp | 75 +++++++++++++++++++ .../Settings/SettingsRegistryMergeUtils.h | 1 + .../Common/Apple/AzCore/std/time_Apple.cpp | 48 +----------- .../Process/ProcessWatcher_Mac.cpp | 38 ++++------ .../Platform/Mac/assetprocessor_mac.cmake | 24 ++++++ .../Platform/Mac/gui_info.plist | 2 +- .../Platform/Mac/main_dummy.cpp | 75 +++++++++++++++++++ .../native/utilities/BuilderManager.cpp | 2 +- Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp | 2 +- cmake/Platform/Common/Install_common.cmake | 8 +- cmake/Platform/Mac/Install_mac.cmake | 50 +++++++++++++ cmake/Platform/Mac/LYWrappers_mac.cmake | 1 + 15 files changed, 278 insertions(+), 76 deletions(-) create mode 100644 Code/Editor/Platform/Mac/main_dummy.cpp create mode 100644 Code/Tools/AssetProcessor/Platform/Mac/main_dummy.cpp 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/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/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/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/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/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/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/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() From adaeb7c203b2287da0f6cc99ddd201c37b2e6374 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 10 Aug 2021 10:16:14 -0500 Subject: [PATCH 217/251] Converted the AZStd implementations of unintialized construct to use std (#2843) * Converted the AZStd implementations of unintialized construct to use std The uninitialized_default_construct and uninitialized_value_construct functions implementations have been removed and the Standard library implementations have been brought into the AZStd namespace scope Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Added a default construct to the UninitializedValueConstruct test case which value initializes the int member which uses zero initialization to initalize it to zero. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- .../AzCore/AzCore/std/createdestroy.h | 112 ++---------------- .../AzCore/Tests/AZStd/CreateDestroy.cpp | 44 +++++++ 2 files changed, 55 insertions(+), 101 deletions(-) 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/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); + } } From 0953a75a94c59a7bce60cbbe5e2a48397475d35f Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 9 Aug 2021 12:04:57 -0700 Subject: [PATCH 218/251] Replace MCore::SmallArray usage with AZStd::vector Signed-off-by: Chris Burel --- .../CommandSystem/Source/MetaData.cpp | 8 +- .../Source/NodeGroupCommands.cpp | 8 +- .../ExporterLib/Exporter/NodeExport.cpp | 6 +- .../EMotionFX/Code/EMotionFX/Source/Actor.cpp | 87 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Actor.h | 13 +- .../Code/EMotionFX/Source/ActorInstance.cpp | 4 +- .../Code/EMotionFX/Source/NodeGroup.cpp | 37 +- .../Code/EMotionFX/Source/NodeGroup.h | 18 +- .../NodeGroups/NodeGroupManagementWidget.cpp | 16 +- .../Source/NodeGroups/NodeGroupWidget.cpp | 18 +- .../Source/NodeWindow/ActorInfo.cpp | 4 +- .../Source/NodeWindow/NodeGroupInfo.cpp | 4 +- Gems/EMotionFX/Code/MCore/Source/SmallArray.h | 414 ------------------ Gems/EMotionFX/Code/MCore/mcore_files.cmake | 1 - 14 files changed, 103 insertions(+), 535 deletions(-) delete mode 100644 Gems/EMotionFX/Code/MCore/Source/SmallArray.h diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp index 9a0913a5db..f98e88a760 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp @@ -41,15 +41,15 @@ namespace CommandSystem void MetaData::GenerateNodeGroupMetaData(EMotionFX::Actor* actor, AZStd::string& outMetaDataString) { AZStd::string nodeNameList; - const AZ::u32 numNodeGroups = actor->GetNumNodeGroups(); - for (uint32 i = 0; i < numNodeGroups; ++i) + const size_t numNodeGroups = actor->GetNumNodeGroups(); + for (size_t i = 0; i < numNodeGroups; ++i) { EMotionFX::NodeGroup* nodeGroup = actor->GetNodeGroup(i); outMetaDataString += AZStd::string::format("AddNodeGroup -actorID $(ACTORID) -name \"%s\"\n", nodeGroup->GetName()); nodeNameList.clear(); - const AZ::u16 numNodes = nodeGroup->GetNumNodes(); - for (AZ::u16 n = 0; n < numNodes; ++n) + const size_t numNodes = nodeGroup->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { const AZ::u16 nodeIndex = nodeGroup->GetNode(n); EMotionFX::Node* node = actor->GetSkeleton()->GetNode(nodeIndex); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp index c65429ab83..adaa9802d9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp @@ -80,7 +80,7 @@ namespace CommandSystem { if (*m_nodeAction == NodeAction::Replace) { - nodeGroup->GetNodeArray().Clear(); + nodeGroup->GetNodeArray().clear(); } for (const AZStd::string& nodeName : *m_nodeNames) { @@ -146,12 +146,12 @@ namespace CommandSystem if (m_nodeNames.has_value()) { // clear previous nodes - nodeGroup->GetNodeArray().Clear(); - const uint16 numNodes = m_oldNodeGroup->GetNumNodes(); + nodeGroup->GetNodeArray().clear(); + const size_t numNodes = m_oldNodeGroup->GetNumNodes(); nodeGroup->SetNumNodes(numNodes); // add all nodes to the group - for (uint16 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { nodeGroup->SetNode(i, m_oldNodeGroup->GetNode(i)); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp index 91727b2113..d8404cc991 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp @@ -249,7 +249,7 @@ namespace ExporterLib { chunkHeader.m_sizeInBytes += sizeof(EMotionFX::FileFormat::Actor_NodeGroup); chunkHeader.m_sizeInBytes += GetStringChunkSize(nodeGroup->GetNameString()); - chunkHeader.m_sizeInBytes += sizeof(uint16) * nodeGroup->GetNumNodes(); + chunkHeader.m_sizeInBytes += sizeof(uint16) * aznumeric_cast(nodeGroup->GetNumNodes()); } // endian conversion @@ -277,14 +277,14 @@ namespace ExporterLib MCORE_ASSERT(actor); // get the number of node groups - const uint32 numGroups = actor->GetNumNodeGroups(); + const size_t numGroups = actor->GetNumNodeGroups(); // create the node group array and reserve some elements AZStd::vector nodeGroups; nodeGroups.reserve(numGroups); // iterate through the node groups and add them to the array - for (uint32 i = 0; i < numGroups; ++i) + for (size_t i = 0; i < numGroups; ++i) { nodeGroups.emplace_back(actor->GetNodeGroup(i)); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index df039b7186..94a56cc0d5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -142,9 +142,9 @@ namespace EMotionFX result->RecursiveAddDependencies(this); // clone all nodes groups - for (uint32 i = 0; i < m_nodeGroups.GetLength(); ++i) + for (const NodeGroup* nodeGroup : m_nodeGroups) { - result->AddNodeGroup(aznew NodeGroup(*m_nodeGroups[i])); + result->AddNodeGroup(aznew NodeGroup(*nodeGroup)); } // clone the materials @@ -948,12 +948,11 @@ namespace EMotionFX // remove all node groups void Actor::RemoveAllNodeGroups() { - const uint32 numGroups = m_nodeGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + for (NodeGroup*& nodeGroup : m_nodeGroups) { - delete m_nodeGroups[i]; + delete nodeGroup; } - m_nodeGroups.Clear(); + m_nodeGroups.clear(); } @@ -1965,13 +1964,13 @@ namespace EMotionFX } - uint32 Actor::GetNumNodeGroups() const + size_t Actor::GetNumNodeGroups() const { - return m_nodeGroups.GetLength(); + return m_nodeGroups.size(); } - NodeGroup* Actor::GetNodeGroup(uint32 index) const + NodeGroup* Actor::GetNodeGroup(size_t index) const { return m_nodeGroups[index]; } @@ -1979,90 +1978,76 @@ namespace EMotionFX void Actor::AddNodeGroup(NodeGroup* newGroup) { - m_nodeGroups.Add(newGroup); + m_nodeGroups.emplace_back(newGroup); } - void Actor::RemoveNodeGroup(uint32 index, bool delFromMem) + void Actor::RemoveNodeGroup(size_t index, bool delFromMem) { if (delFromMem) { delete m_nodeGroups[index]; } - m_nodeGroups.Remove(index); + m_nodeGroups.erase(AZStd::next(begin(m_nodeGroups), index)); } void Actor::RemoveNodeGroup(NodeGroup* group, bool delFromMem) { - m_nodeGroups.RemoveByValue(group); - if (delFromMem) + const auto found = AZStd::find(begin(m_nodeGroups), end(m_nodeGroups), group); + if (found != end(m_nodeGroups)) { - delete group; + m_nodeGroups.erase(found); + if (delFromMem) + { + delete group; + } } } // find a group index by its name - uint32 Actor::FindNodeGroupIndexByName(const char* groupName) const + size_t Actor::FindNodeGroupIndexByName(const char* groupName) const { - const uint32 numGroups = m_nodeGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + const auto found = AZStd::find_if(begin(m_nodeGroups), end(m_nodeGroups), [groupName](const NodeGroup* nodeGroup) { - if (m_nodeGroups[i]->GetNameString() == groupName) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return nodeGroup->GetNameString() == groupName; + }); + return found != end(m_nodeGroups) ? AZStd::distance(begin(m_nodeGroups), found) : InvalidIndex; } // find a group index by its name, but not case sensitive - uint32 Actor::FindNodeGroupIndexByNameNoCase(const char* groupName) const + size_t Actor::FindNodeGroupIndexByNameNoCase(const char* groupName) const { - const uint32 numGroups = m_nodeGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + const auto found = AZStd::find_if(begin(m_nodeGroups), end(m_nodeGroups), [groupName](const NodeGroup* nodeGroup) { - if (AzFramework::StringFunc::Equal(m_nodeGroups[i]->GetNameString().c_str(), groupName, false /* no case */)) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return AzFramework::StringFunc::Equal(nodeGroup->GetNameString(), groupName, false /* no case */); + }); + return found != end(m_nodeGroups) ? AZStd::distance(begin(m_nodeGroups), found) : InvalidIndex; } // find a group by its name NodeGroup* Actor::FindNodeGroupByName(const char* groupName) const { - const uint32 numGroups = m_nodeGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + const auto found = AZStd::find_if(begin(m_nodeGroups), end(m_nodeGroups), [groupName](const NodeGroup* nodeGroup) { - if (m_nodeGroups[i]->GetNameString() == groupName) - { - return m_nodeGroups[i]; - } - } - return nullptr; + return nodeGroup->GetNameString() == groupName; + }); + return found != end(m_nodeGroups) ? *found : nullptr; } // find a group by its name, but without case sensitivity NodeGroup* Actor::FindNodeGroupByNameNoCase(const char* groupName) const { - const uint32 numGroups = m_nodeGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + const auto found = AZStd::find_if(begin(m_nodeGroups), end(m_nodeGroups), [groupName](const NodeGroup* nodeGroup) { - if (AzFramework::StringFunc::Equal(m_nodeGroups[i]->GetNameString().c_str(), groupName, false /* no case */)) - { - return m_nodeGroups[i]; - } - } - return nullptr; + return AzFramework::StringFunc::Equal(nodeGroup->GetNameString(), groupName, false /* no case */); + }); + return found != end(m_nodeGroups) ? *found : nullptr; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h index 5c4a15e2d8..aa5c5df45c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -23,7 +23,6 @@ // include MCore related files #include #include -#include #include // include required headers @@ -567,13 +566,13 @@ namespace EMotionFX * Get the number of node groups inside this actor object. * @result The number of node groups. */ - uint32 GetNumNodeGroups() const; + size_t GetNumNodeGroups() const; /** * Get a pointer to a given node group. * @param index The node group index, which must be in range of [0..GetNumNodeGroups()-1]. */ - NodeGroup* GetNodeGroup(uint32 index) const; + NodeGroup* GetNodeGroup(size_t index) const; /** * Add a node group. @@ -586,7 +585,7 @@ namespace EMotionFX * @param index The node group number 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 a given node group by its pointer. @@ -601,14 +600,14 @@ namespace EMotionFX * @param groupName The name of the group to search for. This is case sensitive. * @result The group number, or MCORE_INVALIDINDEX32 when it cannot be found. */ - uint32 FindNodeGroupIndexByName(const char* groupName) const; + size_t FindNodeGroupIndexByName(const char* groupName) const; /** * Find a group index by its name, on a non-case sensitive way. * @param groupName The name of the group to search for. This is NOT case sensitive. * @result The group number, or MCORE_INVALIDINDEX32 when it cannot be found. */ - uint32 FindNodeGroupIndexByNameNoCase(const char* groupName) const; + size_t FindNodeGroupIndexByNameNoCase(const char* groupName) const; /** * Find a node group by its name. @@ -925,7 +924,7 @@ namespace EMotionFX 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::vector 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 m_unitType; /**< The unit type used on export. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index 6097784e2f..13927f3fd3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -84,8 +84,8 @@ namespace EMotionFX EnableAllNodes(); // apply actor node group default states (disable groups of nodes that are disabled on default) - const uint32 numGroups = m_actor->GetNumNodeGroups(); - for (uint32 i = 0; i < numGroups; ++i) + const size_t numGroups = m_actor->GetNumNodeGroups(); + for (size_t i = 0; i < numGroups; ++i) { if (m_actor->GetNodeGroup(i)->GetIsEnabledOnDefault() == false) // if this group is disabled on default { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp index 293d64775d..74e59150e0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp @@ -17,7 +17,7 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(NodeGroup, NodeAllocator, 0) - NodeGroup::NodeGroup(const AZStd::string& groupName, uint16 numNodes, bool enabledOnDefault) + NodeGroup::NodeGroup(const AZStd::string& groupName, size_t numNodes, bool enabledOnDefault) : m_name(groupName) , m_nodes(numNodes) , m_enabledOnDefault(enabledOnDefault) @@ -47,28 +47,28 @@ namespace EMotionFX // set the number of nodes - void NodeGroup::SetNumNodes(const uint16 numNodes) + void NodeGroup::SetNumNodes(const size_t numNodes) { - m_nodes.Resize(numNodes); + m_nodes.resize(numNodes); } // get the number of nodes - uint16 NodeGroup::GetNumNodes() const + size_t NodeGroup::GetNumNodes() const { - return static_cast(m_nodes.GetLength()); + return m_nodes.size(); } // set a given node to a given node number - void NodeGroup::SetNode(uint16 index, uint16 nodeIndex) + void NodeGroup::SetNode(size_t index, uint16 nodeIndex) { m_nodes[index] = nodeIndex; } // get the node number of a given index - uint16 NodeGroup::GetNode(uint16 index) const + uint16 NodeGroup::GetNode(size_t index) const { return m_nodes[index]; } @@ -77,10 +77,9 @@ namespace EMotionFX // enable all nodes in the group inside a given actor instance void NodeGroup::EnableNodes(ActorInstance* targetActorInstance) { - const uint16 numNodes = static_cast(m_nodes.GetLength()); - for (uint16 i = 0; i < numNodes; ++i) + for (uint16 node : m_nodes) { - targetActorInstance->EnableNode(m_nodes[i]); + targetActorInstance->EnableNode(node); } } @@ -88,10 +87,9 @@ namespace EMotionFX // disable all nodes in the group inside a given actor instance void NodeGroup::DisableNodes(ActorInstance* targetActorInstance) { - const uint16 numNodes = static_cast(m_nodes.GetLength()); - for (uint16 i = 0; i < numNodes; ++i) + for (uint16 node : m_nodes) { - targetActorInstance->DisableNode(m_nodes[i]); + targetActorInstance->DisableNode(node); } } @@ -99,26 +97,29 @@ namespace EMotionFX // add a given node to the group (performs a realloc internally) void NodeGroup::AddNode(uint16 nodeIndex) { - m_nodes.Add(nodeIndex); + m_nodes.emplace_back(nodeIndex); } // remove a given node by its node number void NodeGroup::RemoveNodeByNodeIndex(uint16 nodeIndex) { - m_nodes.RemoveByValue(nodeIndex); + if (const auto found = AZStd::find(begin(m_nodes), end(m_nodes), nodeIndex); found) + { + m_nodes.erase(found); + } } // remove a given array element from the list of nodes - void NodeGroup::RemoveNodeByGroupIndex(uint16 index) + void NodeGroup::RemoveNodeByGroupIndex(size_t index) { - m_nodes.Remove(index); + m_nodes.erase(AZStd::next(begin(m_nodes), index)); } // get the node array directly - MCore::SmallArray& NodeGroup::GetNodeArray() + AZStd::vector& NodeGroup::GetNodeArray() { return m_nodes; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h index 7ee74415c0..02dc7d70a9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h @@ -11,8 +11,8 @@ // include required files #include "EMotionFXConfig.h" #include "BaseObject.h" -#include #include +#include namespace EMotionFX @@ -34,7 +34,7 @@ namespace EMotionFX public: AZ_CLASS_ALLOCATOR_DECL - NodeGroup(const AZStd::string& groupName = {}, uint16 numNodes = 0, bool enabledOnDefault = true); + NodeGroup(const AZStd::string& groupName = {}, size_t numNodes = 0, bool enabledOnDefault = true); NodeGroup(const NodeGroup& aOther); NodeGroup& operator=(const NodeGroup& aOther); @@ -61,13 +61,13 @@ namespace EMotionFX * This will resize the array of node indices. Don't forget to initialize the node values after increasing the number of nodes though. * @param numNodes The number of nodes that are inside this group. */ - void SetNumNodes(const uint16 numNodes); + void SetNumNodes(size_t numNodes); /** * Get the number of nodes that remain inside this group. * @result The number of nodes inside this group. */ - uint16 GetNumNodes() const; + size_t GetNumNodes() const; /** * Set the value of a given node. @@ -75,14 +75,14 @@ namespace EMotionFX * @param nodeIndex The value for the given node. This is the node index which points inside the Actor object where this group will belong to. * To get access to the actual node object use Actor::GetNode( nodeIndex ). */ - void SetNode(uint16 index, uint16 nodeIndex); + void SetNode(size_t index, uint16 nodeIndex); /** * Get the node index 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 number, which points inside the Actor object. Use Actor::GetNode( returnValue ) to get access to the node information. */ - uint16 GetNode(uint16 index) const; + uint16 GetNode(size_t index) const; /** * Enable all nodes that remain inside this group, for a given actor instance. @@ -127,13 +127,13 @@ 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(uint16 index); + void RemoveNodeByGroupIndex(size_t index); /** * Get direct access to the array of node indices that are part of this group. * @result A reference to the array of nodes inside this group. Please use this with care. */ - MCore::SmallArray& GetNodeArray(); + AZStd::vector& GetNodeArray(); /** * Check whether this group is enabled after actor instance creation time. @@ -155,7 +155,7 @@ namespace EMotionFX private: AZStd::string m_name; /**< The name of the group. */ - MCore::SmallArray m_nodes; /**< The node index numbers that are inside this group. */ + AZStd::vector 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/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp index 67aee6a5af..bd5a93a0ae 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 @@ -262,11 +262,11 @@ namespace EMStudio m_clearButton->setDisabled(disableButtons); // set the row count - m_nodeGroupsTable->setRowCount(m_actor->GetNumNodeGroups()); + m_nodeGroupsTable->setRowCount(aznumeric_caster(m_actor->GetNumNodeGroups())); // fill the table with the existing node groups - const uint32 numNodeGroups = m_actor->GetNumNodeGroups(); - for (uint32 i = 0; i < numNodeGroups; ++i) + const size_t numNodeGroups = m_actor->GetNumNodeGroups(); + for (size_t i = 0; i < numNodeGroups; ++i) { // get the nodegroup EMotionFX::NodeGroup* nodeGroup = m_actor->GetNodeGroup(i); @@ -287,16 +287,16 @@ namespace EMStudio // create table items QTableWidgetItem* tableItemGroupName = new QTableWidgetItem(nodeGroup->GetName()); - AZStd::string numGroupString = AZStd::string::format("%i", nodeGroup->GetNumNodes()); + AZStd::string numGroupString = AZStd::string::format("%zu", nodeGroup->GetNumNodes()); QTableWidgetItem* tableItemNumNodes = new QTableWidgetItem(numGroupString.c_str()); // add items to the table - m_nodeGroupsTable->setCellWidget(i, 0, checkbox); - m_nodeGroupsTable->setItem(i, 1, tableItemGroupName); - m_nodeGroupsTable->setItem(i, 2, tableItemNumNodes); + m_nodeGroupsTable->setCellWidget(aznumeric_caster(i), 0, checkbox); + m_nodeGroupsTable->setItem(aznumeric_caster(i), 1, tableItemGroupName); + m_nodeGroupsTable->setItem(aznumeric_caster(i), 2, tableItemNumNodes); // set the row height - m_nodeGroupsTable->setRowHeight(i, 21); + m_nodeGroupsTable->setRowHeight(aznumeric_caster(i), 21); } // set the old selected row if any one 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 7ce09a55d7..8a20070505 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 @@ -150,17 +150,17 @@ namespace EMStudio m_removeNodesButton->setEnabled((m_nodeTable->rowCount() != 0) && (m_nodeTable->selectedItems().size() != 0)); // clear the table widget - m_nodeTable->setRowCount(m_nodeGroup->GetNumNodes()); + m_nodeTable->setRowCount(aznumeric_caster(m_nodeGroup->GetNumNodes())); // set header items for the table - AZStd::string headerText = AZStd::string::format("%s Nodes (%i / %zu)", ((m_nodeGroup->GetIsEnabledOnDefault()) ? "Enabled" : "Disabled"), m_nodeGroup->GetNumNodes(), m_actor->GetNumNodes()); + AZStd::string headerText = AZStd::string::format("%s Nodes (%zu / %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); m_nodeTable->setHorizontalHeaderItem(0, nameHeaderItem); // fill the table with content - const uint16 numNodes = m_nodeGroup->GetNumNodes(); - for (uint16 i = 0; i < numNodes; ++i) + const size_t numNodes = m_nodeGroup->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // get the nodegroup EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(m_nodeGroup->GetNode(i)); @@ -173,10 +173,10 @@ namespace EMStudio // create table items QTableWidgetItem* tableItemNodeName = new QTableWidgetItem(node->GetName()); - m_nodeTable->setItem(i, 0, tableItemNodeName); + m_nodeTable->setItem(aznumeric_caster(i), 0, tableItemNodeName); // set the row height - m_nodeTable->setRowHeight(i, 21); + m_nodeTable->setRowHeight(aznumeric_caster(i), 21); } // resize to contents and adjust header @@ -257,11 +257,9 @@ namespace EMStudio m_nodeSelectionList.Clear(); if (senderWidget == m_selectNodesButton) { - MCore::SmallArray& nodes = m_nodeGroup->GetNodeArray(); - const uint16 numNodes = nodes.GetLength(); - for (uint16 i = 0; i < numNodes; ++i) + for (const uint16 i : m_nodeGroup->GetNodeArray()) { - EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(nodes[i]); + EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(i); m_nodeSelectionList.AddNode(node); } } 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 6bd00a2b94..9936410231 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 @@ -32,9 +32,9 @@ namespace EMStudio m_nodeCount = actor->GetNumNodes(); // node groups - const uint32 numNodeGroups = actor->GetNumNodeGroups(); + const size_t numNodeGroups = actor->GetNumNodeGroups(); m_nodeGroups.reserve(numNodeGroups); - for (uint32 i = 0; i < numNodeGroups; ++i) + for (size_t i = 0; i < numNodeGroups; ++i) { m_nodeGroups.emplace_back(actor, actor->GetNodeGroup(i)); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp index 07a31f4402..f25158ae0d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp @@ -23,8 +23,8 @@ namespace EMStudio m_name = nodeGroup->GetNameString(); // iterate over the nodes inside the node group - const uint32 numGroupNodes = nodeGroup->GetNumNodes(); - for (uint32 j = 0; j < numGroupNodes; ++j) + const size_t numGroupNodes = nodeGroup->GetNumNodes(); + for (size_t j = 0; j < numGroupNodes; ++j) { const uint16 nodeIndex = nodeGroup->GetNode(j); const EMotionFX::Node* node = actor->GetSkeleton()->GetNode(nodeIndex); diff --git a/Gems/EMotionFX/Code/MCore/Source/SmallArray.h b/Gems/EMotionFX/Code/MCore/Source/SmallArray.h deleted file mode 100644 index ab94cabbfe..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/SmallArray.h +++ /dev/null @@ -1,414 +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" - - -namespace MCore -{ - -/** - * Dynamic array template with a maximum of 65536 items. - * It also doesn't store a memory category and maximum number of elements like the MCore::Array template. - */ -template -class SmallArray -{ - 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 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) : m_length(num) { m_data = (T*)MCore::Allocate(m_length * 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) : m_data(nullptr), m_length(0) { *this = other; } - - /** - * Move constructor. - * @param other The array to move the data from. - */ - 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. - * However, if you store pointers to objects, these objects won't be deleted.
- * Example:
- *
-         * SmallArray< 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
-         */
-        ~SmallArray()                                                            { for (uint32 i=0; i); 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)                    { 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(++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=m_length; Grow(m_length+a.m_length); for (uint32 i=0; i 0) Remove((uint32)0); }
-
-        /**
-         * Remove the last array element.
-         */
-        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(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(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, 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
-         * 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 != 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. - * @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= newLength) return; uint32 oldLen=m_length; Grow(newLength); for (uint32 i=oldLen; i 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=m_length-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 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) - { - // check for growing or shrinking array - if (newLength > m_length) - { - // growing array, construct empty elements at end of array - uint32 oldLen = m_length; - GrowExact(newLength); - if (m_data == nullptr) - { - return false; - } - for (uint32 i=oldLen; i 0) - MCore::MemMove(m_data+destIndex, m_data+sourceIndex, numElements * sizeof(T)); - } - - // operators - bool operator==(const SmallArray& 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 (m_data) - m_data = (T*)MCore::Realloc(m_data, newSize * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - else - m_data = (T*)MCore::Allocate(newSize * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - } - 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 - (m_data+index)->~T(); - } // destruct an element at - - // partition part of array (for sorting) - int32 Partition(int32 left, int32 right, CmpFunc cmp) - { - ::MCore::Swap(m_data[left], m_data[ (left+right)>>1 ]); - - 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(m_data[++i], target) >= 0) break; } - while (j > i) { if (cmp(m_data[--j], target) <= 0) break; } - if (i >= j) break; - ::MCore::Swap(m_data[i], m_data[j]); - } - - ::MCore::Swap(m_data[i], m_data[right]); - return i; - } -}; - -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index 47b35e004b..8b57d0b7f3 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -106,7 +106,6 @@ set(FILES Source/StaticAllocator.cpp Source/StaticAllocator.h Source/StaticString.h - Source/SmallArray.h Source/StandardHeaders.h Source/Stream.h Source/StringConversions.cpp From 7c5120b72fadb51ebee07a408e3f62e6b7a63679 Mon Sep 17 00:00:00 2001 From: Jacob Hilliard <64656371+jcbhl@users.noreply.github.com> Date: Tue, 10 Aug 2021 09:57:04 -0700 Subject: [PATCH 219/251] [ATOM-16021] Initial continuous capture support (#2624) * Profiler: Implement continuous capture internals Signed-off-by: Jacob Hilliard * Profiler: extend ProfileCaptureSystemComponent Implements dumping of saved CPU profiling data to a local file, blocking call. Signed-off-by: Jacob Hilliard * Profiler: Working IO thread for serialization Signed-off-by: Jacob Hilliard * Profiler: switch to AZ::JobFunction for IO Signed-off-by: Jacob Hilliard * Profiler: move to a ring buffer for storage Signed-off-by: Jacob Hilliard * Profiler: switch back to IO thread Signed-off-by: Jacob Hilliard * Profiler: add TODO Signed-off-by: Jacob Hilliard * Profiler: correct thread safety issues Signed-off-by: Jacob Hilliard --- .../Atom/Feature/Utils/ProfilingCaptureBus.h | 8 +- .../ProfilingCaptureSystemComponent.cpp | 160 ++++++++++++------ .../Source/ProfilingCaptureSystemComponent.h | 8 + .../RHI/Code/Include/Atom/RHI/CpuProfiler.h | 9 + .../Code/Include/Atom/RHI/CpuProfilerImpl.h | 23 ++- .../RHI/Code/Source/RHI/CpuProfilerImpl.cpp | 63 ++++++- .../Include/Atom/Utils/ImGuiCpuProfiler.inl | 28 +++ 7 files changed, 240 insertions(+), 59 deletions(-) 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 03f522ba44..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 @@ -28,9 +28,15 @@ namespace AZ //! 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; }; diff --git a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp index 1e2d549e7a..add6d0e098 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp @@ -25,6 +25,7 @@ #include #include #include +#include namespace AZ { @@ -157,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; }; @@ -327,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()); + } } } } @@ -359,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) @@ -383,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) ; } } @@ -474,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) @@ -641,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 @@ -652,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); + }); + + // Start the TickBus. + if (captureStarted) + { + TickBus::Handler::BusConnect(); + } - // Get time Cpu profiled time regions - const RHI::CpuProfiler::TimeRegionMap& timeRegionMap = RHI::CpuProfiler::Get()->GetTimeRegionMap(); + return captureStarted; + } - CpuProfilingStatisticsSerializer serializer(timeRegionMap); - const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer, - outputFilePath, (CpuProfilingStatisticsSerializer*)nullptr, &serializationSettings); + bool ProfilingCaptureSystemComponent::BeginContinuousCpuProfilingCapture() + { + return AZ::RHI::CpuProfiler::Get()->BeginContinuousCapture(); + } - 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::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) diff --git a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h index c401d27f30..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 { @@ -71,6 +72,8 @@ namespace AZ 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: @@ -86,6 +89,11 @@ namespace AZ 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/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/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(); From 43ae25b49b40b888d2e99d8d570e4fd23c0fdb13 Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Tue, 10 Aug 2021 10:00:42 -0700 Subject: [PATCH 220/251] fixed compiler loss of precision warning Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index 2e61542c36..4da5560908 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -172,7 +172,7 @@ namespace AZ if (viewDrawList.size() > 0 && drawLists.size() == 0) { m_drawListView = viewDrawList; - m_drawItemCount += viewDrawList.size(); + m_drawItemCount += (u32)viewDrawList.size(); PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); return; } @@ -183,7 +183,7 @@ namespace AZ // combine draw items from mutiple draw lists to one draw list and sort it. for (auto drawList : drawLists) { - m_drawItemCount += drawList.size(); + m_drawItemCount += (u32)drawList.size(); } PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); m_combinedDrawList.resize(m_drawItemCount); From e3b22f51b2f210ff67e8d21d9bbcffb567406745 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 10:50:24 -0700 Subject: [PATCH 221/251] @lumberyard-employee-dm suggestion to use (w)string_view as the src to simplify functions in conversions.h Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/CryEdit.cpp | 2 +- .../AzCore/AzCore/std/string/conversions.h | 154 +++++------------- .../Keyboard/InputDeviceKeyboard_WinAPI.h | 4 +- .../Keyboard/InputDeviceKeyboard_Windows.cpp | 2 +- Code/Legacy/CrySystem/SystemWin32.cpp | 2 +- Code/Legacy/CrySystem/XConsole.cpp | 2 +- .../Support/include/CrashSupport.h | 2 +- Code/Tools/GridHub/GridHub/main.cpp | 6 +- .../RHI/DX12/Code/Source/RHI/MemoryView.cpp | 2 +- .../Source/RHI/RayTracingPipelineState.cpp | 6 +- .../Code/Source/RHI/RayTracingShaderTable.cpp | 2 +- .../AtomFont/Code/Source/FFont.cpp | 2 +- .../Code/Source/UiTextInputComponent.cpp | 2 +- 13 files changed, 56 insertions(+), 132 deletions(-) diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 408de7be2c..0fc283c5c3 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -3225,7 +3225,7 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled) #ifdef WIN32 wchar_t windowsErrorMessageW[ERROR_LEN]; - windowsErrorMessageW = L'\0'; + windowsErrorMessageW[0] = L'\0'; FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, dw, diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index c5c9b29cdb..40378467db 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -32,79 +32,79 @@ namespace AZStd { static_assert(Size == size_t{ 2 } || Size == size_t{ 4 }, "only wchar_t types of size 2 or 4 can be converted to utf8"); - template - static inline void to_string(AZStd::basic_string& dest, const wchar_t* first, const wchar_t* last) + template + static inline void to_string(AZStd::basic_string& dest, AZStd::wstring_view src) { if constexpr (Size == 2) { - Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf16to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } else if constexpr (Size == 4) { - Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf32to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } } template - static inline void to_string(AZStd::basic_fixed_string& dest, const wchar_t* first, const wchar_t* last) + static inline void to_string(AZStd::basic_fixed_string& dest, AZStd::wstring_view src) { if constexpr (Size == 2) { - Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf16to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } else if constexpr (Size == 4) { - Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf32to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } } - static inline char* to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last) + static inline char* to_string(char* dest, size_t destSize, AZStd::wstring_view src) { if constexpr (Size == 2) { - return Utf8::Unchecked::utf16to8(first, last, dest, destSize); + return Utf8::Unchecked::utf16to8(src.begin(), src.end(), dest, destSize); } else if constexpr (Size == 4) { - return Utf8::Unchecked::utf32to8(first, last, dest, destSize); + return Utf8::Unchecked::utf32to8(src.begin(), src.end(), dest, destSize); } } - template - static inline void to_wstring(AZStd::basic_string& dest, const char* first, const char* last) + template + static inline void to_wstring(AZStd::basic_string& dest, AZStd::string_view src) { if constexpr (Size == 2) { - Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf8to16(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } else if constexpr (Size == 4) { - Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf8to32(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } } template - static inline void to_wstring(AZStd::basic_fixed_string& dest, const char* first, const char* last) + static inline void to_wstring(AZStd::basic_fixed_string& dest, AZStd::string_view src) { if constexpr (Size == 2) { - Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf8to16(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } else if constexpr (Size == 4) { - Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size()); + Utf8::Unchecked::utf8to32(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size()); } } - static inline wchar_t* to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last) + static inline wchar_t* to_wstring(wchar_t* dest, size_t destSize, AZStd::string_view src) { if constexpr (Size == 2) { - return Utf8::Unchecked::utf8to16(first, last, dest, destSize); + return Utf8::Unchecked::utf8to16(src.begin(), src.end(), dest, destSize); } else if constexpr (Size == 4) { - return Utf8::Unchecked::utf8to32(first, last, dest, destSize); + return Utf8::Unchecked::utf8to32(src.begin(), src.end(), dest, destSize); } } }; @@ -284,64 +284,26 @@ namespace AZStd inline AZStd::string to_string(long double val) { AZStd::string str; to_string(str, val); return str; } // In our engine we assume AZStd::string is Utf8 encoded! - template - void to_string(AZStd::basic_string& dest, const wchar_t* str, size_t srcLen = 0) + template + void to_string(AZStd::basic_string& dest, AZStd::wstring_view src) { dest.clear(); - - if (srcLen == 0) - { - srcLen = wcslen(str); - } - - if (srcLen > 0) - { - Internal::WCharTPlatformConverter<>::to_string(dest, str, str + srcLen); - } - } - - template - void to_string(AZStd::basic_string& dest, const AZStd::basic_string& src) - { - return to_string(dest, src.c_str(), src.length()); + Internal::WCharTPlatformConverter<>::to_string(dest, src); } template - void to_string(AZStd::basic_fixed_string& dest, const wchar_t* str, size_t srcLen = 0) + void to_string(AZStd::basic_fixed_string& dest, AZStd::wstring_view src) { dest.clear(); - - if (srcLen == 0) - { - srcLen = wcslen(str); - } - - if (srcLen > 0) - { - Internal::WCharTPlatformConverter<>::to_string(dest, str, str + srcLen); - } - } - - template - void to_string(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src) - { - return to_string(dest, src.c_str(), src.length()); + Internal::WCharTPlatformConverter<>::to_string(dest, src); } - inline void to_string(char* dest, size_t destSize, const wchar_t* str, size_t srcLen = 0) + inline void to_string(char* dest, size_t destSize, AZStd::wstring_view src) { - if (srcLen == 0) + char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, src); + if (endStr < (dest + destSize)) { - srcLen = wcslen(str); - } - - if (srcLen > 0) - { - char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen); - if (endStr < (dest + destSize)) - { - *endStr = '\0'; // null terminator - } + *endStr = '\0'; // null terminator } } @@ -441,64 +403,26 @@ namespace AZStd inline AZStd::wstring to_wstring(unsigned long long val) { AZStd::wstring wstr; to_wstring(wstr, val); return wstr; } inline AZStd::wstring to_wstring(long double val) { AZStd::wstring wstr; to_wstring(wstr, val); return wstr; } - template - void to_wstring(AZStd::basic_string& dest, const char* str, size_t strLen = 0) + template + void to_wstring(AZStd::basic_string& dest, AZStd::string_view src) { dest.clear(); - - if (strLen == 0) - { - strLen = strlen(str); - } - - if (strLen > 0) - { - Internal::WCharTPlatformConverter<>::to_wstring(dest, str, str + strLen); - } + Internal::WCharTPlatformConverter<>::to_wstring(dest, src); } - template - void to_wstring(AZStd::basic_string& dest, const AZStd::basic_string& src) - { - return to_wstring(dest, src.c_str(), src.length()); - } - - template - void to_wstring(AZStd::basic_fixed_string& dest, const char* str, size_t strLen = 0) + template + void to_wstring(AZStd::basic_fixed_string& dest, AZStd::string_view src) { dest.clear(); - - if (strLen == 0) - { - strLen = strlen(str); - } - - if (strLen > 0) - { - Internal::WCharTPlatformConverter<>::to_wstring(dest, str, str + strLen); - } - } - - template - void to_wstring(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src) - { - return to_wstring(dest, src.c_str(), src.length()); + Internal::WCharTPlatformConverter<>::to_wstring(dest, src); } - inline void to_wstring(wchar_t* dest, size_t destSize, const char* str, size_t srcLen = 0) + inline void to_wstring(wchar_t* dest, size_t destSize, AZStd::string_view src) { - if (srcLen == 0) - { - srcLen = strlen(str); - } - - if (srcLen > 0) + wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, src); + if (endWStr < (dest + destSize)) { - wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen); - if (endWStr < (dest + destSize)) - { - *endWStr = '\0'; // null terminator - } + *endWStr = '\0'; // null terminator } } diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h index 591f8421b9..4c90b83bc4 100644 --- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h +++ b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h @@ -59,7 +59,7 @@ namespace AzFramework { // Convert the valid UTF-16 surrogate pair to a UTF-8 code point const wchar_t codePointUTF16[2] = { m_leadSurrogate, codeUnitUTF16 }; - AZStd::to_string(codePointUTF8, codePointUTF16, 2); + AZStd::to_string(codePointUTF8, { codePointUTF16, 2 }); m_leadSurrogate = 0; } else @@ -72,7 +72,7 @@ namespace AzFramework { // Convert the standalone UTF-16 code point to a UTF-8 code point const wchar_t codePointUTF16[1] = { codeUnitUTF16 }; - AZStd::to_string(codePointUTF8, codePointUTF16, 1); + AZStd::to_string(codePointUTF8, { codePointUTF16, 1 }); m_leadSurrogate = 0; } 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 78364fbd0d..f3112ab89c 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 @@ -253,7 +253,7 @@ namespace AzFramework if (stringLength != 0) { // Convert UTF-16 to UTF-8 - AZStd::to_string(o_keyOrButtonText, buffer, stringLength); + AZStd::to_string(o_keyOrButtonText, { buffer, aznumeric_cast(stringLength) }); } } diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index b114c9bf12..da8e966b0a 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -126,7 +126,7 @@ const char* CSystem::GetUserName() DWORD dwSize = iNameBufferSize; wchar_t nameW[iNameBufferSize]; ::GetUserNameW(nameW, &dwSize); - AZStd::to_string(szNameBuffer, iNameBufferSize, nameW, dwSize); + AZStd::to_string(szNameBuffer, iNameBufferSize, { nameW, dwSize }); return szNameBuffer; #else #if defined(LINUX) diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index 8e598c481d..ae07f86312 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -2861,7 +2861,7 @@ void CXConsole::Paste() { // Convert UCS code-point into UTF-8 string AZStd::fixed_string<5> utf8_buf = {0}; - AZStd::to_string(utf8_buf.data(), 5, &cp, 1); + AZStd::to_string(utf8_buf.data(), 5, { &cp, 1 }); AddInputUTF8(utf8_buf.c_str()); } } diff --git a/Code/Tools/CrashHandler/Support/include/CrashSupport.h b/Code/Tools/CrashHandler/Support/include/CrashSupport.h index 1393930913..e0bec5818b 100644 --- a/Code/Tools/CrashHandler/Support/include/CrashSupport.h +++ b/Code/Tools/CrashHandler/Support/include/CrashSupport.h @@ -41,7 +41,7 @@ namespace CrashHandler std::string returnPath; GetExecutablePath(returnPath); wchar_t currentFileNameW[CRASH_HANDLER_MAX_PATH_LEN] = { 0 }; - AZStd::to_wstring(currentFileNameW, CRASH_HANDLER_MAX_PATH_LEN, returnPath.c_str(), returnPath.size()); + AZStd::to_wstring(currentFileNameW, CRASH_HANDLER_MAX_PATH_LEN, { returnPath.c_str(), returnPath.size() }); returnPathW = currentFileNameW; } diff --git a/Code/Tools/GridHub/GridHub/main.cpp b/Code/Tools/GridHub/GridHub/main.cpp index 670367bf06..bfb82efd0d 100644 --- a/Code/Tools/GridHub/GridHub/main.cpp +++ b/Code/Tools/GridHub/GridHub/main.cpp @@ -408,7 +408,7 @@ GridHubApplication::Create(const Descriptor& descriptor, const StartupParameters if (AZ::Utils::GetExecutablePath(originalExeFileName, AZ_ARRAY_SIZE(originalExeFileName)).m_pathStored == AZ::Utils::ExecutablePathResult::Success) { wchar_t originalExeFileNameW[MAX_PATH]; - AZStd::to_wstring(originalExeFileNameW, MAX_PATH, originalExeFileName, MAX_PATH); + AZStd::to_wstring(originalExeFileNameW, MAX_PATH, originalExeFileName); PathRemoveFileSpec(originalExeFileNameW); PathAppend(originalExeFileNameW, GRIDHUB_IMAGE_NAME); @@ -489,7 +489,7 @@ void CopyAndRun(bool failSilently) if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success) { wchar_t myFileNameW[MAX_PATH] = { 0 }; - AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH); + AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName); wchar_t sourceProcPath[MAX_PATH] = { 0 }; wchar_t targetProcPath[MAX_PATH] = { 0 }; wchar_t procDrive[MAX_PATH] = { 0 }; @@ -567,7 +567,7 @@ void RelaunchImage() if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success) { wchar_t myFileNameW[MAX_PATH] = { 0 }; - AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH); + AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName); wchar_t targetProcPath[MAX_PATH] = { 0 }; wchar_t procDrive[MAX_PATH] = { 0 }; wchar_t procDir[MAX_PATH] = { 0 }; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp index 1246fb5b1a..c9d932afb1 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp @@ -94,7 +94,7 @@ namespace AZ if (m_memoryAllocation.m_memory) { AZStd::wstring wname; - AZStd::to_wstring(wname, name.data(), name.size()); + AZStd::to_wstring(wname, name); m_memoryAllocation.m_memory->SetName(wname.data()); } } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp index aebf705790..be0c084d95 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp @@ -84,15 +84,15 @@ namespace AZ for (const RHI::RayTracingHitGroup& hitGroup : descriptor->GetHitGroups()) { AZStd::wstring hitGroupNameWstring; - AZStd::to_wstring(hitGroupNameWstring, hitGroup.m_hitGroupName.GetStringView().data(), hitGroup.m_hitGroupName.GetStringView().size()); + AZStd::to_wstring(hitGroupNameWstring, hitGroup.m_hitGroupName.GetStringView()); hitGroupNameWstrings.push_back(hitGroupNameWstring); AZStd::wstring closestHitShaderNameWstring; - AZStd::to_wstring(closestHitShaderNameWstring, hitGroup.m_closestHitShaderName.GetStringView().data(), hitGroup.m_closestHitShaderName.GetStringView().size()); + AZStd::to_wstring(closestHitShaderNameWstring, hitGroup.m_closestHitShaderName.GetStringView()); closestHitShaderNameWstrings.push_back(closestHitShaderNameWstring); AZStd::wstring anyHitShaderNameWstring; - AZStd::to_wstring(anyHitShaderNameWstring, hitGroup.m_anyHitShaderName.GetStringView().data(), hitGroup.m_anyHitShaderName.GetStringView().size()); + AZStd::to_wstring(anyHitShaderNameWstring, hitGroup.m_anyHitShaderName.GetStringView()); anyHitShaderNameWstrings.push_back(anyHitShaderNameWstring); D3D12_HIT_GROUP_DESC hitGroupDesc = {}; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp index eefb1a28aa..21e7dbc82e 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp @@ -85,7 +85,7 @@ namespace AZ uint8_t* nextRecord = RHI::AlignUp(mappedData + shaderRecordSize, D3D12_RAYTRACING_SHADER_RECORD_BYTE_ALIGNMENT); AZStd::wstring shaderExportNameWstring; - AZStd::to_wstring(shaderExportNameWstring, record.m_shaderExportName.GetStringView().data(), record.m_shaderExportName.GetStringView().size()); + AZStd::to_wstring(shaderExportNameWstring, record.m_shaderExportName.GetStringView()); void* shaderIdentifier = stateObjectProperties->GetShaderIdentifier(shaderExportNameWstring.c_str()); memcpy(mappedData, shaderIdentifier, D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES); mappedData += D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index fd59b7aed4..9317cae846 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -1236,7 +1236,7 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str, // get char width and sum it to the line width // Note: This is not unicode compatible, since char-width depends on surrounding context (ie, combining diacritics etc) char codepoint[5]; - AZStd::to_string(codepoint, 5, (wchar_t*)&ch, 1); + AZStd::to_string(codepoint, 5, { (wchar_t*)&ch, 1 }); curCharWidth = GetTextSize(codepoint, true, ctx).x; // keep track of spaces diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp index 0c61116945..0d9fc09063 100644 --- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp @@ -1186,7 +1186,7 @@ void UiTextInputComponent::UpdateDisplayedTextFunction() // work for cases tested but may not in general. wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 }; AZStd::string replacementCharString; - AZStd::to_string(replacementCharString, wcharString, 1); + AZStd::to_string(replacementCharString, { wcharString, 1 }); int numReplacementChars = LyShine::GetUtf8StringLength(originalText); From 3b9044ce5d583114b15aaa5049ffbbf5191411bd Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 11:31:16 -0700 Subject: [PATCH 222/251] Addressing missing test identified by @hultonha Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../AzCore/AzCore/std/string/conversions.h | 17 +++++++++++++++++ .../Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp | 2 +- Code/Framework/AzCore/Tests/AZStd/String.cpp | 6 ++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index 40378467db..b7887339e2 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -70,6 +70,18 @@ namespace AZStd } } + static inline size_t to_string_length(AZStd::wstring_view src) + { + if constexpr (Size == 2) + { + return Utf8::Unchecked::utf16ToUtf8BytesRequired(src.begin(), src.end()); + } + else if constexpr (Size == 4) + { + return Utf8::Unchecked::utf32ToUtf8BytesRequired(src.begin(), src.end()); + } + } + template static inline void to_wstring(AZStd::basic_string& dest, AZStd::string_view src) { @@ -307,6 +319,11 @@ namespace AZStd } } + inline size_t to_string_length(AZStd::wstring_view src) + { + return Internal::WCharTPlatformConverter<>::to_string_length(src); + } + template int stoi(const AZStd::basic_string& str, AZStd::size_t* idx = 0, int base = 10) { diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp index 4d8c9c8cfc..bcba24b768 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp @@ -43,7 +43,7 @@ namespace AZ } else { - size_t utf8PathSize = Utf8::Unchecked::utf16ToUtf8BytesRequired(pathBufferW, pathBufferW + pathLen); + size_t utf8PathSize = AZStd::to_string_length({ pathBufferW, pathLen }); if (utf8PathSize >= exeStorageSize) { result.m_pathStored = ExecutablePathResult::BufferSizeNotLargeEnough; diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index 309f561a75..9dae4a3d3f 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -674,6 +674,7 @@ namespace UnitTest string str1; to_string(str1, wstr); AZ_TEST_ASSERT(str1 == "BlaBla 5"); + EXPECT_EQ(8, to_string_length(wstr)); str1 = string::format("%ls", wstr.c_str()); AZ_TEST_ASSERT(str1 == "BlaBla 5"); @@ -690,6 +691,11 @@ namespace UnitTest char strBuffer[9]; to_string(strBuffer, 9, wstr1.c_str()); AZ_TEST_ASSERT(0 == azstricmp(strBuffer, "BLABLA 5")); + EXPECT_EQ(8, to_string_length(wstr1)); + + // wstring to char with unicode + wstring ws1InfinityEscaped = L"Infinity: \u221E"; // escaped + EXPECT_EQ(13, to_string_length(ws1InfinityEscaped)); // wchar_t buffer to char buffer wchar_t wstrBuffer[9] = L"BLABLA 5"; From e6259882b87d1096523c4167862b05ecfa5788cb Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Tue, 10 Aug 2021 09:58:11 -0700 Subject: [PATCH 223/251] Replace `MCore::AlignedArray` with `AZStd::vector` Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp | 159 ++-- Gems/EMotionFX/Code/EMotionFX/Source/Pose.h | 18 +- .../Code/MCore/Source/AlignedArray.h | 783 ------------------ Gems/EMotionFX/Code/MCore/mcore_files.cmake | 1 - 4 files changed, 87 insertions(+), 874 deletions(-) delete mode 100644 Gems/EMotionFX/Code/MCore/Source/AlignedArray.h diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp index 23390bf69b..99f1474c89 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp @@ -24,10 +24,6 @@ namespace EMotionFX 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,10 +51,10 @@ namespace EMotionFX // resize the buffers 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()); + m_localSpaceTransforms.resize_no_construct(numTransforms); + m_modelSpaceTransforms.resize_no_construct(numTransforms); + m_flags.resize_no_construct(numTransforms); + m_morphWeights.resize_no_construct(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets()); for (const auto& poseDataItem : m_poseDatas) { @@ -79,11 +75,11 @@ namespace EMotionFX // resize the buffers const size_t numTransforms = m_actor->GetSkeleton()->GetNumNodes(); - m_localSpaceTransforms.ResizeFast(numTransforms); - m_modelSpaceTransforms.ResizeFast(numTransforms); + m_localSpaceTransforms.resize_no_construct(numTransforms); + m_modelSpaceTransforms.resize_no_construct(numTransforms); - const size_t oldSize = m_flags.GetLength(); - m_flags.ResizeFast(numTransforms); + const size_t oldSize = m_flags.size(); + m_flags.resize_no_construct(numTransforms); if (oldSize < numTransforms && clearAllFlags == false) { for (size_t i = oldSize; i < numTransforms; ++i) @@ -93,7 +89,7 @@ namespace EMotionFX } MorphSetup* morphSetup = m_actor->GetMorphSetup(0); - m_morphWeights.ResizeFast((morphSetup) ? morphSetup->GetNumMorphTargets() : 0); + m_morphWeights.resize_no_construct((morphSetup) ? morphSetup->GetNumMorphTargets() : 0); for (const auto& poseDataItem : m_poseDatas) { @@ -111,11 +107,11 @@ namespace EMotionFX void Pose::SetNumTransforms(size_t numTransforms) { // resize the buffers - m_localSpaceTransforms.ResizeFast(numTransforms); - m_modelSpaceTransforms.ResizeFast(numTransforms); + m_localSpaceTransforms.resize_no_construct(numTransforms); + m_modelSpaceTransforms.resize_no_construct(numTransforms); - const size_t oldSize = m_flags.GetLength(); - m_flags.ResizeFast(numTransforms); + const size_t oldSize = m_flags.size(); + m_flags.resize_no_construct(numTransforms); for (size_t i = oldSize; i < numTransforms; ++i) { @@ -127,10 +123,18 @@ namespace EMotionFX void Pose::Clear(bool clearMem) { - m_localSpaceTransforms.Clear(clearMem); - m_modelSpaceTransforms.Clear(clearMem); - m_flags.Clear(clearMem); - m_morphWeights.Clear(clearMem); + const auto clear = [clearMem](auto& vector) + { + vector.clear(); + if (clearMem) + { + vector.shrink_to_fit(); + } + }; + clear(m_localSpaceTransforms); + clear(m_modelSpaceTransforms); + clear(m_flags); + clear(m_morphWeights); ClearPoseDatas(); } @@ -139,7 +143,7 @@ namespace EMotionFX // clear the pose flags void Pose::ClearFlags(uint8 newFlags) { - MCore::MemSet((uint8*)m_flags.GetPtr(), newFlags, sizeof(uint8) * m_flags.GetLength()); + MCore::MemSet((uint8*)m_flags.data(), newFlags, sizeof(uint8) * m_flags.size()); } @@ -398,30 +402,27 @@ namespace EMotionFX // invalidate all local transforms void Pose::InvalidateAllLocalSpaceTransforms() { - const size_t numFlags = m_flags.GetLength(); - for (size_t i = 0; i < numFlags; ++i) + for (uint8& flag : m_flags) { - m_flags[i] &= ~FLAG_LOCALTRANSFORMREADY; + flag &= ~FLAG_LOCALTRANSFORMREADY; } } void Pose::InvalidateAllModelSpaceTransforms() { - const size_t numFlags = m_flags.GetLength(); - for (size_t i = 0; i < numFlags; ++i) + for (uint8& flag : m_flags) { - m_flags[i] &= ~FLAG_MODELTRANSFORMREADY; + flag &= ~FLAG_MODELTRANSFORMREADY; } } void Pose::InvalidateAllLocalAndModelSpaceTransforms() { - const size_t numFlags = m_flags.GetLength(); - for (size_t i = 0; i < numFlags; ++i) + for (uint8& flag : m_flags) { - m_flags[i] &= ~(FLAG_LOCALTRANSFORMREADY | FLAG_MODELTRANSFORMREADY); + flag &= ~(FLAG_LOCALTRANSFORMREADY | FLAG_MODELTRANSFORMREADY); } } @@ -469,8 +470,8 @@ namespace EMotionFX // make sure the number of transforms are equal MCORE_ASSERT(destPose); MCORE_ASSERT(outPose); - MCORE_ASSERT(m_localSpaceTransforms.GetLength() == destPose->m_localSpaceTransforms.GetLength()); - MCORE_ASSERT(m_localSpaceTransforms.GetLength() == outPose->m_localSpaceTransforms.GetLength()); + MCORE_ASSERT(m_localSpaceTransforms.size() == destPose->m_localSpaceTransforms.size()); + MCORE_ASSERT(m_localSpaceTransforms.size() == outPose->m_localSpaceTransforms.size()); MCORE_ASSERT(instance->GetIsMixing() == false); // get some motion instance properties which we use to decide the optimized blending routine @@ -509,7 +510,7 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -533,7 +534,7 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -550,8 +551,8 @@ namespace EMotionFX // make sure the number of transforms are equal MCORE_ASSERT(destPose); MCORE_ASSERT(outPose); - MCORE_ASSERT(m_localSpaceTransforms.GetLength() == destPose->m_localSpaceTransforms.GetLength()); - MCORE_ASSERT(m_localSpaceTransforms.GetLength() == outPose->m_localSpaceTransforms.GetLength()); + MCORE_ASSERT(m_localSpaceTransforms.size() == destPose->m_localSpaceTransforms.size()); + MCORE_ASSERT(m_localSpaceTransforms.size() == outPose->m_localSpaceTransforms.size()); MCORE_ASSERT(instance->GetIsMixing()); const bool additive = (instance->GetBlendMode() == BLENDMODE_ADDITIVE); @@ -564,7 +565,7 @@ namespace EMotionFX Transform result; const MotionLinkData* motionLinkData = instance->GetMotion()->GetMotionData()->FindMotionLinkData(actorInstance->GetActor()); - AZ_Assert(motionLinkData->GetJointDataLinks().size() == m_localSpaceTransforms.GetLength(), "Expecting there to be the same amount of motion links as pose transforms."); + AZ_Assert(motionLinkData->GetJointDataLinks().size() == m_localSpaceTransforms.size(), "Expecting there to be the same amount of motion links as pose transforms."); // blend all transforms if (!additive) @@ -589,7 +590,7 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -619,7 +620,7 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -647,10 +648,10 @@ namespace EMotionFX return; } - m_modelSpaceTransforms.MemCopyContentsFrom(sourcePose->m_modelSpaceTransforms); - m_localSpaceTransforms.MemCopyContentsFrom(sourcePose->m_localSpaceTransforms); - m_flags.MemCopyContentsFrom(sourcePose->m_flags); - m_morphWeights.MemCopyContentsFrom(sourcePose->m_morphWeights); + m_modelSpaceTransforms = sourcePose->m_modelSpaceTransforms; + m_localSpaceTransforms = sourcePose->m_localSpaceTransforms; + m_flags = sourcePose->m_flags; + m_morphWeights = 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. @@ -727,11 +728,11 @@ namespace EMotionFX m_localSpaceTransforms[nodeNr].Zero(); } - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); - for (size_t i = 0; i < numMorphs; ++i) + for (float& morphWeight : m_morphWeights) { - m_morphWeights[i] = 0.0f; + morphWeight = 0.0f; } } else @@ -742,11 +743,11 @@ namespace EMotionFX m_localSpaceTransforms[i].Zero(); } - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); - for (size_t i = 0; i < numMorphs; ++i) + for (float& morphWeight : m_morphWeights) { - m_morphWeights[i] = 0.0f; + morphWeight = 0.0f; } } @@ -795,7 +796,7 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == other->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -814,7 +815,7 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == other->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -841,7 +842,7 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -865,7 +866,7 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -886,7 +887,7 @@ namespace EMotionFX Pose& Pose::MakeRelativeTo(const Pose& other) { - AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size"); if (m_actorInstance) { const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); @@ -899,7 +900,7 @@ namespace EMotionFX } else { - const size_t numNodes = m_localSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.size(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -907,7 +908,7 @@ namespace EMotionFX } } - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); AZ_Assert(numMorphs == other.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); for (size_t i = 0; i < numMorphs; ++i) { @@ -921,7 +922,7 @@ namespace EMotionFX Pose& Pose::ApplyAdditive(const Pose& additivePose, float weight) { - AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == additivePose.m_localSpaceTransforms.size(), "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"); @@ -939,7 +940,7 @@ namespace EMotionFX } else { - AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == additivePose.m_localSpaceTransforms.size(), "Poses must be of the same size"); if (m_actorInstance) { const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); @@ -959,7 +960,7 @@ namespace EMotionFX } else { - const size_t numNodes = m_localSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.size(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -974,7 +975,7 @@ namespace EMotionFX } } - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); AZ_Assert(numMorphs == additivePose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); for (size_t i = 0; i < numMorphs; ++i) { @@ -989,7 +990,7 @@ namespace EMotionFX Pose& Pose::ApplyAdditive(const Pose& additivePose) { - AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == additivePose.m_localSpaceTransforms.size(), "Poses must be of the same size"); if (m_actorInstance) { const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); @@ -1009,7 +1010,7 @@ namespace EMotionFX } else { - const size_t numNodes = m_localSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.size(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -1024,7 +1025,7 @@ namespace EMotionFX } } - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); AZ_Assert(numMorphs == additivePose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); for (size_t i = 0; i < numMorphs; ++i) { @@ -1038,7 +1039,7 @@ namespace EMotionFX Pose& Pose::MakeAdditive(const Pose& refPose) { - AZ_Assert(m_localSpaceTransforms.GetLength() == refPose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == refPose.m_localSpaceTransforms.size(), "Poses must be of the same size"); if (m_actorInstance) { const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); @@ -1057,7 +1058,7 @@ namespace EMotionFX } else { - const size_t numNodes = m_localSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.size(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -1071,7 +1072,7 @@ namespace EMotionFX } } - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); AZ_Assert(numMorphs == refPose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); for (size_t i = 0; i < numMorphs; ++i) { @@ -1101,7 +1102,7 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -1123,7 +1124,7 @@ namespace EMotionFX } // blend the morph weights - const size_t numMorphs = m_morphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.size(); MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); for (size_t i = 0; i < numMorphs; ++i) @@ -1274,23 +1275,19 @@ namespace EMotionFX // zero all morph weights void Pose::ZeroMorphWeights() { - const size_t numMorphs = m_morphWeights.GetLength(); - for (size_t m = 0; m < numMorphs; ++m) - { - m_morphWeights[m] = 0.0f; - } + AZStd::fill(begin(m_morphWeights), end(m_morphWeights), 0.0f); } void Pose::ResizeNumMorphs(size_t numMorphTargets) { - m_morphWeights.Resize(numMorphTargets); + m_morphWeights.resize(numMorphTargets); } Pose& Pose::PreMultiply(const Pose& other) { - AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size"); if (m_actorInstance) { const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); @@ -1304,7 +1301,7 @@ namespace EMotionFX } else { - const size_t numNodes = m_localSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.size(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -1320,7 +1317,7 @@ namespace EMotionFX Pose& Pose::Multiply(const Pose& other) { - AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size"); if (m_actorInstance) { const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); @@ -1333,7 +1330,7 @@ namespace EMotionFX } else { - const size_t numNodes = m_localSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.size(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); @@ -1348,7 +1345,7 @@ namespace EMotionFX Pose& Pose::MultiplyInverse(const Pose& other) { - AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size"); if (m_actorInstance) { const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); @@ -1363,7 +1360,7 @@ namespace EMotionFX } else { - const size_t numNodes = m_localSpaceTransforms.GetLength(); + const size_t numNodes = m_localSpaceTransforms.size(); for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h index 32c7a33bd2..b7844276be 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include #include #include @@ -98,9 +98,9 @@ namespace EMotionFX Transform CalcTrajectoryTransform() const; - 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 Transform* GetLocalSpaceTransforms() const { return m_localSpaceTransforms.data(); } + MCORE_INLINE const Transform* GetModelSpaceTransforms() const { return m_modelSpaceTransforms.data(); } + MCORE_INLINE size_t GetNumTransforms() const { return m_localSpaceTransforms.size(); } 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; } @@ -116,7 +116,7 @@ namespace EMotionFX 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(); } + MCORE_INLINE size_t GetNumMorphWeights() const { return m_morphWeights.size(); } void ResizeNumMorphs(size_t numMorphTargets); /** @@ -193,11 +193,11 @@ namespace EMotionFX T* GetAndPreparePoseData(ActorInstance* linkToActorInstance) { return azdynamic_cast(GetAndPreparePoseData(azrtti_typeid(), linkToActorInstance)); } private: - mutable MCore::AlignedArray m_localSpaceTransforms; - mutable MCore::AlignedArray m_modelSpaceTransforms; - mutable MCore::AlignedArray m_flags; + mutable AZStd::vector m_localSpaceTransforms; + mutable AZStd::vector m_modelSpaceTransforms; + mutable AZStd::vector m_flags; AZStd::unordered_map > m_poseDatas; - MCore::AlignedArray m_morphWeights; /**< The morph target weights. */ + AZStd::vector m_morphWeights; /**< The morph target weights. */ const ActorInstance* m_actorInstance; const Actor* m_actor; const Skeleton* m_skeleton; diff --git a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h b/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h deleted file mode 100644 index 5ffaac2e40..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h +++ /dev/null @@ -1,783 +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" - - -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 18446744073709551614 items (maximum size_t value - 1 for the invalid index). - */ - template - class AlignedArray - { - 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 = 3 - }; - - /** - * Default constructor. - * Initializes the array so it's empty and has no memory allocated. - */ - MCORE_INLINE AlignedArray() - : m_data(nullptr) - , m_length(0) - , m_maxLength(0) - , m_memCategory(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 AlignedArray(T* elems, size_t num, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : m_length(num) - , m_maxLength(AllocSize(num)) - , m_memCategory(memCategory) - { - 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]); - } - } - - /** - * 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 AlignedArray(size_t initSize, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : m_data(nullptr) - , m_length(initSize) - , m_maxLength(initSize) - , m_memCategory(memCategory) - { - if (m_maxLength > 0) - { - 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); - } - } - } - - /** - * Copy constructor. - * @param other The other array to copy the data from. - */ - AlignedArray(const AlignedArray& 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) { 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. - * However, if you store pointers to objects, these objects won't be deleted.
- * Example:
- *
-         * AlignedArray< Object*, 16 > data;
-         * 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 (size_t i=0; i
-         */
-        ~AlignedArray()
-        {
-            for (size_t i = 0; i < m_length; ++i)
-            {
-                Destruct(i);
-            }
-            if (m_data)
-            {
-                AlignedFree(m_data);
-            }
-        }
-
-        /**
-         * 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 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)                  { m_memCategory = categoryID; }
-
-        /**
-         * Get a pointer to the first element.
-         * @result A pointer to the first element.
-         */
-        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 m_data; }
-
-        /**
-         * Get a given item/element.
-         * @param pos The item/element number.
-         * @result A reference to the element.
-         */
-        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 m_data[0]; }
-
-        /**
-         * Get the last element.
-         * @result A reference to the last element.
-         */
-        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 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(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 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 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 (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(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 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.
-         * 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 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 size_t CalcMemoryUsage(bool includeMembers = true) const
-        {
-            size_t result = m_maxLength * sizeof(T);
-            if (includeMembers)
-            {
-                result += sizeof(AlignedArray);
-            }
-            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(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(++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(++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 AlignedArray& a)
-        {
-            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]);
-            }
-        }                                                                                                                                                                                   // 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(++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(++m_length); Construct(m_length - 1); }
-
-        /**
-         * Remove the first array element.
-         */
-        MCORE_INLINE void RemoveFirst()
-        {
-            if (m_length > 0)
-            {
-                Remove(0);
-            }
-        }
-
-        /**
-         * Remove the last array element.
-         */
-        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(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(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(size_t pos)
-        {
-            Destruct(pos);
-            if (m_length > 1)
-            {
-                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(size_t pos, size_t num)
-        {
-            for (size_t i = pos; i < pos + num; ++i)
-            {
-                Destruct(i);
-            }
-            MoveElements(pos, pos + num, m_length - pos - num);
-            m_length -= 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)
-        {
-            size_t index = Find(item);
-            if (index == InvalidIndex)
-            {
-                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(size_t 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. - * @param pos1 The first element number. - * @param pos2 The second element number. - */ - MCORE_INLINE void Swap(size_t pos1, size_t pos2) - { - if (pos1 != pos2) - { - 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 (size_t i = 0; i < m_length; ++i) - { - Destruct(i); - } - m_length = 0; - if (clearMem) - { - this->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(size_t newLength) - { - if (m_length >= newLength) - { - return; - } - size_t oldLen = m_length; - Grow(newLength); - for (size_t 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(size_t minLength) - { - if (m_maxLength < minLength) - { - 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 (m_length == m_maxLength) - { - return; - } - MCORE_ASSERT(m_maxLength >= m_length); - Realloc(m_length); - } - - /** - * 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) != 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 InvalidIndex is returned. - */ - MCORE_INLINE size_t Find(const T& x) const - { - for (size_t i = 0; i < m_length; ++i) - { - if (m_data[i] == x) - { - return i; - } - } - return InvalidIndex; - } - - /** - * Copy the contents of another array into this one using a direct memory copy. - * This does not call copy constructors of the objects, but just copies the raw memory data. - * 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*)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); - 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, 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 InvalidIndex, GetLength()-1 will be used). - * @param cmp The compare function. - */ - MCORE_INLINE void Sort(size_t first = 0, size_t last = InvalidIndex, CmpFunc cmp = StdCmp) - { - if (last == InvalidIndex) - { - last = m_length - 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(size_t newLength) - { - if (m_length == newLength) - { - return; - } - - if (newLength > m_length) - { - GrowExact(newLength); - } - - m_length = 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. - */ - void Resize(size_t newLength) - { - if (m_length == newLength) - { - return; - } - - // check for growing or shrinking array - if (newLength > m_length) - { - // growing array, construct empty elements at end of array - const size_t oldLen = m_length; - GrowExact(newLength); - for (size_t i = oldLen; i < newLength; ++i) - { - Construct(i); - } - } - else - { - // shrinking array, destruct elements at end of array - for (size_t i = newLength; i < m_length; ++i) - { - Destruct(i); - } - - m_length = newLength; - } - } - - /** - * Move "numElements" elements starting from the source index, to the dest index. - * Please note thate 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(size_t destIndex, size_t sourceIndex, size_t numElements) - { - if (numElements > 0) - { - MemMove(m_data + destIndex, m_data + sourceIndex, numElements * sizeof(T)); - } - } - - // operators - bool operator==(const AlignedArray& other) const - { - if (m_length != other.m_length) - { - return false; - } - for (size_t i = 0; i < m_length; ++i) - { - if (m_data[i] != other.m_data[i]) - { - return false; - } - } - return true; - } - AlignedArray& operator= (const AlignedArray& other) - { - if (&other != this) - { - Clear(false); - m_memCategory = other.m_memCategory; - Grow(other.m_length); - for (size_t i = 0; i < m_length; ++i) - { - Construct(i, other.m_data[i]); - } - } - return *this; - } - AlignedArray& operator= (AlignedArray&& other) - { - MCORE_ASSERT(&other != this); - if (m_data) - { - AlignedFree(m_data); - } - 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[](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* 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(size_t newLength) - { - m_length = newLength; - if (m_maxLength >= newLength) - { - return; - } - Realloc(AllocSize(newLength)); - } - MCORE_INLINE void GrowExact(size_t newLength) - { - m_length = newLength; - if (m_maxLength < newLength) - { - Realloc(newLength); - } - } - 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 (m_data) - { - m_data = (T*)AlignedRealloc(m_data, newSize * sizeof(T), m_maxLength * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - } - else - { - m_data = (T*)AlignedAllocate(newSize * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - } - - m_maxLength = newSize; - } - void Free() - { - m_length = 0; - m_maxLength = 0; - if (m_data) - { - AlignedFree(m_data); - m_data = nullptr; - } - } - 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 - (m_data + index)->~T(); - } - - // partition part of array (for sorting) - int32 Partition(int32 left, int32 right, CmpFunc cmp) - { - ::MCore::Swap(m_data[left], m_data[ (left + right) >> 1 ]); - - 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(m_data[++i], target) >= 0) - { - break; - } - } - while (j > i) - { - if (cmp(m_data[--j], target) <= 0) - { - break; - } - } - if (i >= j) - { - break; - } - ::MCore::Swap(m_data[i], m_data[j]); - } - - ::MCore::Swap(m_data[i], m_data[right]); - return i; - } - }; -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index 47b35e004b..bb9c0f4447 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -11,7 +11,6 @@ set(FILES Source/Algorithms.cpp Source/Algorithms.h Source/Algorithms.inl - Source/AlignedArray.h Source/Array2D.h Source/Array2D.inl Source/Attribute.cpp From 8d0f9f4114630a35ebceb677086f7e16ff5c1df2 Mon Sep 17 00:00:00 2001 From: Scott Romero <24445312+AMZN-ScottR@users.noreply.github.com> Date: Tue, 10 Aug 2021 12:19:31 -0700 Subject: [PATCH 224/251] [development] updated file regex when uploading latest tagged installer (#2987) The "Latest" tagged installer uploads were failing the file filter because the upload script now collects files as full path before performing the regex. Signed-off-by: AMZN-ScottR 24445312+AMZN-ScottR@users.noreply.github.com --- cmake/Platform/Windows/PackagingPostBuild.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Platform/Windows/PackagingPostBuild.cmake b/cmake/Platform/Windows/PackagingPostBuild.cmake index 3f364b89c5..5e09743373 100644 --- a/cmake/Platform/Windows/PackagingPostBuild.cmake +++ b/cmake/Platform/Windows/PackagingPostBuild.cmake @@ -189,7 +189,7 @@ if(CPACK_AUTO_GEN_TAG) upload_to_s3( ${_latest_upload_url} ${_temp_dir} - "(${_non_versioned_exe}|build_tag.txt)$" + ".*(${_non_versioned_exe}|build_tag.txt)$" ) # cleanup the temp files From a9cd126026e2a27ed531b097717cdb8f3a0d10e3 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 12:30:04 -0700 Subject: [PATCH 225/251] Adding PLATFORM_H_SECTION_15 back since it is used in restricted Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/platform.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 9ff461543f..88d06c9b1e 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -24,6 +24,7 @@ #define PLATFORM_H_SECTION_12 12 #define PLATFORM_H_SECTION_13 13 #define PLATFORM_H_SECTION_14 14 +#define PLATFORM_H_SECTION_15 15 #endif #if (defined(LINUX) && !defined(ANDROID)) || defined(APPLE) @@ -414,4 +415,9 @@ threadID CryGetCurrentThreadId(); #endif #endif +#if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_15 + #include AZ_RESTRICTED_FILE(platform_h) +#endif + void InitRootDir(char szExeFileName[] = nullptr, uint nExeSize = 0, char szExeRootName[] = nullptr, uint nRootSize = 0); From ab1b6ff3b40640ce502a340b447ab8939f143189 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Tue, 10 Aug 2021 12:41:24 -0700 Subject: [PATCH 226/251] Add LyShine gem runtime dependency to Material Editor in AutomatedTesting project (#2996) Signed-off-by: abrmich --- AutomatedTesting/Gem/Code/CMakeLists.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/AutomatedTesting/Gem/Code/CMakeLists.txt b/AutomatedTesting/Gem/Code/CMakeLists.txt index 76c0db3f5c..58ffd957d6 100644 --- a/AutomatedTesting/Gem/Code/CMakeLists.txt +++ b/AutomatedTesting/Gem/Code/CMakeLists.txt @@ -57,6 +57,12 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) TARGETS Editor VARIANTS Tools) + # The Material Editor needs the Lyshine "Tools" gem variant for the custom LyShine pass + ly_enable_gems( + PROJECT_NAME AutomatedTesting GEMS LyShine + TARGETS MaterialEditor + VARIANTS Tools) + # The pipeline tools use "Builders" gem variants: ly_enable_gems( PROJECT_NAME AutomatedTesting GEM_FILE enabled_gems.cmake From 5472d6768e8a3ceb81f901251858bb58600439d0 Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Tue, 10 Aug 2021 12:48:26 -0700 Subject: [PATCH 227/251] Minor improvements Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h | 6 +++--- .../RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h index cdbf983561..2c884ceedf 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h @@ -38,12 +38,12 @@ namespace AZ void SetDrawListTag(Name drawListName); - void SetPipelineStateDataIndex(u32 index); + void SetPipelineStateDataIndex(uint32_t index); //! Expose shader resource group. ShaderResourceGroup* GetShaderResourceGroup(); - u32 GetDrawItemCount(); + uint32_t GetDrawItemCount(); protected: explicit RasterPass(const PassDescriptor& descriptor); @@ -78,7 +78,7 @@ namespace AZ RHI::Viewport m_viewportState; bool m_overrideScissorSate = false; bool m_overrideViewportState = false; - u32 m_drawItemCount = 0; + uint32_t m_drawItemCount = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index 4da5560908..ce02e1c570 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -104,7 +104,7 @@ namespace AZ m_flags.m_hasDrawListTag = true; } - void RasterPass::SetPipelineStateDataIndex(u32 index) + void RasterPass::SetPipelineStateDataIndex(uint32_t index) { m_pipelineStateDataIndex.m_index = index; } @@ -114,7 +114,7 @@ namespace AZ return m_shaderResourceGroup.get(); } - u32 RasterPass::GetDrawItemCount() + uint32_t RasterPass::GetDrawItemCount() { return m_drawItemCount; } @@ -172,7 +172,7 @@ namespace AZ if (viewDrawList.size() > 0 && drawLists.size() == 0) { m_drawListView = viewDrawList; - m_drawItemCount += (u32)viewDrawList.size(); + m_drawItemCount += static_cast(viewDrawList.size()); PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); return; } @@ -183,7 +183,7 @@ namespace AZ // combine draw items from mutiple draw lists to one draw list and sort it. for (auto drawList : drawLists) { - m_drawItemCount += (u32)drawList.size(); + m_drawItemCount += static_cast(drawList.size()); } PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); m_combinedDrawList.resize(m_drawItemCount); @@ -211,7 +211,7 @@ namespace AZ void RasterPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) { RenderPass::SetupFrameGraphDependencies(frameGraph); - frameGraph.SetEstimatedItemCount(static_cast(m_drawListView.size())); + frameGraph.SetEstimatedItemCount(static_cast(m_drawListView.size())); } void RasterPass::CompileResources(const RHI::FrameGraphCompileContext& context) From 4450eb4e224c1352addf25db767a61ef3a812e39 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 13:24:20 -0700 Subject: [PATCH 228/251] fix new warning hit Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4f1aa5b42b..a0d0e62abd 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 @@ -330,7 +330,7 @@ namespace EMStudio const size_t numMorphTargets = m_morphSetup->GetNumMorphTargets(); const uint32 numPhonemeSets = m_morphTarget->GetNumAvailablePhonemeSets(); int insertPosition = 0; - for (int i = 1; i < numPhonemeSets; ++i) + for (uint32 i = 1; i < numPhonemeSets; ++i) { // check if another morph target already has this phoneme set. bool phonemeSetFound = false; From 181998f8107f8776c3bc137732059f0a3b67639e Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 14:05:14 -0700 Subject: [PATCH 229/251] Fixes a nightly build and a CMake warning (#2941) * Addressing CMake warning and removing timeouts that are the same as the default Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * missed this one Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * Making it an error so developers stops putting timeouts longer than the allowed one since it causes AR issues Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * fixing warning from the nightly build Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * disabling test that is triggering a timeout Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Gem/PythonTests/Blast/CMakeLists.txt | 1 - .../Gem/PythonTests/NvCloth/CMakeLists.txt | 1 - .../PythonAssetBuilder/CMakeLists.txt | 1 - .../Gem/PythonTests/WhiteBox/CMakeLists.txt | 1 - .../asset_processor_tests/CMakeLists.txt | 24 +++++++++---------- .../Gem/PythonTests/editor/CMakeLists.txt | 4 ---- .../PythonTests/largeworlds/CMakeLists.txt | 11 --------- .../Gem/PythonTests/physics/CMakeLists.txt | 3 --- .../Gem/PythonTests/prefab/CMakeLists.txt | 1 - .../Gem/PythonTests/scripting/CMakeLists.txt | 2 -- .../Gem/PythonTests/smoke/CMakeLists.txt | 1 - Gems/PhysX/Code/CMakeLists.txt | 1 - cmake/LYTestWrappers.cmake | 2 +- 13 files changed, 12 insertions(+), 41 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt index 7048a6bd46..172eded09a 100644 --- a/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL TRUE PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Active.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt index a39cdf04cf..3913041f88 100644 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt @@ -13,7 +13,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_REQUIRES gpu TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Active.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt index 9b6542b3e3..905470e08f 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt index b5fcfcc44c..1c7a02862d 100644 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Active.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt index 0170d73af0..3d7a9204e2 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt @@ -92,17 +92,17 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AssetProcessor ) - ly_add_pytest( - NAME AssetPipelineTests.AssetBundler - PATH ${CMAKE_CURRENT_LIST_DIR}/asset_bundler_batch_tests.py - EXCLUDE_TEST_RUN_TARGET_FROM_IDE - TEST_SERIAL - TIMEOUT 2400 - TEST_SUITE periodic - RUNTIME_DEPENDENCIES - AZ::AssetProcessor - AZ::AssetBundlerBatch - ) + # Issue #3017 + #ly_add_pytest( + # NAME AssetPipelineTests.AssetBundler + # PATH ${CMAKE_CURRENT_LIST_DIR}/asset_bundler_batch_tests.py + # EXCLUDE_TEST_RUN_TARGET_FROM_IDE + # TEST_SERIAL + # TEST_SUITE periodic + # RUNTIME_DEPENDENCIES + # AZ::AssetProcessor + # AZ::AssetBundlerBatch + #) ly_add_pytest( NAME AssetPipelineTests.AssetBundler_SandBox @@ -111,7 +111,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) PYTEST_MARKS "SUITE_sandbox" # run only sandbox tests in this file EXCLUDE_TEST_RUN_TARGET_FROM_IDE TEST_SERIAL - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::AssetBundlerBatch @@ -133,7 +132,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) PATH ${CMAKE_CURRENT_LIST_DIR}/missing_dependency_tests.py EXCLUDE_TEST_RUN_TARGET_FROM_IDE TEST_SERIAL - TIMEOUT 1500 TEST_SUITE periodic RUNTIME_DEPENDENCIES AZ::AssetProcessorBatch diff --git a/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt index afde0a0d94..fa35bb25c6 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt @@ -13,7 +13,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_main and not REQUIRES_gpu" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -28,7 +27,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_periodic and not REQUIRES_gpu" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -44,7 +42,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_REQUIRES gpu PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_main and REQUIRES_gpu" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -59,7 +56,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_sandbox" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt index 351ca19031..043485d869 100644 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt @@ -16,7 +16,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE main PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "not SUITE_sandbox and not SUITE_periodic and not SUITE_benchmark" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -33,7 +32,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE sandbox PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_sandbox" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -49,7 +47,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_filter" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -64,7 +61,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_modifier" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -79,7 +75,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_regression" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -94,7 +89,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_area" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -109,7 +103,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_misc" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -124,7 +117,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_surfacetagemitter" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -140,7 +132,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE main PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas PYTEST_MARKS "not SUITE_sandbox and not SUITE_periodic and not SUITE_benchmark" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -155,7 +146,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas PYTEST_MARKS "SUITE_periodic" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -170,7 +160,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/gradient_signal - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor diff --git a/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt index 248bf3fdc5..eb37db1943 100644 --- a/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -25,7 +24,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Periodic.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -38,7 +36,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE sandbox TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Sandbox.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt index 1d9c54fa40..48c24d1ebf 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt @@ -13,7 +13,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt index 80b6e9a54e..25988216b2 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Periodic.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -25,7 +24,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE sandbox TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Sandbox.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 2c1d03b5a2..3fc4f3db0e 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -18,7 +18,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_smoke" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::PythonBindingsExample diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index a69019249f..80e8bee8e3 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -186,7 +186,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_googlebenchmark( NAME Gem::PhysX.Benchmarks TARGET Gem::PhysX.Tests - TIMEOUT 1500 #25mins ) list(APPEND testTargets PhysX.Tests) diff --git a/cmake/LYTestWrappers.cmake b/cmake/LYTestWrappers.cmake index efb19a20dd..8e71cb3db1 100644 --- a/cmake/LYTestWrappers.cmake +++ b/cmake/LYTestWrappers.cmake @@ -114,7 +114,7 @@ function(ly_add_test) if(NOT ly_add_test_TIMEOUT) set(ly_add_test_TIMEOUT ${LY_TEST_DEFAULT_TIMEOUT}) elseif(ly_add_test_TIMEOUT GREATER LY_TEST_DEFAULT_TIMEOUT) - message(WARNING "TIMEOUT for test ${ly_add_test_NAME} set at ${ly_add_test_TIMEOUT} seconds which is longer than the default of ${LY_TEST_DEFAULT_TIMEOUT}. Allowing a single module to run exceedingly long creates problems in a CI pipeline.") + message(FATAL_ERROR "TIMEOUT for test ${ly_add_test_NAME} set at ${ly_add_test_TIMEOUT} seconds which is longer than the default of ${LY_TEST_DEFAULT_TIMEOUT}. Allowing a single module to run exceedingly long creates problems in a CI pipeline.") endif() if(NOT ly_add_test_TEST_COMMAND) From d71674579a372c17af98f522f5b96949f2495667 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 16:22:03 -0700 Subject: [PATCH 230/251] fixing startup on game launcher Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/platform_impl.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 3d7b2180fc..3d23d8783e 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -290,14 +290,14 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], uint // Check if the engineroot exists azstrcat(szPath, AZ_ARRAY_SIZE(szPath), "\\engine.json"); WIN32_FILE_ATTRIBUTE_DATA data; - AZStd::wstring szPathW; - AZStd::to_wstring(szPathW, szPath); - BOOL res = GetFileAttributesExW(szPathW.c_str(), GetFileExInfoStandard, &data); + wchar_t szPathW[_MAX_PATH]; + AZStd::to_wstring(szPathW, _MAX_PATH, szPath); + BOOL res = GetFileAttributesExW(szPathW, GetFileExInfoStandard, &data); if (res != 0 && data.dwFileAttributes != INVALID_FILE_ATTRIBUTES) { // Found file szPath[n] = 0; - SetCurrentDirectoryW(szPathW.c_str()); + SetCurrentDirectoryW(szPathW); break; } } From cfa6e259f3bc5ddeb690afb6e74f6aa27b25062c Mon Sep 17 00:00:00 2001 From: Jeremy Ong Date: Tue, 10 Aug 2021 17:24:07 -0600 Subject: [PATCH 231/251] Hide RenderDoc integration behind LY_RENDERDOC_ENABLED option Signed-off-by: Jeremy Ong --- Gems/Atom/RHI/Code/CMakeLists.txt | 8 +++----- Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake | 7 ------- .../RHI/Code/Platform/Windows/renderdoc_windows.cmake | 9 +-------- 3 files changed, 4 insertions(+), 20 deletions(-) diff --git a/Gems/Atom/RHI/Code/CMakeLists.txt b/Gems/Atom/RHI/Code/CMakeLists.txt index eeb8f73bac..343736ff7c 100644 --- a/Gems/Atom/RHI/Code/CMakeLists.txt +++ b/Gems/Atom/RHI/Code/CMakeLists.txt @@ -11,20 +11,19 @@ ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Sourc include(${pal_dir}/AtomRHITests_traits_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +set(LY_RENDERDOC_ENABLED OFF CACHE BOOL "Enable RenderDoc integration.") set(RENDERDOC_CMAKE ${CMAKE_CURRENT_SOURCE_DIR}/${pal_dir}/renderdoc_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) if(EXISTS ${RENDERDOC_CMAKE}) include(${RENDERDOC_CMAKE}) endif() -if(TARGET "3rdParty::renderdoc") +if(LY_RENDERDOC_ENABLED AND TARGET "3rdParty::renderdoc") message(STATUS "Renderdoc found, adding as runtime dependency") set(USE_RENDERDOC_DEFINE "USE_RENDERDOC") set(RENDERDOC_BUILD_DEPENDENCY "3rdParty::renderdoc") - set(RENDERDOC_API_DEPENDENCY "3rdParty::renderdoc_api") else() set(USE_RENDERDOC_DEFINE "") set(RENDERDOC_BUILD_DEPENDENCY "") - set(RENDERDOC_API_DEPENDENCY "") endif() ly_add_target( @@ -62,9 +61,8 @@ ly_add_target( AZ::AzCore AZ::AzFramework Gem::Atom_RHI.Reflect - ${RENDERDOC_BUILD_DEPENDENCY} PUBLIC - ${RENDERDOC_API_DEPENDENCY} + ${RENDERDOC_BUILD_DEPENDENCY} COMPILE_DEFINITIONS PUBLIC ${USE_RENDERDOC_DEFINE} diff --git a/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake b/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake index 0faccf80ec..222a3d5768 100644 --- a/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake +++ b/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake @@ -24,13 +24,6 @@ if(NOT LY_MONOLITHIC_GAME) INCLUDE_DIRECTORIES "." RUNTIME_DEPENDENCIES "${RENDERDOC_PATH}/librenderdoc.so" ) - - ly_add_external_target( - NAME renderdoc_api - VERSION - 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} - INCLUDE_DIRECTORIES "." - ) endif() endif() endif() \ No newline at end of file diff --git a/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake b/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake index 499321b2ab..90c44bcb7c 100644 --- a/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake +++ b/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake @@ -9,7 +9,7 @@ # Prevent bundling the renderdoc dll with a packaged title if(NOT LY_MONOLITHIC_GAME) # Common installation path for renderdoc path - set(RENDERDOC_PATH "C:/Program Files/RenderDoc") + set(RENDERDOC_PATH "$ENV{PROGRAMFILES}/RenderDoc") if(DEFINED ENV{"ATOM_RENDERDOC_PATH"}) set(RENDERDOC_PATH ENV{"ATOM_RENDERDOC_PATH"}) endif() @@ -26,13 +26,6 @@ if(NOT LY_MONOLITHIC_GAME) INCLUDE_DIRECTORIES "." RUNTIME_DEPENDENCIES "${RENDERDOC_PATH}/renderdoc.dll" ) - - ly_add_external_target( - NAME renderdoc_api - VERSION - 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} - INCLUDE_DIRECTORIES "." - ) endif() endif() endif() \ No newline at end of file From 25844a9ed6cff59d07e6cce1bdc63f01da6a8412 Mon Sep 17 00:00:00 2001 From: AMZN-mnaumov <82239319+AMZN-mnaumov@users.noreply.github.com> Date: Tue, 10 Aug 2021 16:40:51 -0700 Subject: [PATCH 232/251] Selecting entities when duplicating prefabs (#2995) * Selecting entitie when duplicating prefabs Signed-off-by: mnaumov * PR feedback Signed-off-by: mnaumov --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 69efe33d72..bb394720c9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1727,6 +1727,7 @@ namespace AzToolsFramework AliasPath absoluteInstancePath = commonOwningInstance.GetAbsoluteInstanceAliasPath(); absoluteInstancePath.Append(newInstanceAlias); + absoluteInstancePath.Append(PrefabDomUtils::ContainerEntityName); AZ::EntityId newEntityId = InstanceEntityIdMapper::GenerateEntityIdForAliasPath(absoluteInstancePath); duplicatedEntityIds.push_back(newEntityId); From 4cee263033090c4464607eb53f198ab3db8c54e3 Mon Sep 17 00:00:00 2001 From: Artur K <96597+nemerle@users.noreply.github.com> Date: Wed, 11 Aug 2021 02:07:01 +0200 Subject: [PATCH 233/251] Minimal TypeInfo header/reduce std interdependencies. (#2688) * Minimal TypeInfo header/reduce std interdependencies. TypeInfoSimple.h is a small header that can replace the use of TypeInfo.h in some cases. Signed-off-by: Nemerle * Windows build fixed Removed algorithm.h from string_view.h smoke-test passed Signed-off-by: nemerle <96597+nemerle@users.noreply.github.com> * Resotore dynamic_pointer_cast in intrusive_ptr Requested by reviewer. Signed-off-by: nemerle <96597+nemerle@users.noreply.github.com> * Fix CI build string.h - missed alogorithm.h, since it was removed from string_view NodeWrapper.h - missing smart_ptr.h Signed-off-by: nemerle <96597+nemerle@users.noreply.github.com> Co-authored-by: Nemerle --- .../EditorCommon/DrawingPrimitives/Ruler.cpp | 1 + .../std/containers/fixed_vector_set.h | 1 + .../AzCore/AzCore/Component/ComponentExport.h | 2 +- .../AzCore/AzCore/Component/EntityId.h | 2 +- .../AzCore/AzCore/Debug/IEventLogger.h | 2 +- .../AzCore/AzCore/EBus/OrderedEvent.inl | 1 + Code/Framework/AzCore/AzCore/IO/Path/Path.h | 1 + .../AzCore/AzCore/Interface/Interface.h | 1 + Code/Framework/AzCore/AzCore/Math/Crc.h | 4 +- .../AzCore/AzCore/Math/PackedVector3.h | 1 + Code/Framework/AzCore/AzCore/Math/Random.h | 4 +- Code/Framework/AzCore/AzCore/Math/Vector2.h | 2 +- Code/Framework/AzCore/AzCore/Math/Vector3.h | 2 +- Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h | 36 +----------------- .../AzCore/AzCore/RTTI/TypeInfoSimple.h | 38 +++++++++++++++++++ .../AzCore/AzCore/Serialization/DataOverlay.h | 2 +- .../Serialization/Json/ArraySerializer.h | 2 +- .../Serialization/Json/DoubleSerializer.h | 2 +- .../AzCore/Serialization/Json/IntSerializer.h | 2 +- .../AzCore/AzCore/azcore_files.cmake | 1 + Code/Framework/AzCore/AzCore/std/allocator.h | 2 +- .../AzCore/AzCore/std/allocator_traits.h | 1 + .../AzCore/AzCore/std/chrono/types.h | 1 - .../AzCore/AzCore/std/containers/deque.h | 4 +- .../AzCore/AzCore/std/containers/list.h | 3 +- .../AzCore/std/containers/ring_buffer.h | 1 - .../AzCore/AzCore/std/containers/vector.h | 7 +--- .../AzCore/AzCore/std/createdestroy.h | 1 + .../AzCore/std/function/function_base.h | 1 + .../AzCore/std/function/function_template.h | 1 + Code/Framework/AzCore/AzCore/std/hash_table.h | 1 - Code/Framework/AzCore/AzCore/std/iterator.h | 3 +- .../AzCore/AzCore/std/parallel/atomic.h | 2 - .../AzCore/std/smart_ptr/intrusive_ptr.h | 24 +++++------- .../AzCore/AzCore/std/string/string.h | 1 + .../AzCore/AzCore/std/string/string_view.h | 15 +++++--- .../AzCore/std/typetraits/conjunction.h | 1 + .../AzCore/std/typetraits/static_storage.h | 3 +- Code/Framework/AzCore/AzCore/std/utils.h | 2 +- .../IO/Streamer/StreamerContext_Default.h | 1 + .../AzCore/Debug/StackTracer_Windows.cpp | 1 + .../Framework/AzCore/Tests/AZStd/SmartPtr.cpp | 5 ++- .../AzFramework/Archive/IArchive.h | 1 + .../AzFramework/Asset/CfgFileAsset.h | 2 +- .../Physics/Collision/CollisionGroups.h | 2 +- .../Physics/Collision/CollisionLayers.h | 2 +- .../Configuration/CollisionConfiguration.h | 2 +- .../Configuration/SceneConfiguration.h | 2 +- .../Slice/SliceInstantiationTicket.h | 2 +- .../AzFramework/Viewport/CameraState.h | 5 +++ .../AzFramework/Viewport/ScreenGeometry.h | 3 +- .../AzNetworking/PacketLayer/IPacket.h | 2 +- .../AzToolsFramework/API/ViewPaneOptions.h | 2 +- .../AzToolsFramework/Asset/AssetDebugInfo.h | 2 +- .../AzToolsFramework/Viewport/ViewportTypes.h | 1 + Code/Legacy/CryCommon/LyShine/UiAssetTypes.h | 2 +- .../native/ui/AssetTreeFilterModel.h | 1 + .../native/ui/SourceAssetDetailsPanel.h | 1 + Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h | 1 + .../SceneCore/Utilities/DebugOutput.h | 1 + .../Include/Private/ClientConfiguration.h | 1 + .../MaterialFunctorSourceDataRegistration.h | 1 + .../Code/Editor/Utilities/RecentFiles.cpp | 1 + 63 files changed, 129 insertions(+), 96 deletions(-) create mode 100644 Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h diff --git a/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp b/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp index 866a8206d6..1f0bd9ad88 100644 --- a/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp +++ b/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace DrawingPrimitives { diff --git a/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h b/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h index 1d5c9c2edd..c014f4b44e 100644 --- a/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h +++ b/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h @@ -8,6 +8,7 @@ #pragma once #include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentExport.h b/Code/Framework/AzCore/AzCore/Component/ComponentExport.h index c31c739160..0b3f9ea617 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentExport.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentExport.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include #include diff --git a/Code/Framework/AzCore/AzCore/Component/EntityId.h b/Code/Framework/AzCore/AzCore/Component/EntityId.h index 8e00cc70a9..e95813b388 100644 --- a/Code/Framework/AzCore/AzCore/Component/EntityId.h +++ b/Code/Framework/AzCore/AzCore/Component/EntityId.h @@ -9,7 +9,7 @@ #define AZCORE_ENTITY_ID_H #include -#include +#include #include /** @file diff --git a/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h b/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h index f04199e923..a11b411ded 100644 --- a/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h +++ b/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl b/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl index 7c2e92d25b..aa3ac7d5ef 100644 --- a/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl +++ b/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl @@ -7,6 +7,7 @@ */ #pragma once +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.h b/Code/Framework/AzCore/AzCore/IO/Path/Path.h index 6f7e995a74..36640e821d 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.h +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/Interface/Interface.h b/Code/Framework/AzCore/AzCore/Interface/Interface.h index 8131f5b08f..8664e2905f 100644 --- a/Code/Framework/AzCore/AzCore/Interface/Interface.h +++ b/Code/Framework/AzCore/AzCore/Interface/Interface.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/Math/Crc.h b/Code/Framework/AzCore/AzCore/Math/Crc.h index e8e8414f72..9ba2a83139 100644 --- a/Code/Framework/AzCore/AzCore/Math/Crc.h +++ b/Code/Framework/AzCore/AzCore/Math/Crc.h @@ -8,7 +8,7 @@ #pragma once #include - +#include #include ////////////////////////////////////////////////////////////////////////// @@ -108,7 +108,7 @@ namespace AZ namespace AZStd { - template<> + template<> struct hash { size_t operator()(const AZ::Crc32& id) const diff --git a/Code/Framework/AzCore/AzCore/Math/PackedVector3.h b/Code/Framework/AzCore/AzCore/Math/PackedVector3.h index 88108350c8..9a9acacdf3 100644 --- a/Code/Framework/AzCore/AzCore/Math/PackedVector3.h +++ b/Code/Framework/AzCore/AzCore/Math/PackedVector3.h @@ -8,6 +8,7 @@ #pragma once #include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Math/Random.h b/Code/Framework/AzCore/AzCore/Math/Random.h index 3c87824b1d..4912d9ad29 100644 --- a/Code/Framework/AzCore/AzCore/Math/Random.h +++ b/Code/Framework/AzCore/AzCore/Math/Random.h @@ -9,8 +9,10 @@ #pragma once #include -#include +#include #include +#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Math/Vector2.h b/Code/Framework/AzCore/AzCore/Math/Vector2.h index bd20618f06..c667f48010 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector2.h +++ b/Code/Framework/AzCore/AzCore/Math/Vector2.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Math/Vector3.h b/Code/Framework/AzCore/AzCore/Math/Vector3.h index 4be70aa02e..6b7ded5641 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector3.h +++ b/Code/Framework/AzCore/AzCore/Math/Vector3.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h index 8ec55274f5..022025a3df 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h +++ b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h @@ -1006,12 +1006,6 @@ namespace AZ AZ_TYPE_INFO_INTERNAL_FUNCTION_VARIATION_SPECIALIZATION(AZStd::function, "{C9F9C644-CCC3-4F77-A792-F5B5DBCA746E}"); } // namespace AZ -#define AZ_TYPE_INFO_INTERNAL_1(_ClassName) static_assert(false, "You must provide a ClassName,ClassUUID") -#define AZ_TYPE_INFO_INTERNAL_2(_ClassName, _ClassUuid) \ - void TYPEINFO_Enable(){} \ - static const char* TYPEINFO_Name() { return #_ClassName; } \ - static const AZ::TypeId& TYPEINFO_Uuid() { static AZ::TypeId s_uuid(_ClassUuid); return s_uuid; } - // Template class type info #define AZ_TYPE_INFO_INTERNAL_TEMPLATE(_ClassName, _ClassUuid, ...)\ void TYPEINFO_Enable() {}\ @@ -1050,39 +1044,11 @@ namespace AZ #define AZ_TYPE_INFO_INTERNAL_17 AZ_TYPE_INFO_INTERNAL_TEMPLATE #define AZ_TYPE_INFO_INTERNAL(...) AZ_MACRO_SPECIALIZE(AZ_TYPE_INFO_INTERNAL_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) -#define AZ_TYPE_INFO_1 AZ_TYPE_INFO_INTERNAL_1 -#define AZ_TYPE_INFO_2 AZ_TYPE_INFO_INTERNAL_2 -#define AZ_TYPE_INFO_3 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_4 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_5 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_6 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_7 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_8 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_9 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_10 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_11 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_12 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_13 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_14 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_15 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_16 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_17 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED - // Fall-back for the original version of AZ_TYPE_INFO that accepted template arguments. This should not be used, unless // to fix issues where AZ_TYPE_INFO was incorrectly used and the old UUID has to be maintained. #define AZ_TYPE_INFO_LEGACY AZ_TYPE_INFO_INTERNAL -/** -* Use this macro inside a class to allow it to be identified across modules and serialized (in different contexts). -* The expected input is the class and the assigned uuid as a string or an instance of a uuid. -* Example: -* class MyClass -* { -* public: -* AZ_TYPE_INFO(MyClass, "{BD5B1568-D232-4EBF-93BD-69DB66E3773F}"); -* ... -*/ -#define AZ_TYPE_INFO(...) AZ_MACRO_SPECIALIZE(AZ_TYPE_INFO_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) +#include /** * Use this macro outside a class to allow it to be identified across modules and serialized (in different contexts). diff --git a/Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h b/Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h new file mode 100644 index 0000000000..4da514f931 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h @@ -0,0 +1,38 @@ +/* + * 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 AZ +{ + using TypeId = AZ::Uuid; +} + +#define AZ_TYPE_INFO_INTERNAL_1(_ClassName) static_assert(false, "You must provide a ClassName,ClassUUID") +#define AZ_TYPE_INFO_INTERNAL_2(_ClassName, _ClassUuid) \ + void TYPEINFO_Enable(){} \ + static const char* TYPEINFO_Name() { return #_ClassName; } \ + static const AZ::TypeId& TYPEINFO_Uuid() { static AZ::TypeId s_uuid(_ClassUuid); return s_uuid; } + +#define AZ_TYPE_INFO_1 AZ_TYPE_INFO_INTERNAL_1 +#define AZ_TYPE_INFO_2 AZ_TYPE_INFO_INTERNAL_2 + +/** +* Use this macro inside a class to allow it to be identified across modules and serialized (in different contexts). +* The expected input is the class and the assigned uuid as a string or an instance of a uuid. +* Example: +* class MyClass +* { +* public: +* AZ_TYPE_INFO(MyClass, "{BD5B1568-D232-4EBF-93BD-69DB66E3773F}"); +* ... +*/ +#define AZ_TYPE_INFO(...) AZ_MACRO_SPECIALIZE(AZ_TYPE_INFO_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) + diff --git a/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h b/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h index 41f0b129e2..0fc4c5b362 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h +++ b/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h @@ -9,7 +9,7 @@ #define AZCORE_DATA_OVERLAY_H #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h b/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h index eb7fd250d0..084e46194b 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h b/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h index f3da5d6b1c..4ba5c2b011 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h b/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h index b7a1989c83..4a22e84bad 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h @@ -10,7 +10,7 @@ #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 c33d678730..0c95b9d592 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -434,6 +434,7 @@ set(FILES Preprocessor/Sequences.h RTTI/RTTI.h RTTI/TypeInfo.h + RTTI/TypeInfoSimple.h RTTI/ReflectContext.h RTTI/ReflectContext.cpp RTTI/ReflectionManager.h diff --git a/Code/Framework/AzCore/AzCore/std/allocator.h b/Code/Framework/AzCore/AzCore/std/allocator.h index 0e024bbb5f..0fee5481e2 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator.h +++ b/Code/Framework/AzCore/AzCore/std/allocator.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/allocator_traits.h b/Code/Framework/AzCore/AzCore/std/allocator_traits.h index 227727f694..95e64bbc49 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_traits.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_traits.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/chrono/types.h b/Code/Framework/AzCore/AzCore/std/chrono/types.h index 19ef2c8469..ce42482132 100644 --- a/Code/Framework/AzCore/AzCore/std/chrono/types.h +++ b/Code/Framework/AzCore/AzCore/std/chrono/types.h @@ -10,7 +10,6 @@ #include #include -#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/containers/deque.h b/Code/Framework/AzCore/AzCore/std/containers/deque.h index 170f3316f0..215845a8f4 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/deque.h +++ b/Code/Framework/AzCore/AzCore/std/containers/deque.h @@ -5,14 +5,17 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ +#pragma once #ifndef AZSTD_DEQUE_H #define AZSTD_DEQUE_H 1 + #include #include #include #include #include +#include namespace AZStd { @@ -1242,4 +1245,3 @@ namespace AZStd } #endif // AZSTD_DEQUE_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/containers/list.h b/Code/Framework/AzCore/AzCore/std/containers/list.h index 4d78c01364..124d8b7d7c 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/list.h +++ b/Code/Framework/AzCore/AzCore/std/containers/list.h @@ -7,12 +7,14 @@ */ #ifndef AZSTD_LIST_H #define AZSTD_LIST_H 1 +#pragma once #include #include #include #include #include +#include namespace AZStd { @@ -1346,4 +1348,3 @@ namespace AZStd } #endif // AZSTD_LIST_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h index 31fbdd85e9..7e84124958 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h +++ b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h @@ -12,7 +12,6 @@ #include #include #include -//#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/containers/vector.h b/Code/Framework/AzCore/AzCore/std/containers/vector.h index 5c1c4da16c..bf02527d77 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/vector.h +++ b/Code/Framework/AzCore/AzCore/std/containers/vector.h @@ -5,13 +5,13 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_VECTOR_H -#define AZSTD_VECTOR_H 1 +#pragma once #include #include #include #include +#include namespace AZStd { @@ -1395,6 +1395,3 @@ namespace AZStd return removedCount; } } - -#endif // AZSTD_VECTOR_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/createdestroy.h b/Code/Framework/AzCore/AzCore/std/createdestroy.h index 94b86a58e4..0fa6e4ed40 100644 --- a/Code/Framework/AzCore/AzCore/std/createdestroy.h +++ b/Code/Framework/AzCore/AzCore/std/createdestroy.h @@ -16,6 +16,7 @@ #include #include #include +#include // AZStd::addressof namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/function/function_base.h b/Code/Framework/AzCore/AzCore/std/function/function_base.h index 409c3824a4..c1dd669f51 100644 --- a/Code/Framework/AzCore/AzCore/std/function/function_base.h +++ b/Code/Framework/AzCore/AzCore/std/function/function_base.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/function/function_template.h b/Code/Framework/AzCore/AzCore/std/function/function_template.h index 4f7d41dbd9..586b02e671 100644 --- a/Code/Framework/AzCore/AzCore/std/function/function_template.h +++ b/Code/Framework/AzCore/AzCore/std/function/function_template.h @@ -9,6 +9,7 @@ #include #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/hash_table.h b/Code/Framework/AzCore/AzCore/std/hash_table.h index c364720b3b..9a31020c49 100644 --- a/Code/Framework/AzCore/AzCore/std/hash_table.h +++ b/Code/Framework/AzCore/AzCore/std/hash_table.h @@ -7,7 +7,6 @@ */ #pragma once -#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/iterator.h b/Code/Framework/AzCore/AzCore/std/iterator.h index 6135b6f450..8d0d49b649 100644 --- a/Code/Framework/AzCore/AzCore/std/iterator.h +++ b/Code/Framework/AzCore/AzCore/std/iterator.h @@ -8,8 +8,9 @@ #pragma once #include -#include #include +#include +#include #include // use by ConstIteratorCast #include diff --git a/Code/Framework/AzCore/AzCore/std/parallel/atomic.h b/Code/Framework/AzCore/AzCore/std/parallel/atomic.h index 09b6f68166..8516dd976a 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/atomic.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/atomic.h @@ -8,8 +8,6 @@ #pragma once #include -#include -#include #include namespace AZStd diff --git a/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h b/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h index 20bc51a18b..9ee9b94fd0 100644 --- a/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h +++ b/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h @@ -5,8 +5,7 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_SMART_PTR_INTRUSIVE_PTR_H -#define AZSTD_SMART_PTR_INTRUSIVE_PTR_H +#pragma once // // intrusive_ptr.hpp @@ -19,10 +18,10 @@ // // See http://www.boost.org/libs/smart_ptr/intrusive_ptr.html for documentation. // - -#include #include +#include #include +#include namespace AZStd { @@ -112,7 +111,7 @@ namespace AZStd CountPolicy::add_ref(px); } } - + ~intrusive_ptr() { if (px != 0) @@ -120,7 +119,7 @@ namespace AZStd CountPolicy::release(px); } } - + template enable_if_t::value, intrusive_ptr&> operator=(intrusive_ptr const& rhs) { @@ -157,28 +156,28 @@ namespace AZStd this_type(rhs).swap(*this); return *this; } - + intrusive_ptr& operator=(T* rhs) { this_type(rhs).swap(*this); return *this; } - + void reset() { this_type().swap(*this); } - + void reset(T* rhs) { this_type(rhs).swap(*this); } - + T* get() const { return px; } - + T& operator*() const { AZ_Assert(px != 0, "You can't dereference a null pointer"); @@ -298,6 +297,3 @@ namespace AZStd // operator<< - not supported } // namespace AZStd - -#endif // #ifndef AZSTD_SMART_PTR_INTRUSIVE_PTR_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/string/string.h b/Code/Framework/AzCore/AzCore/std/string/string.h index 4d8fb0c5b5..ad3546ab09 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string.h +++ b/Code/Framework/AzCore/AzCore/std/string/string.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/string/string_view.h b/Code/Framework/AzCore/AzCore/std/string/string_view.h index a3d243dae7..9a98795554 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string_view.h +++ b/Code/Framework/AzCore/AzCore/std/string/string_view.h @@ -8,15 +8,16 @@ #pragma once #include -#include #include #include -#include + namespace AZStd { namespace StringInternal { + constexpr size_t min_size(size_t left, size_t right) { return (left < right) ? left : right; } + template constexpr SizeT char_find(const CharT* s, size_t count, CharT ch, SizeT npos = static_cast(-1)) noexcept { @@ -83,7 +84,7 @@ namespace AZStd } // Add one to offset so that for loop condition can check against 0 as the breakout condition - size_t lastIndex = (AZStd::min)(offset, size - count) + 1; + size_t lastIndex = StringInternal::min_size(offset, size - count) + 1; for (; lastIndex; --lastIndex) { @@ -576,7 +577,7 @@ namespace AZStd { return 0; } - size_type rlen = AZStd::min(count, size() - pos); + size_type rlen = StringInternal::min_size(count, size() - pos); Traits::copy(dest, data() + pos, rlen); return rlen; } @@ -584,12 +585,12 @@ namespace AZStd constexpr basic_string_view substr(size_type pos = 0, size_type count = npos) const { AZ_Assert(pos <= size(), "Cannot create substring where position is larger than size"); - return pos > size() ? basic_string_view() : basic_string_view(data() + pos, AZStd::min(count, size() - pos)); + return pos > size() ? basic_string_view() : basic_string_view(data() + pos, StringInternal::min_size(count, size() - pos)); } constexpr int compare(basic_string_view other) const { - size_t cmpSize = AZStd::min(size(), other.size()); + size_t cmpSize = StringInternal::min_size(size(), other.size()); int cmpval = cmpSize == 0 ? 0 : Traits::compare(data(), other.data(), cmpSize); if (cmpval == 0) { @@ -891,6 +892,8 @@ namespace AZStd return hash; } + template + struct hash; template struct hash> { diff --git a/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h b/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h index c6084e020e..64f923a40e 100644 --- a/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h +++ b/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h @@ -8,6 +8,7 @@ #pragma once #include +#include // for true_type namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h b/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h index 449c9d85c0..00a683b0a8 100644 --- a/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h +++ b/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h @@ -9,11 +9,12 @@ #include #include -#include +#include #include namespace AZStd { + using std::forward; // Extension: static_storage: Used to initialize statics in a thread-safe manner // These are similar to default_delete/no_delete, except they just invoke the destructor (or not) template diff --git a/Code/Framework/AzCore/AzCore/std/utils.h b/Code/Framework/AzCore/AzCore/std/utils.h index 0de56cedcb..4c918250de 100644 --- a/Code/Framework/AzCore/AzCore/std/utils.h +++ b/Code/Framework/AzCore/AzCore/std/utils.h @@ -23,7 +23,7 @@ #include #include -#include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h b/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h index 1478f663fa..3052c3f874 100644 --- a/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h +++ b/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace AZ::Platform { diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index d2cdac84c7..e6be83bde1 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -7,6 +7,7 @@ */ #include #include +#include #include #include diff --git a/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp b/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp index 6fe55b5672..c852fd35bb 100644 --- a/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp @@ -2051,10 +2051,11 @@ namespace UnitTest TEST_F(SmartPtr, IntrusivePtr_DynamicCast) { + AZStd::intrusive_ptr basePointer = new RefCountedSubclass; - AZStd::intrusive_ptr correctCast = dynamic_pointer_cast(basePointer); - AZStd::intrusive_ptr wrongCast = dynamic_pointer_cast(basePointer); + AZStd::intrusive_ptr correctCast = azdynamic_cast(basePointer); + AZStd::intrusive_ptr wrongCast = azdynamic_cast(basePointer); EXPECT_TRUE(correctCast.get() == basePointer.get()); EXPECT_TRUE(wrongCast.get() == nullptr); diff --git a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h index 3de63169b2..8866c1b74d 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h b/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h index aacf4303a7..2aadf9ae6c 100644 --- a/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h +++ b/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h @@ -7,7 +7,7 @@ */ #pragma once -#include +#include #include namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h index f83a042577..5340a1a344 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h index 25675e311a..6b5a4cd2a9 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h index e784c2339b..b6308e19e0 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h index 246059bde9..a6590d3702 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h b/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h index 092fcd7822..3097c18d60 100644 --- a/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h +++ b/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h index 0887754bdf..e174771c3b 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h @@ -11,6 +11,11 @@ #include #include +namespace AZ +{ + class SerializeContext; +} // namespace AZ + namespace AzFramework { //! Represents the camera state populated by the viewport camera. diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h index 1063709343..c0fa1ad631 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h @@ -11,7 +11,8 @@ #include #include #include -#include +#include +#include namespace AZ { diff --git a/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h b/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h index 021ca54cca..9962382f9f 100644 --- a/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h +++ b/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h index a05a57e138..be93e1af1a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h index 38bee8a1e5..56eaeb0f75 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h index 0ce80261ce..1cfb0dbe74 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h @@ -19,6 +19,7 @@ namespace AZ { class ReflectContext; + class SerializeContext; } namespace AzToolsFramework diff --git a/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h b/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h index a9c810c025..fef5f4d348 100644 --- a/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h +++ b/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h @@ -7,7 +7,7 @@ */ #pragma once -#include +#include #include //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h b/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h index 05fd3d73d7..70b10e915f 100644 --- a/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h +++ b/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h @@ -10,6 +10,7 @@ #if !defined(Q_MOC_RUN) #include +#include #include #endif diff --git a/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h b/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h index 99610467a6..dec4749e03 100644 --- a/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h +++ b/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h @@ -10,6 +10,7 @@ #if !defined(Q_MOC_RUN) #include "AssetDetailsPanel.h" +#include #include #endif diff --git a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h index e011bf213f..bef3cf0db4 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h @@ -7,6 +7,7 @@ */ #pragma once #include +#include struct aiNode; diff --git a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h index 5bb57a6167..5fe5b98243 100644 --- a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h +++ b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace AZ::SceneAPI::Utilities diff --git a/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h b/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h index 7bcb60d325..ddda2299d4 100644 --- a/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h +++ b/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h @@ -8,6 +8,7 @@ #pragma once #include +#include namespace AWSMetrics { diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h index 8d8700f284..6ec4641fd8 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include diff --git a/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp b/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp index fa665bb48f..84ee2a8ff8 100644 --- a/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp @@ -8,6 +8,7 @@ #include "RecentFiles.h" #include "CommonSettingsConfigurations.h" +#include #include #include From a7a0e8d2ef6778153deb28fedfc495832f162842 Mon Sep 17 00:00:00 2001 From: jonawals Date: Wed, 11 Aug 2021 02:43:44 +0100 Subject: [PATCH 234/251] Fix for PathLib unlink wrong version parameter. (#3020) * Fix for PathLib unlink wrong version parameter. * Fix dst target for TIAF. * Remove TIAF historic data arhciving on s3 buckets * Change permissions for TIAF bucket upload Signed-off-by: John --- scripts/build/Platform/Windows/build_config.json | 2 +- scripts/build/TestImpactAnalysis/git_utils.py | 4 +++- .../TestImpactAnalysis/tiaf_persistent_storage_s3.py | 9 +++------ 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index 8ac0b5241c..4c275a49cf 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/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" + "--config=\"!OUTPUT_DIRECTORY!/bin/TestImpactFramework/profile/Persistent/tiaf.json\" --src-branch=!BRANCH_NAME! --dst-branch=!CHANGE_TARGET! --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 04d994ba4a..3561b337f3 100644 --- a/scripts/build/TestImpactAnalysis/git_utils.py +++ b/scripts/build/TestImpactAnalysis/git_utils.py @@ -32,7 +32,9 @@ class Repo: try: # Remove the existing file (if any) and create the parent directory - output_path.unlink(missing_ok=True) + # output_path.unlink(missing_ok=True) # missing_ok is only available in Python 3.8+ + if output_path.is_file(): + output_path.unlink() output_path.parent.mkdir(exist_ok=True) except EnvironmentError as e: raise RuntimeError(f"Could not create path for output file '{output_path}'") diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py index 75c4bc93d5..09b4df0564 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py @@ -48,14 +48,11 @@ class PersistentStorageS3(PersistentStorage): 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 + logger.info(f"Attempting to decode historic data object...") response = object.get() file_stream = response['Body'] + logger.info(f"Decoding complete.") # Decompress and unpack the zipped historic data JSON historic_data_json = zlib.decompress(file_stream.read()).decode('UTF-8') @@ -79,7 +76,7 @@ class PersistentStorageS3(PersistentStorage): 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) + self._bucket.upload_fileobj(data, self._historic_data_key, ExtraArgs={'ACL': 'bucket-owner-full-control'}) logger.info("Upload complete.") except botocore.exceptions.BotoCoreError as e: logger.error(f"There was a problem with the s3 bucket: {e}") From fa2032d21d406b959f4c94025cb94f412807cde3 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 19:02:38 -0700 Subject: [PATCH 235/251] Linux fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/GameEngine.h | 1 + Code/Editor/Include/IObjectManager.h | 1 + Code/Editor/QtUtil.h | 1 + .../Platform/Linux/Launcher_Linux.cpp | 1 + Code/Legacy/CryCommon/AppleSpecific.h | 4 ---- Code/Legacy/CryCommon/CryThread_pthreads.h | 20 ------------------- Code/Legacy/CryCommon/LinuxSpecific.h | 16 +++++++++++++-- Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 2 -- Code/Legacy/CryCommon/VectorMap.h | 1 + 9 files changed, 19 insertions(+), 28 deletions(-) diff --git a/Code/Editor/GameEngine.h b/Code/Editor/GameEngine.h index 84df8bf002..829baec55a 100644 --- a/Code/Editor/GameEngine.h +++ b/Code/Editor/GameEngine.h @@ -20,6 +20,7 @@ #include "LogFile.h" #include "CryListenerSet.h" #include "Util/ModalWindowDismisser.h" +#include #endif class CStartupLogoDialog; diff --git a/Code/Editor/Include/IObjectManager.h b/Code/Editor/Include/IObjectManager.h index efc1955a56..360cc8fe34 100644 --- a/Code/Editor/Include/IObjectManager.h +++ b/Code/Editor/Include/IObjectManager.h @@ -12,6 +12,7 @@ #pragma once #include +#include #include #include #include diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h index bb1f8ba427..a16eb1e692 100644 --- a/Code/Editor/QtUtil.h +++ b/Code/Editor/QtUtil.h @@ -12,6 +12,7 @@ #include #include #include "UnicodeFunctions.h" +#include #include #include diff --git a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp index 1e87b902a6..3030dcc740 100644 --- a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp +++ b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp @@ -10,6 +10,7 @@ #include #include // for AZ_MAX_PATH_LEN +#include #include diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index 87aea0fbb5..df3b7578eb 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -355,13 +355,9 @@ enum #define wcsnicmp wcsncasecmp //#define memcpy_s(dest,bytes,src,n) memcpy(dest,src,n) #define _isnan ISNAN -#define _wtof(str) wcstod(str, 0) - #define TARGET_DEFAULT_ALIGN (0x8U) - - #define _msize malloc_size diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h index 2c6b389dbb..17f7e5d2a0 100644 --- a/Code/Legacy/CryCommon/CryThread_pthreads.h +++ b/Code/Legacy/CryCommon/CryThread_pthreads.h @@ -653,15 +653,9 @@ private: typedef CryEventTimed CryEvent; -#if !PLATFORM_SUPPORTS_THREADLOCAL -TLS_DECLARE(class CrySimpleThreadSelf*, g_CrySimpleThreadSelf); -#endif - class CrySimpleThreadSelf { protected: -#if PLATFORM_SUPPORTS_THREADLOCAL - static CrySimpleThreadSelf* GetSelf() { return m_Self; @@ -673,20 +667,6 @@ protected: } private: static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self; - -#else - - static CrySimpleThreadSelf* GetSelf() - { - return TLS_GET(CrySimpleThreadSelf*, g_CrySimpleThreadSelf); - } - - static void SetSelf(CrySimpleThreadSelf* pSelf) - { - TLS_SET(g_CrySimpleThreadSelf, pSelf); - } - -#endif }; template diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h index a587350cb2..112e965555 100644 --- a/Code/Legacy/CryCommon/LinuxSpecific.h +++ b/Code/Legacy/CryCommon/LinuxSpecific.h @@ -209,8 +209,20 @@ typedef unsigned long int threadID; #define wcsicmp wcscasecmp #define wcsnicmp wcsncasecmp - -#define _wtof(str) wcstod(str, 0) +typedef union _LARGE_INTEGER +{ + struct + { + DWORD LowPart; + LONG HighPart; + }; + struct + { + DWORD LowPart; + LONG HighPart; + } u; + long long QuadPart; +} LARGE_INTEGER; // stdlib.h stuff #define _MAX_DRIVE 3 // max. length of drive component diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 2de17e6b28..625add59ad 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -324,8 +324,6 @@ inline uint32 GetTickCount() #define _strlwr_s(BUF, SIZE) strlwr(BUF) #define _strups strupr -#define _wtof(str) wcstod(str, 0) - // Need to include this before using it's used in finddata, but after the strnicmp definition #include "CryString.h" diff --git a/Code/Legacy/CryCommon/VectorMap.h b/Code/Legacy/CryCommon/VectorMap.h index 1a42f0e48f..75b1562c4d 100644 --- a/Code/Legacy/CryCommon/VectorMap.h +++ b/Code/Legacy/CryCommon/VectorMap.h @@ -14,6 +14,7 @@ #define CRYINCLUDE_CRYCOMMON_VECTORMAP_H #pragma once +#include //-------------------------------------------------------------------------- // VectorMap From 2361490c8bf0f89d4e32b84e60aa7dcc10e85a64 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 20:18:59 -0700 Subject: [PATCH 236/251] Fixes for Android Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/platform.h | 2 +- .../AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 88d06c9b1e..030fd4186e 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -192,7 +192,7 @@ #else #if defined(WIN64) #include "Win64specific.h" - #elif defined(LINUX64) + #elif defined(LINUX64) && !defined(ANDROID) #include "Linux64Specific.h" #elif defined(MAC) #include "MacSpecific.h" diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index 7dd2629bd0..44de9656d2 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include From ccc4f27129a7a98fe7cab82eb66e44ac23ae9067 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Tue, 10 Aug 2021 21:09:55 -0700 Subject: [PATCH 237/251] Changed check for latest garbage to a for loop. Signed-off-by: dmcdiar --- Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h index 3f9fed056f..cd8a85a385 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h @@ -180,15 +180,16 @@ namespace AZ m_pendingGarbage.push_back({ AZStd::move(m_pendingObjects), m_currentIteration }); } - if (m_pendingNotifies.size()) + if (!m_pendingNotifies.empty()) { - if (m_pendingGarbage.size()) + if (!m_pendingGarbage.empty()) { // find the newest garbage entry and add any pending notifies Garbage& latestGarbage = m_pendingGarbage.front(); size_t latestGarbageAge = m_currentIteration - latestGarbage.m_collectIteration; - size_t i = 1; - while (i < m_pendingGarbage.size()) + + // check the rest of the entries to see if they are newer + for (size_t i = 1; i < m_pendingGarbage.size(); ++i) { size_t age = m_currentIteration - m_pendingGarbage[i].m_collectIteration; if (age < latestGarbageAge) From 6a5a7740ad59ef5db87ba08e2c4ceff74851d038 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Wed, 11 Aug 2021 00:45:27 -0700 Subject: [PATCH 238/251] EMotion FX: Selecting Motion Properties crashes the Editor (#3005) Signed-off-by: Benjamin Jillich --- Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp index 27f83b07a3..5e9cf66fa7 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp @@ -498,7 +498,7 @@ namespace MysticQt } if (findPreviousMaximizedDialogNeeded) { - for (auto curDialog = AZStd::make_reverse_iterator(dialog) + 1; curDialog != m_dialogs.rend(); ++curDialog) + for (auto curDialog = AZStd::make_reverse_iterator(dialog); curDialog != m_dialogs.rend(); ++curDialog) { if (curDialog->m_maximizeSize && curDialog->m_frame->isHidden() == false) { From 5c90bc0d58f359306352f845a094531b6e184c98 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Wed, 11 Aug 2021 00:45:47 -0700 Subject: [PATCH 239/251] Skip blend shapes that influence multiple meshes (#3009) Signed-off-by: Benjamin Jillich --- .../Source/RPI.Builders/Model/MorphTargetExporter.cpp | 11 ++++++++--- .../MeshOptimizer/MeshOptimizerComponent.cpp | 6 ++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp index 0a1fb49ab5..fa437c002f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp @@ -159,9 +159,14 @@ namespace AZ::RPI // Determine the vertex index range for the morph target. const uint32_t numVertices = blendShapeData->GetVertexCount(); - AZ_Assert(blendShapeData->GetVertexCount() == sourceMesh.m_meshData->GetVertexCount(), - "Blend shape (%s) contains more/less vertices (%d) than the neutral mesh (%d).", - blendShapeName.c_str(), numVertices, sourceMesh.m_meshData->GetVertexCount()); + if (blendShapeData->GetVertexCount() != sourceMesh.m_meshData->GetVertexCount()) + { + AZ_Error(ModelAssetBuilderComponent::s_builderName, false, + "Skipping blend shape (%s) as it contains more/less vertices (%d) than the neutral mesh (%d). " + "The blend shape is most likely influencing multiple meshes, which is currently not supported.", + blendShapeName.c_str(), numVertices, sourceMesh.m_meshData->GetVertexCount()); + return; + } // The start index is after any previously added deltas metaData.m_startIndex = aznumeric_cast(packedCompressedMorphTargetVertexData.size()); diff --git a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp index 7541e2fce7..a410c4e6c9 100644 --- a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp +++ b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp @@ -379,10 +379,12 @@ namespace AZ::SceneGenerationComponents auto [optimizedMesh, optimizedUVs, optimizedTangents, optimizedBitangents, optimizedVertexColors, optimizedSkinWeights] = OptimizeMesh(mesh, mesh, uvDatas, tangentDatas, bitangentDatas, colorDatas, skinWeightDatas, meshGroup, hasBlendShapes); - AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "Base mesh: %zu vertices, optimized mesh: %zu vertices, %0.02f%% of the original", + AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "Optimized mesh '%s': Original: %zu vertices -> optimized: %zu vertices, %0.02f%% of the original (hasBlendShapes=%s)", + graph.GetNodeName(nodeIndex).GetName(), mesh->GetUsedControlPointCount(), optimizedMesh->GetUsedControlPointCount(), - ((float)optimizedMesh->GetUsedControlPointCount() / (float)mesh->GetUsedControlPointCount()) * 100.0f + ((float)optimizedMesh->GetUsedControlPointCount() / (float)mesh->GetUsedControlPointCount()) * 100.0f, + hasBlendShapes ? "Yes" : "No" ); const NodeIndex optimizedMeshNodeIndex = graph.AddChild(graph.GetNodeParent(nodeIndex), name.c_str(), AZStd::move(optimizedMesh)); From da4dfea9caccf66a3a14072d27a64c66ec9250f5 Mon Sep 17 00:00:00 2001 From: AMZN-AlexOteiza <82234181+AMZN-AlexOteiza@users.noreply.github.com> Date: Wed, 11 Aug 2021 10:15:41 +0100 Subject: [PATCH 240/251] Adjustment to property row so the label is more visible (#2866) Signed-off-by: Garcia Ruiz Co-authored-by: Garcia Ruiz --- .../AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index 5ea36bb30e..05c04872e3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -70,7 +70,7 @@ namespace AzToolsFramework m_leftAreaContainer = new QWidget(this); m_middleAreaContainer = new QWidget(this); - const int minimumControlWidth = 192; + const int minimumControlWidth = 142; m_middleAreaContainer->setMinimumWidth(minimumControlWidth); m_mainLayout->addWidget(m_leftAreaContainer, LabelColumnStretch, Qt::AlignLeft); m_mainLayout->addWidget(m_middleAreaContainer, ValueColumnStretch); From 3845f430881bcd6770fca90c1c4425cf53d3700c Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 11 Aug 2021 08:13:38 -0700 Subject: [PATCH 241/251] missing header include after merge Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/std/string/conversions.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index b7887339e2..be71e12275 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include From fbcb6510e68721c19ac17c5618fd1d021514d901 Mon Sep 17 00:00:00 2001 From: sconel <32552662+sconel@users.noreply.github.com> Date: Wed, 11 Aug 2021 10:45:31 -0700 Subject: [PATCH 242/251] Update storage of Prefab Dom info to be best effort (#2862) * Update storage of Prefab Dom info to be best effort Signed-off-by: sconel * Update IssueReporter to Skipped instead of PartialSkip Signed-off-by: sconel * Address PR feedback Signed-off-by: sconel * Fix failing Prefab Unit Test that expected default values to be stripped Signed-off-by: sconel --- .../Instance/InstanceToTemplatePropagator.cpp | 20 +--- .../AzToolsFramework/Prefab/Link/Link.cpp | 3 +- .../Prefab/PrefabDomUtils.cpp | 94 +++++++++++++++---- .../AzToolsFramework/Prefab/PrefabDomUtils.h | 28 ++++-- .../AzToolsFramework/Prefab/PrefabLoader.cpp | 2 +- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 4 +- .../Prefab/Spawnable/EditorInfoRemover.cpp | 2 +- .../Prefab/Spawnable/SpawnableUtils.cpp | 2 +- ...refabInstanceToTemplatePropagatorTests.cpp | 93 ++++++++++++++++++ .../Tests/Prefab/PrefabTestComponent.cpp | 14 +++ .../Tests/Prefab/PrefabTestComponent.h | 18 ++++ .../Tests/Prefab/PrefabTestFixture.cpp | 1 + .../Prefab/PrefabUpdateWithPatchesTests.cpp | 5 +- .../Pipeline/NetworkPrefabProcessor.cpp | 2 +- 14 files changed, 241 insertions(+), 47 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index 814c4e2a7f..36b39f3a72 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -46,7 +46,6 @@ namespace AzToolsFramework bool InstanceToTemplatePropagator::GenerateDomForEntity(PrefabDom& generatedEntityDom, const AZ::Entity& entity) { - //grab the owning instance so we can use the entityIdMapper in settings InstanceOptionalReference owningInstance = m_instanceEntityMapperInterface->FindOwningInstance(entity.GetId()); if (!owningInstance) @@ -54,19 +53,8 @@ namespace AzToolsFramework AZ_Error("Prefab", false, "Entity does not belong to an instance"); return false; } - - InstanceEntityIdMapper entityIdMapper; - entityIdMapper.SetStoringInstance(owningInstance->get()); - - //create settings so that the serialized entity dom undergoes mapping from entity id to entity alias - AZ::JsonSerializerSettings settings; - settings.m_metadata.Add(static_cast(&entityIdMapper)); - - //generate PrefabDom using Json serialization system - AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store( - generatedEntityDom, generatedEntityDom.GetAllocator(), entity, settings); - return result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success; + return PrefabDomUtils::StoreEntityInPrefabDomFormat(entity, owningInstance->get(), generatedEntityDom); } bool InstanceToTemplatePropagator::GenerateDomForInstance(PrefabDom& generatedInstanceDom, const Prefab::Instance& instance) @@ -185,8 +173,10 @@ namespace AzToolsFramework else { AZ_Error( - "Prefab", result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::PartialSkip, - "Some of the patches are not successfully applied."); + "Prefab", + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::Skipped) && + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::PartialSkip), + "Some of the patches were not successfully applied."); m_prefabSystemComponentInterface->SetTemplateDirtyFlag(templateId, true); m_prefabSystemComponentInterface->PropagateTemplateChanges(templateId, instanceToExclude); return true; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index 3c7e5ff3f8..940a2787cb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -196,7 +196,8 @@ namespace AzToolsFramework m_sourceTemplateId, m_targetTemplateId); return false; } - if (applyPatchResult.GetOutcome() == AZ::JsonSerializationResult::Outcomes::PartialSkip) + if (applyPatchResult.GetOutcome() == AZ::JsonSerializationResult::Outcomes::PartialSkip || + applyPatchResult.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Skipped) { AZ_Error( "Prefab", false, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index 86983d7912..1ad88e53d2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp @@ -26,6 +26,30 @@ namespace AzToolsFramework { namespace PrefabDomUtils { + namespace Internal + { + AZ::JsonSerializationResult::ResultCode JsonIssueReporter(AZStd::string& scratchBuffer, + AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, AZStd::string_view path) + { + namespace JSR = AZ::JsonSerializationResult; + + if (result.GetProcessing() == JSR::Processing::Halted) + { + scratchBuffer.append(message.begin(), message.end()); + scratchBuffer.append("\n Reason: "); + result.AppendToString(scratchBuffer, path); + scratchBuffer.append("."); + AZ_Warning("Prefab Serialization", false, "%s", scratchBuffer.c_str()); + + scratchBuffer.clear(); + + return JSR::ResultCode(result.GetTask(), JSR::Outcomes::Skipped); + } + + return result; + } + } + PrefabDomValueReference FindPrefabDomValue(PrefabDomValue& parentValue, const char* valueName) { PrefabDomValue::MemberIterator valueIterator = parentValue.FindMember(valueName); @@ -48,7 +72,7 @@ namespace AzToolsFramework return valueIterator->value; } - bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreInstanceFlags flags) + bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreFlags flags) { InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetStoringInstance(instance); @@ -59,11 +83,21 @@ namespace AzToolsFramework settings.m_metadata.Add(static_cast(&entityIdMapper)); settings.m_metadata.Add(&entityIdMapper); - if ((flags & StoreInstanceFlags::StripDefaultValues) != StoreInstanceFlags::StripDefaultValues) + if ((flags & StoreFlags::StripDefaultValues) != StoreFlags::StripDefaultValues) { settings.m_keepDefaults = true; } + AZStd::string scratchBuffer; + auto issueReportingCallback = [&scratchBuffer] + (AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, + AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode + { + return Internal::JsonIssueReporter(scratchBuffer, message, result, path); + }; + + settings.m_reporting = AZStd::move(issueReportingCallback); + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), instance, settings); @@ -80,7 +114,38 @@ namespace AzToolsFramework return true; } - bool LoadInstanceFromPrefabDom(Instance& instance, const PrefabDom& prefabDom, LoadInstanceFlags flags) + bool StoreEntityInPrefabDomFormat(const AZ::Entity& entity, Instance& owningInstance, PrefabDom& prefabDom, StoreFlags flags) + { + InstanceEntityIdMapper entityIdMapper; + entityIdMapper.SetStoringInstance(owningInstance); + + //create settings so that the serialized entity dom undergoes mapping from entity id to entity alias + AZ::JsonSerializerSettings settings; + settings.m_metadata.Add(static_cast(&entityIdMapper)); + + if ((flags & StoreFlags::StripDefaultValues) != StoreFlags::StripDefaultValues) + { + settings.m_keepDefaults = true; + } + + AZStd::string scratchBuffer; + auto issueReportingCallback = [&scratchBuffer] + (AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, + AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode + { + return Internal::JsonIssueReporter(scratchBuffer, message, result, path); + }; + + settings.m_reporting = AZStd::move(issueReportingCallback); + + //generate PrefabDom using Json serialization system + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store( + prefabDom, prefabDom.GetAllocator(), entity, settings); + + return result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success; + } + + bool LoadInstanceFromPrefabDom(Instance& instance, const PrefabDom& prefabDom, LoadFlags flags) { // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload @@ -89,7 +154,7 @@ namespace AzToolsFramework InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetLoadingInstance(instance); - if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + if ((flags & LoadFlags::AssignRandomEntityId) == LoadFlags::AssignRandomEntityId) { entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); } @@ -119,7 +184,7 @@ namespace AzToolsFramework } bool LoadInstanceFromPrefabDom( - Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, LoadInstanceFlags flags) + Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, LoadFlags flags) { // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload @@ -128,7 +193,7 @@ namespace AzToolsFramework InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetLoadingInstance(instance); - if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + if ((flags & LoadFlags::AssignRandomEntityId) == LoadFlags::AssignRandomEntityId) { entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); } @@ -161,7 +226,7 @@ namespace AzToolsFramework } bool LoadInstanceFromPrefabDom( - Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, LoadInstanceFlags flags) + Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, LoadFlags flags) { // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload @@ -170,7 +235,7 @@ namespace AzToolsFramework InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetLoadingInstance(instance); - if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + if ((flags & LoadFlags::AssignRandomEntityId) == LoadFlags::AssignRandomEntityId) { entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); } @@ -240,15 +305,12 @@ namespace AzToolsFramework AZ::JsonSerializationResult::ResultCode ApplyPatches( PrefabDomValue& prefabDomToApplyPatchesOn, PrefabDom::AllocatorType& allocator, const PrefabDomValue& patches) { - auto issueReportingCallback = [](AZStd::string_view, AZ::JsonSerializationResult::ResultCode result, - AZStd::string_view) -> AZ::JsonSerializationResult::ResultCode + AZStd::string scratchBuffer; + auto issueReportingCallback = [&scratchBuffer] + (AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, + AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode { - using namespace AZ::JsonSerializationResult; - if (result.GetProcessing() == Processing::Halted) - { - return ResultCode(result.GetTask(), Outcomes::PartialSkip); - } - return result; + return Internal::JsonIssueReporter(scratchBuffer, message, result, path); }; AZ::JsonApplyPatchSettings applyPatchSettings; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h index e773b581dd..b04cf9f57d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h @@ -38,7 +38,7 @@ namespace AzToolsFramework PrefabDomValueReference FindPrefabDomValue(PrefabDomValue& parentValue, const char* valueName); PrefabDomValueConstReference FindPrefabDomValue(const PrefabDomValue& parentValue, const char* valueName); - enum class StoreInstanceFlags : uint8_t + enum class StoreFlags : uint8_t { //! No flags used during the call to LoadInstanceFromPrefabDom. None = 0, @@ -47,7 +47,7 @@ namespace AzToolsFramework //! such as saving to disk, this flag will control that behavior. StripDefaultValues = 1 << 0 }; - AZ_DEFINE_ENUM_BITWISE_OPERATORS(StoreInstanceFlags); + AZ_DEFINE_ENUM_BITWISE_OPERATORS(StoreFlags); /** * Stores a valid Prefab Instance within a Prefab Dom. Useful for generating Templates @@ -56,9 +56,21 @@ namespace AzToolsFramework * @param flags Controls behavior such as whether to store default values * @return bool on whether the operation succeeded */ - bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreInstanceFlags flags = StoreInstanceFlags::None); + bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreFlags flags = StoreFlags::None); - enum class LoadInstanceFlags : uint8_t + /** + * Stores a valid entity in Prefab Dom format. + * @param entity The entity to store + * @param owningInstance The instance owning the passed in entity. + * Used for contextualizing the entity's place in a Prefab hierarchy. + * @param prefabDom The prefabDom that will be used to store the entity data + * @param flags controls behavior such as whether to store default values + * @return bool on whether the operation succeeded + */ + bool StoreEntityInPrefabDomFormat(const AZ::Entity& entity, Instance& owningInstance, PrefabDom& prefabDom, + StoreFlags flags = StoreFlags::None); + + enum class LoadFlags : uint8_t { //! No flags used during the call to LoadInstanceFromPrefabDom. None = 0, @@ -66,7 +78,7 @@ namespace AzToolsFramework //! unique, e.g. when they are duplicates of live entities, this flag will assign them a random new id. AssignRandomEntityId = 1 << 0 }; - AZ_DEFINE_ENUM_BITWISE_OPERATORS(LoadInstanceFlags); + AZ_DEFINE_ENUM_BITWISE_OPERATORS(LoadFlags); /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. @@ -76,7 +88,7 @@ namespace AzToolsFramework * @return bool on whether the operation succeeded. */ bool LoadInstanceFromPrefabDom( - Instance& instance, const PrefabDom& prefabDom, LoadInstanceFlags flags = LoadInstanceFlags::None); + Instance& instance, const PrefabDom& prefabDom, LoadFlags flags = LoadFlags::None); /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. @@ -88,7 +100,7 @@ namespace AzToolsFramework */ bool LoadInstanceFromPrefabDom( Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, - LoadInstanceFlags flags = LoadInstanceFlags::None); + LoadFlags flags = LoadFlags::None); /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. @@ -101,7 +113,7 @@ namespace AzToolsFramework */ bool LoadInstanceFromPrefabDom( Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, - LoadInstanceFlags flags = LoadInstanceFlags::None); + LoadFlags flags = LoadFlags::None); inline PrefabDomPath GetPrefabDomInstancePath(const char* instanceName) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp index ea54c9d10c..5091a2d1bc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp @@ -328,7 +328,7 @@ namespace AzToolsFramework PrefabDom storedPrefabDom(&savingTemplateDom->get().GetAllocator()); if (!PrefabDomUtils::StoreInstanceInPrefabDom(savingPrefabInstance, storedPrefabDom, - PrefabDomUtils::StoreInstanceFlags::StripDefaultValues)) + PrefabDomUtils::StoreFlags::StripDefaultValues)) { return false; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index 955af18a66..fc64e0b5b3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -266,8 +266,8 @@ namespace AzToolsFramework AZ_Error( "Prefab", - result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::PartialSkip || - result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success, + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::Skipped) && + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::PartialSkip), "Some of the patches are not successfully applied."); //remove the link id placed into the instance diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp index 1d856fa395..dfba1d54ba 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp @@ -513,7 +513,7 @@ exportComponent, prefabProcessorContext); // convert Prefab DOM into Prefab Instance. AZStd::unique_ptr instance(aznew Instance()); if (!Prefab::PrefabDomUtils::LoadInstanceFromPrefabDom(*instance, prefab, - Prefab::PrefabDomUtils::LoadInstanceFlags::AssignRandomEntityId)) + Prefab::PrefabDomUtils::LoadFlags::AssignRandomEntityId)) { PrefabDomValueReference sourceReference = PrefabDomUtils::FindPrefabDomValue(prefab, PrefabDomUtils::SourceName); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp index 1373d2fa75..902f439280 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp @@ -30,7 +30,7 @@ namespace AzToolsFramework::Prefab::SpawnableUtils { Instance instance; if (Prefab::PrefabDomUtils::LoadInstanceFromPrefabDom(instance, prefabDom, referencedAssets, - Prefab::PrefabDomUtils::LoadInstanceFlags::AssignRandomEntityId)) // Always assign random entity ids because the spawnable is + Prefab::PrefabDomUtils::LoadFlags::AssignRandomEntityId)) // Always assign random entity ids because the spawnable is // going to be used to create clones of the entities. { AzFramework::Spawnable::EntityList& entities = spawnable.GetEntities(); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp index 8379992553..ebe35a5402 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -18,6 +19,98 @@ namespace UnitTest { using PrefabInstanceToTemplateTests = PrefabTestFixture; + TEST_F(PrefabInstanceToTemplateTests, GenerateEntityDom_InvalidType_InvalidTypeSkipped) + { + const char* newEntityName = "New Entity"; + AZ::Entity* newEntity = CreateEntity(newEntityName, false); + ASSERT_TRUE(newEntity); + + // Add a component with a member that is missing reflection info + // and a member that is properly reflected + PrefabTestComponentWithUnReflectedTypeMember* newComponent = + newEntity->CreateComponent(); + + ASSERT_TRUE(newComponent); + + AZStd::unique_ptr prefabInstance = m_prefabSystemComponent->CreatePrefab({ newEntity }, {}, "test/path"); + ASSERT_TRUE(prefabInstance); + + PrefabDom entityDom; + m_instanceToTemplateInterface->GenerateDomForEntity(entityDom, *newEntity); + + auto componentListDom = entityDom.FindMember("Components"); + + // Confirm that there is only one component in the entityDom + ASSERT_NE(componentListDom, entityDom.MemberEnd()); + ASSERT_TRUE(componentListDom->value.IsObject()); + ASSERT_EQ(componentListDom->value.MemberCount(), 1); + + auto testComponentDom = componentListDom->value.MemberBegin(); + ASSERT_TRUE(testComponentDom->value.IsObject()); + + // Confirm that the componentDom does not contained the invalid UnReflectedType + // We want to skip over it and produce a best effort entityDom + auto unReflectedTypeDom = testComponentDom->value.FindMember("UnReflectedType"); + ASSERT_EQ(unReflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the presence of the valid ReflectedType + auto reflectedTypeDom = testComponentDom->value.FindMember("ReflectedType"); + ASSERT_NE(reflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the reflected type has the correct type and value + ASSERT_TRUE(reflectedTypeDom->value.IsInt()); + EXPECT_EQ(reflectedTypeDom->value.GetInt(), newComponent->m_reflectedType); + } + + TEST_F(PrefabInstanceToTemplateTests, GenerateInstanceDom_InvalidType_InvalidTypeSkipped) + { + const char* newEntityName = "New Entity"; + AZ::Entity* newEntity = CreateEntity(newEntityName, false); + ASSERT_TRUE(newEntity); + + // Add a component with a member that is missing reflection info + // and a member that is properly reflected + PrefabTestComponentWithUnReflectedTypeMember* newComponent = + newEntity->CreateComponent(); + + ASSERT_TRUE(newComponent); + + AZStd::unique_ptr prefabInstance = m_prefabSystemComponent->CreatePrefab({ newEntity }, {}, "test/path"); + ASSERT_TRUE(prefabInstance); + + PrefabDom instanceDom; + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDom, *prefabInstance); + + // Acquire the entity out of the instanceDom + auto entitiesDom = instanceDom.FindMember(PrefabDomUtils::EntitiesName); + ASSERT_NE(entitiesDom, instanceDom.MemberEnd()); + ASSERT_EQ(entitiesDom->value.MemberCount(), 1); + + auto entityDom = entitiesDom->value.MemberBegin(); + auto componentListDom = entityDom->value.FindMember("Components"); + + // Confirm that there is only one component in the entityDom + ASSERT_NE(componentListDom, entityDom->value.MemberEnd()); + ASSERT_TRUE(componentListDom->value.IsObject()); + ASSERT_EQ(componentListDom->value.MemberCount(), 1); + + auto testComponentDom = componentListDom->value.MemberBegin(); + ASSERT_TRUE(testComponentDom->value.IsObject()); + + // Confirm that the componentDom does not contained the invalid UnReflectedType + // We want to skip over it and produce a best effort entityDom + auto unReflectedTypeDom = testComponentDom->value.FindMember("UnReflectedType"); + ASSERT_EQ(unReflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the presence of the valid ReflectedType + auto reflectedTypeDom = testComponentDom->value.FindMember("ReflectedType"); + ASSERT_NE(reflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the reflected type has the correct type and value + ASSERT_TRUE(reflectedTypeDom->value.IsInt()); + EXPECT_EQ(reflectedTypeDom->value.GetInt(), newComponent->m_reflectedType); + } + TEST_F(PrefabInstanceToTemplateTests, PrefabUpdateTemplate_UpdateEntityOnInstance) { //create template with single entity diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp index 8f7ee398a0..5d29b179c4 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp @@ -28,4 +28,18 @@ namespace UnitTest : m_boolProperty(boolProperty) { } + + void PrefabTestComponentWithUnReflectedTypeMember::Reflect(AZ::ReflectContext* reflection) + { + AZ::SerializeContext* serializeContext = AZ::RttiCast(reflection); + + // We reflect our member but not its type this will result in missing reflection data + // when we try to store or load this field + if (serializeContext) + { + serializeContext->Class() + ->Field("UnReflectedType", &PrefabTestComponentWithUnReflectedTypeMember::m_unReflectedType) + ->Field("ReflectedType", &PrefabTestComponentWithUnReflectedTypeMember::m_reflectedType); + } + } } diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h index 0ed8f6d9c9..e0e986b7db 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h @@ -27,4 +27,22 @@ namespace UnitTest int m_intProperty = 0; AZ::EntityId m_entityIdProperty; }; + + class UnReflectedType + { + public: + AZ_TYPE_INFO(UnReflectedType, "{FB65262C-CE9A-45CA-99EB-4DDCB19B32DB}"); + int m_unReflectedInt = 42; + }; + + class PrefabTestComponentWithUnReflectedTypeMember + : public AzToolsFramework::Components::EditorComponentBase + { + public: + AZ_EDITOR_COMPONENT(PrefabTestComponentWithUnReflectedTypeMember, "{726281E1-8E47-46AB-8018-D3F4BA823D74}"); + static void Reflect(AZ::ReflectContext* reflection); + + UnReflectedType m_unReflectedType; + int m_reflectedType = 52; + }; } diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp index ded88d2da3..ed30de09c4 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp @@ -49,6 +49,7 @@ namespace UnitTest EXPECT_TRUE(m_instanceToTemplateInterface); GetApplication()->RegisterComponentDescriptor(PrefabTestComponent::CreateDescriptor()); + GetApplication()->RegisterComponentDescriptor(PrefabTestComponentWithUnReflectedTypeMember::CreateDescriptor()); } AZStd::unique_ptr PrefabTestFixture::CreateTestApplication() diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp index 72e88c6336..c17763f778 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp @@ -136,7 +136,10 @@ namespace UnitTest PrefabDomValueReference wheelEntityComponentBoolPropertyValue = PrefabDomUtils::FindPrefabDomValue(wheelEntityComponentValue->get(), PrefabTestDomUtils::BoolPropertyName); - ASSERT_FALSE(wheelEntityComponentBoolPropertyValue.has_value()); + + ASSERT_TRUE(wheelEntityComponentBoolPropertyValue.has_value()); + ASSERT_TRUE(wheelEntityComponentBoolPropertyValue->get().IsBool()); + ASSERT_FALSE(wheelEntityComponentBoolPropertyValue->get().GetBool()); // Validate that the axles under the car have the same DOM as the axle template. PrefabTestDomUtils::ValidatePrefabDomInstances(axleInstanceAliasesUnderCar, carTemplateDom, axleTemplateDom); diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index d49f6901f3..acfec5eb38 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -56,7 +56,7 @@ namespace Multiplayer // convert Prefab DOM into Prefab Instance. AZStd::unique_ptr sourceInstance(aznew Instance()); - if (!PrefabDomUtils::LoadInstanceFromPrefabDom(*sourceInstance, prefab, PrefabDomUtils::LoadInstanceFlags::AssignRandomEntityId)) + if (!PrefabDomUtils::LoadInstanceFromPrefabDom(*sourceInstance, prefab, PrefabDomUtils::LoadFlags::AssignRandomEntityId)) { PrefabDomValueConstReference sourceReference = PrefabDomUtils::FindPrefabDomValue(prefab, PrefabDomUtils::SourceName); From 6d1bb8e439eb2b0b8aeaebd45e69115b156275f7 Mon Sep 17 00:00:00 2001 From: jromnoa <80134229+jromnoa@users.noreply.github.com> Date: Wed, 11 Aug 2021 11:19:22 -0700 Subject: [PATCH 243/251] Add Light component GPU (screenshot) test to AutomatedTesting nightly o3de runs. (#2923) * adds the Light component GPU screenshot test to AutomatedTesting Signed-off-by: jromnoa * add LIGHT_TYPE_PROPERTY constant to test script since it is re-used multiple times Signed-off-by: jromnoa * removes redundant f strings, adds LIGHT_COMPONENT and LIGHT_TYPE_PROPERTY constants for re-use, removed formattng errors, increase CMakeLists.txt timeout, add attach_component_to_entity() to hydra_editor_utils.py Signed-off-by: jromnoa * fix ImportError Signed-off-by: jromnoa * moves the LIGHT_TYPES constant to a new file since scripts rely on it that do not have the Editor launched (can't see hydra bindings so failes with ModuleNotFound error) Signed-off-by: jromnoa --- .../hydra_editor_utils.py | 30 ++ .../PythonTests/atom_renderer/CMakeLists.txt | 2 +- ...dra_AtomEditorComponents_LightComponent.py | 2 +- .../hydra_GPUTest_LightComponent.py | 268 ++++++++++++++++++ .../atom_utils/atom_component_helper.py | 191 ++++++++++++- .../atom_utils/atom_constants.py | 19 ++ .../atom_utils/screenshot_utils.py | 17 ++ .../golden_images/AreaLight_1.ppm | 3 + .../golden_images/AreaLight_2.ppm | 3 + .../golden_images/AreaLight_3.ppm | 3 + .../golden_images/AreaLight_4.ppm | 3 + .../golden_images/AreaLight_5.ppm | 3 + .../golden_images/SpotLight_1.ppm | 3 + .../golden_images/SpotLight_2.ppm | 3 + .../golden_images/SpotLight_3.ppm | 3 + .../golden_images/SpotLight_4.ppm | 3 + .../golden_images/SpotLight_5.ppm | 3 + .../golden_images/SpotLight_6.ppm | 3 + .../atom_renderer/test_Atom_GPUTests.py | 61 +++- .../atom_renderer/test_Atom_MainSuite.py | 2 +- 20 files changed, 607 insertions(+), 18 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py index cec1b6456b..985e32ede5 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py @@ -8,6 +8,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT import azlmbr.bus as bus import azlmbr.editor as editor import azlmbr.entity as entity +import azlmbr.legacy.general as general import azlmbr.object from typing import List @@ -428,3 +429,32 @@ def get_component_type_id_map(component_name_list): type_ids_by_component[component_names[i]] = typeId return type_ids_by_component + + +def attach_component_to_entity(entity_id, component_name): + # type: (azlmbr.entity.EntityId, str) -> azlmbr.entity.EntityComponentIdPair + """ + Adds the component if not added already. + :param entity_id: EntityId of the entity to attach the component to + :param component_name: name of the component + :return: If successful, returns the EntityComponentIdPair, otherwise returns None. + """ + type_ids_list = editor.EditorComponentAPIBus( + bus.Broadcast, 'FindComponentTypeIdsByEntityType', [component_name], 0) + general.log(f"Components found = {len(type_ids_list)}") + if len(type_ids_list) < 1: + general.log(f"ERROR: A component class with name {component_name} doesn't exist") + return None + elif len(type_ids_list) > 1: + general.log(f"ERROR: Found more than one component classes with same name: {component_name}") + return None + # Before adding the component let's check if it is already attached to the entity. + component_outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', entity_id, type_ids_list[0]) + if component_outcome.IsSuccess(): + return component_outcome.GetValue() # In this case the value is not a list. + component_outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', entity_id, type_ids_list) + if component_outcome.IsSuccess(): + general.log(f"{component_name} Component added to entity.") + return component_outcome.GetValue()[0] + general.log(f"ERROR: Failed to add component [{component_name}] to entity") + return None diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt index d4f036faeb..f056623ecd 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt @@ -39,7 +39,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedT TEST_SUITE main TEST_REQUIRES gpu TEST_SERIAL - TIMEOUT 800 + TIMEOUT 1200 PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_GPUTests.py RUNTIME_DEPENDENCIES AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py index ec8dc199ae..24866f3b19 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py @@ -19,7 +19,7 @@ import azlmbr.legacy.general as general sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) import editor_python_test_tools.hydra_editor_utils as hydra -from atom_renderer.atom_utils.atom_component_helper import LIGHT_TYPES +from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES LIGHT_TYPE_PROPERTY = 'Controller|Configuration|Light type' SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES = [ diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py new file mode 100644 index 0000000000..08f921e68b --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py @@ -0,0 +1,268 @@ +""" +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 + +Hydra script that is used to create an entity with a Light component attached. +It then updates the property values of the Light component and takes a screenshot. +The screenshot is compared against an expected golden image for test verification. + +See the run() function for more in-depth test info. +""" +import os +import sys + +import azlmbr.asset as asset +import azlmbr.bus as bus +import azlmbr.editor as editor +import azlmbr.math as math +import azlmbr.paths +import azlmbr.legacy.general as general + +sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) + +import editor_python_test_tools.hydra_editor_utils as hydra +from atom_renderer.atom_utils import screenshot_utils +from atom_renderer.atom_utils import atom_component_helper +from editor_python_test_tools.editor_test_helper import EditorTestHelper + +helper = EditorTestHelper(log_prefix="Atom_EditorTestHelper") + +LEVEL_NAME = "auto_test" +LIGHT_COMPONENT = "Light" +LIGHT_TYPE_PROPERTY = 'Controller|Configuration|Light type' +DEGREE_RADIAN_FACTOR = 0.0174533 + + +def run(): + """ + Sets up the tests by making sure the required level is created & setup correctly. + It then executes 2 test cases - see each associated test function's docstring for more info. + + Finally prints the string "Light component tests completed" after completion + + Tests will fail immediately if any of these log lines are found: + 1. Trace::Assert + 2. Trace::Error + 3. Traceback (most recent call last): + + :return: None + """ + atom_component_helper.create_basic_atom_level(level_name=LEVEL_NAME) + + # Run tests. + area_light_test() + spot_light_test() + general.log("Light component tests completed.") + + +def area_light_test(): + """ + Basic test for the "Light" component attached to an "area_light" entity. + + Test Case - Light Component: Capsule, Spot (disk), and Point (sphere): + 1. Creates "area_light" entity w/ a Light component that has a Capsule Light type w/ the color set to 255, 0, 0 + 2. Enters game mode to take a screenshot for comparison, then exits game mode. + 3. Sets the Light component Intensity Mode to Lumens (default). + 4. Ensures the Light component Mode is Automatic (default). + 5. Sets the Intensity value of the Light component to 0.0 + 6. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 7. Updates the Intensity value of the Light component to 1000.0 + 8. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 9. Swaps the Capsule light type option to Spot (disk) light type on the Light component + 10. Updates "area_light" entity Transform rotate value to x: 90.0, y:0.0, z:0.0 + 11. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 12. Swaps the Spot (disk) light type for the Point (sphere) light type in the Light component. + 13. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 14. Deletes the Light component from the "area_light" entity and verifies its successful. + """ + # Create an "area_light" entity with "Light" component using Light type of "Capsule" + area_light_entity_name = "area_light" + area_light = hydra.Entity(area_light_entity_name) + area_light.create_entity(math.Vector3(-1.0, -2.0, 3.0), [LIGHT_COMPONENT]) + general.log( + f"{area_light_entity_name}_test: Component added to the entity: " + f"{hydra.has_components(area_light.id, [LIGHT_COMPONENT])}") + light_component_id_pair = hydra.attach_component_to_entity(area_light.id, LIGHT_COMPONENT) + + # Select the "Capsule" light type option. + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['capsule'] + ) + + # Update color and take screenshot in game mode + color = math.Color(255.0, 0.0, 0.0, 0.0) + area_light.get_set_test(0, "Controller|Configuration|Color", color) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_1", area_light_entity_name) + + # Update intensity value to 0.0 and take screenshot in game mode + area_light.get_set_test(0, "Controller|Configuration|Attenuation Radius|Mode", 1) + area_light.get_set_test(0, "Controller|Configuration|Intensity", 0.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_2", area_light_entity_name) + + # Update intensity value to 1000.0 and take screenshot in game mode + area_light.get_set_test(0, "Controller|Configuration|Intensity", 1000.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_3", area_light_entity_name) + + # Swap the "Capsule" light type option to "Spot (disk)" light type + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['spot_disk'] + ) + area_light_rotation = math.Vector3(DEGREE_RADIAN_FACTOR * 90.0, 0.0, 0.0) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", area_light.id, area_light_rotation) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_4", area_light_entity_name) + + # Swap the "Spot (disk)" light type to the "Point (sphere)" light type and take screenshot. + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['sphere'] + ) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_5", area_light_entity_name) + + editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntityById", area_light.id) + + +def spot_light_test(): + """ + Basic test for the Light component attached to a "spot_light" entity. + + Test Case - Light Component: Spot (disk) with shadows & colors: + 1. Creates "spot_light" entity w/ a Light component attached to it. + 2. Selects the "directional_light" entity already present in the level and disables it. + 3. Selects the "global_skylight" entity already present in the level and disables the HDRi Skybox component, + as well as the Global Skylight (IBL) component. + 4. Enters game mode to take a screenshot for comparison, then exits game mode. + 5. Selects the "ground_plane" entity and changes updates the material to a new material. + 6. Enters game mode to take a screenshot for comparison, then exits game mode. + 7. Selects the "spot_light" entity and increases the Light component Intensity to 800 lm + 8. Enters game mode to take a screenshot for comparison, then exits game mode. + 9. Selects the "spot_light" entity and sets the Light component Color to 47, 75, 37 + 10. Enters game mode to take a screenshot for comparison, then exits game mode. + 11. Selects the "spot_light" entity and modifies the Shutter controls to the following values: + - Enable shutters: True + - Inner Angle: 60.0 + - Outer Angle: 75.0 + 12. Enters game mode to take a screenshot for comparison, then exits game mode. + 13. Selects the "spot_light" entity and modifies the Shadow controls to the following values: + - Enable Shadow: True + - ShadowmapSize: 256 + 14. Modifies the world translate position of the "spot_light" entity to 0.7, -2.0, 1.9 (for casting shadows better) + 15. Enters game mode to take a screenshot for comparison, then exits game mode. + """ + # Disable "Directional Light" component for the "directional_light" entity + # "directional_light" entity is created by the create_basic_atom_level() function by default. + directional_light_entity_id = hydra.find_entity_by_name("directional_light") + directional_light = hydra.Entity(name='directional_light', id=directional_light_entity_id) + directional_light_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Directional Light"], 0)[0] + directional_light_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', directional_light.id, directional_light_component_type + ).GetValue() + editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [directional_light_component]) + general.idle_wait(0.5) + + # Disable "Global Skylight (IBL)" and "HDRi Skybox" components for the "global_skylight" entity + global_skylight_entity_id = hydra.find_entity_by_name("global_skylight") + global_skylight = hydra.Entity(name='global_skylight', id=global_skylight_entity_id) + global_skylight_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Global Skylight (IBL)"], 0)[0] + global_skylight_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', global_skylight.id, global_skylight_component_type + ).GetValue() + editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [global_skylight_component]) + hdri_skybox_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["HDRi Skybox"], 0)[0] + hdri_skybox_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', global_skylight.id, hdri_skybox_component_type + ).GetValue() + editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [hdri_skybox_component]) + general.idle_wait(0.5) + + # Create a "spot_light" entity with "Light" component using Light Type of "Spot (disk)" + spot_light_entity_name = "spot_light" + spot_light = hydra.Entity(spot_light_entity_name) + spot_light.create_entity(math.Vector3(0.7, -2.0, 1.0), [LIGHT_COMPONENT]) + general.log( + f"{spot_light_entity_name}_test: Component added to the entity: " + f"{hydra.has_components(spot_light.id, [LIGHT_COMPONENT])}") + rotation = math.Vector3(DEGREE_RADIAN_FACTOR * 300.0, 0.0, 0.0) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", spot_light.id, rotation) + light_component_type = hydra.attach_component_to_entity(spot_light.id, LIGHT_COMPONENT) + editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_type, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['spot_disk'] + ) + + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_1", spot_light_entity_name) + + # Change default material of ground plane entity and take screenshot + ground_plane_entity_id = hydra.find_entity_by_name("ground_plane") + ground_plane = hydra.Entity(name='ground_plane', id=ground_plane_entity_id) + ground_plane_asset_path = os.path.join("Materials", "Presets", "MacBeth", "22_neutral_5-0_0-70d.azmaterial") + ground_plane_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", ground_plane_asset_path, math.Uuid(), False) + material_property_path = "Default Material|Material Asset" + material_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Material"], 0)[0] + material_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', ground_plane.id, material_component_type).GetValue() + editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + material_component, + material_property_path, + ground_plane_asset_value + ) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_2", spot_light_entity_name) + + # Increase intensity value of the Spot light and take screenshot in game mode + spot_light.get_set_test(0, "Controller|Configuration|Intensity", 800.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_3", spot_light_entity_name) + + # Update the Spot light color and take screenshot in game mode + color_value = math.Color(47.0 / 255.0, 75.0 / 255.0, 37.0 / 255.0, 255.0 / 255.0) + spot_light.get_set_test(0, "Controller|Configuration|Color", color_value) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_4", spot_light_entity_name) + + # Update the Shutter controls of the Light component and take screenshot + spot_light.get_set_test(0, "Controller|Configuration|Shutters|Enable shutters", True) + spot_light.get_set_test(0, "Controller|Configuration|Shutters|Inner angle", 60.0) + spot_light.get_set_test(0, "Controller|Configuration|Shutters|Outer angle", 75.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_5", spot_light_entity_name) + + # Update the Shadow controls, move the spot_light entity world translate position and take screenshot + spot_light.get_set_test(0, "Controller|Configuration|Shadows|Enable shadow", True) + spot_light.get_set_test(0, "Controller|Configuration|Shadows|Shadowmap size", 256.0) + azlmbr.components.TransformBus( + azlmbr.bus.Event, "SetWorldTranslation", spot_light.id, math.Vector3(0.7, -2.0, 1.9)) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_6", spot_light_entity_name) + + +if __name__ == "__main__": + run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py index de4e28bb36..58b72ef01a 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py @@ -3,17 +3,184 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright SPDX-License-Identifier: Apache-2.0 OR MIT -File to assist with common hydra component functions or constants used across various Atom tests. +File to assist with common hydra component functions used across various Atom tests. """ +import os -# Light type options for the Light component. -LIGHT_TYPES = { - 'unknown': 0, - 'sphere': 1, - 'spot_disk': 2, - 'capsule': 3, - 'quad': 4, - 'polygon': 5, - 'simple_point': 6, - 'simple_spot': 7, -} +from editor_python_test_tools.editor_test_helper import EditorTestHelper + +helper = EditorTestHelper(log_prefix="Atom_EditorTestHelper") + + +def create_basic_atom_level(level_name): + """ + Creates a new level inside the Editor matching level_name & adds the following: + 1. "default_level" entity to hold all other entities. + 2. Adds Grid, Global Skylight (IBL), ground Mesh, Directional Light, Sphere w/ material+mesh, & Camera components. + 3. Each of these components has its settings tweaked slightly to match the ideal scene to test Atom rendering. + :param level_name: name of the level to create and apply this basic setup to. + :return: None + """ + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.camera as camera + import azlmbr.editor as editor + import azlmbr.entity as entity + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.object + + import editor_python_test_tools.hydra_editor_utils as hydra + + # Create a new level. + new_level_name = level_name + heightmap_resolution = 512 + heightmap_meters_per_pixel = 1 + terrain_texture_resolution = 412 + use_terrain = False + + # Return codes are ECreateLevelResult defined in CryEdit.h + return_code = general.create_level_no_prompt( + new_level_name, heightmap_resolution, heightmap_meters_per_pixel, terrain_texture_resolution, use_terrain) + if return_code == 1: + general.log(f"{new_level_name} level already exists") + elif return_code == 2: + general.log("Failed to create directory") + elif return_code == 3: + general.log("Directory length is too long") + elif return_code != 0: + general.log("Unknown error, failed to create level") + else: + general.log(f"{new_level_name} level created successfully") + + # Enable idle and update viewport. + general.idle_enable(True) + general.idle_wait(1.0) + general.update_viewport() + general.idle_wait(0.5) # half a second is more than enough for updating the viewport. + + # Close out problematic windows, FPS meters, and anti-aliasing. + if general.is_helpers_shown(): # Turn off the helper gizmos if visible + general.toggle_helpers() + general.idle_wait(1.0) + if general.is_pane_visible("Error Report"): # Close Error Report windows that block focus. + general.close_pane("Error Report") + if general.is_pane_visible("Error Log"): # Close Error Log windows that block focus. + general.close_pane("Error Log") + general.idle_wait(1.0) + general.run_console("r_displayInfo=0") + general.run_console("r_antialiasingmode=0") + general.idle_wait(1.0) + + # Delete all existing entities & create default_level entity + search_filter = azlmbr.entity.SearchFilter() + all_entities = entity.SearchBus(azlmbr.bus.Broadcast, "SearchEntities", search_filter) + editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntities", all_entities) + default_level = hydra.Entity("default_level") + default_position = math.Vector3(0.0, 0.0, 0.0) + default_level.create_entity(default_position, ["Grid"]) + default_level.get_set_test(0, "Controller|Configuration|Secondary Grid Spacing", 1.0) + + # Set the viewport up correctly after adding the parent default_level entity. + screen_width = 1280 + screen_height = 720 + degree_radian_factor = 0.0174533 # Used by "Rotation" property for the Transform component. + general.set_viewport_size(screen_width, screen_height) + general.update_viewport() + helper.wait_for_condition( + function=lambda: helper.isclose(a=general.get_viewport_size().x, b=screen_width, rel_tol=0.1) + and helper.isclose(a=general.get_viewport_size().y, b=screen_height, rel_tol=0.1), + timeout_in_seconds=4.0 + ) + result = helper.isclose(a=general.get_viewport_size().x, b=screen_width, rel_tol=0.1) and helper.isclose( + a=general.get_viewport_size().y, b=screen_height, rel_tol=0.1) + general.log(general.get_viewport_size().x) + general.log(general.get_viewport_size().y) + general.log(general.get_viewport_size().z) + general.log(f"Viewport is set to the expected size: {result}") + general.log("Basic level created") + general.run_console("r_DisplayInfo = 0") + + # Create global_skylight entity and set the properties + global_skylight = hydra.Entity("global_skylight") + global_skylight.create_entity( + entity_position=default_position, + components=["HDRi Skybox", "Global Skylight (IBL)"], + parent_id=default_level.id) + global_skylight_asset_path = os.path.join( + "LightingPresets", "greenwich_park_02_4k_iblskyboxcm_iblspecular.exr.streamingimage") + global_skylight_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", global_skylight_asset_path, math.Uuid(), False) + global_skylight.get_set_test(0, "Controller|Configuration|Cubemap Texture", global_skylight_asset_value) + global_skylight.get_set_test(1, "Controller|Configuration|Diffuse Image", global_skylight_asset_value) + global_skylight.get_set_test(1, "Controller|Configuration|Specular Image", global_skylight_asset_value) + + # Create ground_plane entity and set the properties + ground_plane = hydra.Entity("ground_plane") + ground_plane.create_entity( + entity_position=default_position, + components=["Material"], + parent_id=default_level.id) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalUniformScale", ground_plane.id, 32.0) + ground_plane_material_asset_path = os.path.join( + "Materials", "Presets", "PBR", "metal_chrome.azmaterial") + ground_plane_material_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", ground_plane_material_asset_path, math.Uuid(), False) + ground_plane.get_set_test(0, "Default Material|Material Asset", ground_plane_material_asset_value) + + # Work around to add the correct Atom Mesh component + mesh_type_id = azlmbr.globals.property.EditorMeshComponentTypeId + ground_plane.components.append( + editor.EditorComponentAPIBus( + bus.Broadcast, "AddComponentsOfType", ground_plane.id, [mesh_type_id] + ).GetValue()[0] + ) + ground_plane_mesh_asset_path = os.path.join("Models", "plane.azmodel") + ground_plane_mesh_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", ground_plane_mesh_asset_path, math.Uuid(), False) + ground_plane.get_set_test(1, "Controller|Configuration|Mesh Asset", ground_plane_mesh_asset_value) + + # Create directional_light entity and set the properties + directional_light = hydra.Entity("directional_light") + directional_light.create_entity( + entity_position=math.Vector3(0.0, 0.0, 10.0), + components=["Directional Light"], + parent_id=default_level.id) + directional_light_rotation = math.Vector3(degree_radian_factor * -90.0, 0.0, 0.0) + azlmbr.components.TransformBus( + azlmbr.bus.Event, "SetLocalRotation", directional_light.id, directional_light_rotation) + + # Create sphere entity and set the properties + sphere_entity = hydra.Entity("sphere") + sphere_entity.create_entity( + entity_position=math.Vector3(0.0, 0.0, 1.0), + components=["Material"], + parent_id=default_level.id) + sphere_material_asset_path = os.path.join("Materials", "Presets", "PBR", "metal_brass_polished.azmaterial") + sphere_material_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", sphere_material_asset_path, math.Uuid(), False) + sphere_entity.get_set_test(0, "Default Material|Material Asset", sphere_material_asset_value) + + # Work around to add the correct Atom Mesh component + sphere_entity.components.append( + editor.EditorComponentAPIBus( + bus.Broadcast, "AddComponentsOfType", sphere_entity.id, [mesh_type_id] + ).GetValue()[0] + ) + sphere_mesh_asset_path = os.path.join("Models", "sphere.azmodel") + sphere_mesh_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", sphere_mesh_asset_path, math.Uuid(), False) + sphere_entity.get_set_test(1, "Controller|Configuration|Mesh Asset", sphere_mesh_asset_value) + + # Create camera component and set the properties + camera_entity = hydra.Entity("camera") + camera_entity.create_entity( + entity_position=math.Vector3(5.5, -12.0, 9.0), + components=["Camera"], + parent_id=default_level.id) + rotation = math.Vector3( + degree_radian_factor * -27.0, degree_radian_factor * -12.0, degree_radian_factor * 25.0 + ) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", camera_entity.id, rotation) + camera_entity.get_set_test(0, "Controller|Configuration|Field of view", 60.0) + camera.EditorCameraViewRequestBus(azlmbr.bus.Event, "ToggleCameraAsActiveView", camera_entity.id) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py new file mode 100644 index 0000000000..88a959f198 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py @@ -0,0 +1,19 @@ +""" +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 + +Hold constants used across both hydra and non-hydra scripts. +""" + +# Light type options for the Light component. +LIGHT_TYPES = { + 'unknown': 0, + 'sphere': 1, + 'spot_disk': 2, + 'capsule': 3, + 'quad': 4, + 'polygon': 5, + 'simple_point': 6, + 'simple_spot': 7, +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py index 28a4037dcc..a7a02816ac 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py @@ -91,3 +91,20 @@ class ScreenshotHelper(object): else: frames_waited = frames_waited + 1 general.log(f"(waited {frames_waited} frames)") + + +def take_screenshot_game_mode(screenshot_name, entity_name=None): + """ + Enters game mode & takes a screenshot, then exits game mode after. + :param screenshot_name: name to give the captured screenshot .ppm file. + :param entity_name: name of the entity being tested (for generating unique log lines). + :return: None + """ + general.enter_game_mode() + helper.wait_for_condition(lambda: general.is_in_game_mode(), 2.0) + general.log(f"{entity_name}_test: Entered game mode: {general.is_in_game_mode()}") + ScreenshotHelper(general.idle_wait_frames).capture_screenshot_blocking(f"{screenshot_name}.ppm") + general.idle_wait(1.0) + general.exit_game_mode() + helper.wait_for_condition(lambda: not general.is_in_game_mode(), 2.0) + general.log(f"{entity_name}_test: Exit game mode: {not general.is_in_game_mode()}") diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm new file mode 100644 index 0000000000..0725999dcf --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:954d7d0df47c840a24e313893800eb3126d0c0d47c3380926776b51833778db7 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm new file mode 100644 index 0000000000..3a45bd31e3 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e81c19128f42ba362a2d5f3ccf159dfbc942d67ceeb1ac8c21f295a6fd9d2ce5 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm new file mode 100644 index 0000000000..15d679b784 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e20801213e065b6ea8c95ede81c23faa9b6dc70a2002dc5bced293e1bed989f +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm new file mode 100644 index 0000000000..85c083a386 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e250f812e594e5152bf2d6f23caa8b53b78276bfdf344d7a8d355dd96cb995c0 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm new file mode 100644 index 0000000000..d575de761e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95be359041f8291c74b335297a4dfe9902a180510f24a181b15e1a5ba4d3b024 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm new file mode 100644 index 0000000000..bbbd127929 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:118e43e4b915e262726183467cc4b82f244565213fea5b6bfe02be07f0851ab1 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm new file mode 100644 index 0000000000..8e716fabcc --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc2ce3256a6552975962c9e113c52c1a22bf3817d417151f6f60640dd568e0fa +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm new file mode 100644 index 0000000000..6b6a5a5d6e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:287d98890b35427688999760f9d066bcbff1a3bc9001534241dc212b32edabd8 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm new file mode 100644 index 0000000000..eb05228cc2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66e91c92c868167c850078cd91714db47e10a96e23cc30191994486bd79c353f +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm new file mode 100644 index 0000000000..5e12edc46d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d950d173f5101820c5e18205401ca08ce5feeff2302ac2920b292750d86a8fa4 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm new file mode 100644 index 0000000000..d442d90287 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72eddb7126eae0c839b933886e0fb69d78229f72d49ef13199de28df2b7879db +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py index 9165bced90..7be1ed1b12 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py @@ -15,11 +15,11 @@ import pytest import ly_test_tools.environment.file_system as file_system from ly_test_tools.image.screenshot_compare_qssim import qssim as compare_screenshots from ly_test_tools.benchmark.data_aggregator import BenchmarkDataAggregator + import editor_python_test_tools.hydra_test_utils as hydra logger = logging.getLogger(__name__) DEFAULT_SUBFOLDER_PATH = 'user/PythonTests/Automated/Screenshots' -EDITOR_TIMEOUT = 600 TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts") @@ -67,6 +67,7 @@ class TestAllComponentsIndepthTests(object): "Trace::Assert", "Trace::Error", "Traceback (most recent call last):", + "Screenshot failed" ] hydra.launch_and_validate_results( @@ -74,7 +75,7 @@ class TestAllComponentsIndepthTests(object): TEST_DIRECTORY, editor, "hydra_GPUTest_BasicLevelSetup.py", - timeout=EDITOR_TIMEOUT, + timeout=180, expected_lines=level_creation_expected_lines, unexpected_lines=unexpected_lines, halt_on_unexpected=True, @@ -85,6 +86,60 @@ class TestAllComponentsIndepthTests(object): for test_screenshot, golden_screenshot in zip(test_screenshots, golden_images): compare_screenshots(test_screenshot, golden_screenshot) + def test_LightComponent_ScreenshotMatchesGoldenImage( + self, request, editor, workspace, project, launcher_platform, level): + """ + Please review the hydra script run by this test for more specific test info. + Tests that the Light component screenshots in a rendered level appear the same as the golden images. + """ + screenshot_names = [ + "AreaLight_1.ppm", + "AreaLight_2.ppm", + "AreaLight_3.ppm", + "AreaLight_4.ppm", + "AreaLight_5.ppm", + "SpotLight_1.ppm", + "SpotLight_2.ppm", + "SpotLight_3.ppm", + "SpotLight_4.ppm", + "SpotLight_5.ppm", + "SpotLight_6.ppm", + ] + test_screenshots = [] + for screenshot in screenshot_names: + screenshot_path = os.path.join(workspace.paths.project(), DEFAULT_SUBFOLDER_PATH, screenshot) + test_screenshots.append(screenshot_path) + file_system.delete(test_screenshots, True, True) + + golden_images = [] + for golden_image in screenshot_names: + golden_image_path = os.path.join(golden_images_directory(), golden_image) + golden_images.append(golden_image_path) + + expected_lines = ["Light component tests completed."] + unexpected_lines = [ + "Trace::Assert", + "Trace::Error", + "Traceback (most recent call last):", + "Screenshot failed", + ] + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "hydra_GPUTest_LightComponent.py", + timeout=180, + expected_lines=expected_lines, + unexpected_lines=unexpected_lines, + halt_on_unexpected=True, + cfg_args=[level], + null_renderer=False, + ) + + for test_screenshot, golden_screenshot in zip(test_screenshots, golden_images): + compare_screenshots(test_screenshot, golden_screenshot) + + @pytest.mark.parametrize('rhi', ['dx12', 'vulkan']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.parametrize("launcher_platform", ["windows_editor"]) @@ -116,7 +171,7 @@ class TestPerformanceBenchmarkSuite(object): TEST_DIRECTORY, editor, "hydra_GPUTest_AtomFeatureIntegrationBenchmark.py", - timeout=EDITOR_TIMEOUT, + timeout=600, expected_lines=expected_lines, unexpected_lines=unexpected_lines, halt_on_unexpected=True, diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index 98d2ba0632..39689816b8 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -12,7 +12,7 @@ import os import pytest import editor_python_test_tools.hydra_test_utils as hydra -from atom_renderer.atom_utils.atom_component_helper import LIGHT_TYPES +from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES logger = logging.getLogger(__name__) EDITOR_TIMEOUT = 120 From 2564e8f8dce6fc65804500dee166f72a574477f9 Mon Sep 17 00:00:00 2001 From: smurly Date: Wed, 11 Aug 2021 12:15:31 -0700 Subject: [PATCH 244/251] MaterialEditor BasicTests added to AutomatedTesting for AR (#3022) * MaterialEditor BasicTests added to AutomatedTesting for AR Signed-off-by: Scott Murray * launch_and_validate_results adding a waiter.wait_for to the log monitor so the log file exists Signed-off-by: Scott Murray --- .../AssetProcessorGamePlatformConfig.setreg | 19 ++ .../hydra_test_utils.py | 15 +- .../hydra_AtomMaterialEditor_BasicTests.py | 183 ++++++++++++ .../atom_utils/material_editor_utils.py | 274 ++++++++++++++++++ .../atom_renderer/test_Atom_MainSuite.py | 63 ++++ 5 files changed, 552 insertions(+), 2 deletions(-) create mode 100644 AutomatedTesting/AssetProcessorGamePlatformConfig.setreg create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py diff --git a/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg b/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg new file mode 100644 index 0000000000..5457b3f1ca --- /dev/null +++ b/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg @@ -0,0 +1,19 @@ +{ + "Amazon": { + "AssetProcessor": { + "Settings": { + "RC cgf": { + "ignore": true + }, + "RC fbx": { + "ignore": true + }, + "ScanFolder AtomTestData": { + "watch": "@ENGINEROOT@/Gems/Atom/TestData", + "recursive": 1, + "order": 1000 + } + } + } + } +} diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py index 3004b9ec7d..3d4d9ea419 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py @@ -29,7 +29,7 @@ def teardown_editor(editor): def launch_and_validate_results(request, test_directory, editor, editor_script, expected_lines, unexpected_lines=[], halt_on_unexpected=False, run_python="--runpythontest", auto_test_mode=True, null_renderer=True, cfg_args=[], - timeout=300): + timeout=300, log_file_name="Editor.log"): """ Runs the Editor with the specified script, and monitors for expected log lines. :param request: Special fixture providing information of the requesting test function. @@ -44,6 +44,7 @@ def launch_and_validate_results(request, test_directory, editor, editor_script, :param null_renderer: Specifies the test does not require the renderer. Defaults to True. :param cfg_args: Additional arguments for CFG, such as LevelName. :param timeout: Length of time for test to run. Default is 60. + :param log_file_name: Name of the log file created by the editor. Defaults to 'Editor.log' """ test_case = os.path.join(test_directory, editor_script) request.addfinalizer(lambda: teardown_editor(editor)) @@ -58,7 +59,17 @@ def launch_and_validate_results(request, test_directory, editor, editor_script, with editor.start(): - editorlog_file = os.path.join(editor.workspace.paths.project_log(), 'Editor.log') + editorlog_file = os.path.join(editor.workspace.paths.project_log(), log_file_name) + + # Log monitor requires the file to exist. + logger.debug(f"Waiting until log file <{editorlog_file}> exists...") + waiter.wait_for( + lambda: os.path.exists(editorlog_file), + timeout=60, + exc=f"Log file '{editorlog_file}' was never created by another process.", + interval=1, + ) + logger.debug(f"Done! log file <{editorlog_file}> exists.") # Initialize the log monitor and set time to wait for log creation log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=editor, log_file_path=editorlog_file) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py new file mode 100644 index 0000000000..b3c51ca912 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py @@ -0,0 +1,183 @@ +""" +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 azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. +""" + +import os +import sys +import time + +import azlmbr.math as math +import azlmbr.paths + +sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) + +import atom_renderer.atom_utils.material_editor_utils as material_editor + +NEW_MATERIAL = "test_material.material" +NEW_MATERIAL_1 = "test_material_1.material" +NEW_MATERIAL_2 = "test_material_2.material" +TEST_MATERIAL_1 = "001_DefaultWhite.material" +TEST_MATERIAL_2 = "002_BaseColorLerp.material" +TEST_MATERIAL_3 = "003_MetalMatte.material" +TEST_DATA_PATH = os.path.join( + azlmbr.paths.devroot, "Gems", "Atom", "TestData", "TestData", "Materials", "StandardPbrTestCases" +) +MATERIAL_TYPE_PATH = os.path.join( + azlmbr.paths.devroot, "Gems", "Atom", "Feature", "Common", "Assets", + "Materials", "Types", "StandardPBR.materialtype", +) + + +def run(): + """ + Summary: + Material Editor basic tests including the below + 1. Opening an Existing Asset + 2. Creating a New Asset + 3. Closing Selected Material + 4. Closing All Materials + 5. Closing all but Selected Material + 6. Saving Material + 7. Saving as a New Material + 8. Saving as a Child Material + 9. Saving all Open Materials + + Expected Result: + All the above functions work as expected in Material Editor. + + :return: None + """ + + # 1) Test Case: Opening an Existing Asset + document_id = material_editor.open_material(MATERIAL_TYPE_PATH) + print(f"Material opened: {material_editor.is_open(document_id)}") + + # Verify if the test material exists initially + target_path = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL) + print(f"Test asset doesn't exist initially: {not os.path.exists(target_path)}") + + # 2) Test Case: Creating a New Material Using Existing One + material_editor.save_document_as_child(document_id, target_path) + material_editor.wait_for_condition(lambda: os.path.exists(target_path), 2.0) + print(f"New asset created: {os.path.exists(target_path)}") + + # Verify if the newly created document is open + new_document_id = material_editor.open_material(target_path) + material_editor.wait_for_condition(lambda: material_editor.is_open(new_document_id)) + print(f"New Material opened: {material_editor.is_open(new_document_id)}") + + # 3) Test Case: Closing Selected Material + print(f"Material closed: {material_editor.close_document(new_document_id)}") + + # Open materials initially + document1_id, document2_id, document3_id = ( + material_editor.open_material(os.path.join(TEST_DATA_PATH, material)) + for material in [TEST_MATERIAL_1, TEST_MATERIAL_2, TEST_MATERIAL_3] + ) + + # 4) Test Case: Closing All Materials + print(f"All documents closed: {material_editor.close_all_documents()}") + + # 5) Test Case: Closing all but Selected Material + document1_id, document2_id, document3_id = ( + material_editor.open_material(os.path.join(TEST_DATA_PATH, material)) + for material in [TEST_MATERIAL_1, TEST_MATERIAL_2, TEST_MATERIAL_3] + ) + result = material_editor.close_all_except_selected(document1_id) + print(f"Close All Except Selected worked as expected: {result and material_editor.is_open(document1_id)}") + + # 6) Test Case: Saving Material + document_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + property_name = azlmbr.name.Name("baseColor.color") + initial_color = material_editor.get_property(document_id, property_name) + # Assign new color to the material file and save the actual material + expected_color = math.Color(0.25, 0.25, 0.25, 1.0) + material_editor.set_property(document_id, property_name, expected_color) + material_editor.save_document(document_id) + + # 7) Test Case: Saving as a New Material + # Assign new color to the material file and save the document as copy + expected_color_1 = math.Color(0.5, 0.5, 0.5, 1.0) + material_editor.set_property(document_id, property_name, expected_color_1) + target_path_1 = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL_1) + material_editor.save_document_as_copy(document_id, target_path_1) + time.sleep(2.0) + + # 8) Test Case: Saving as a Child Material + # Assign new color to the material file save the document as child + expected_color_2 = math.Color(0.75, 0.75, 0.75, 1.0) + material_editor.set_property(document_id, property_name, expected_color_2) + target_path_2 = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL_2) + material_editor.save_document_as_child(document_id, target_path_2) + time.sleep(2.0) + + # Close/Reopen documents + material_editor.close_all_documents() + document_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + document1_id = material_editor.open_material(target_path_1) + document2_id = material_editor.open_material(target_path_2) + + # Verify if the changes are saved in the actual document + actual_color = material_editor.get_property(document_id, property_name) + print(f"Actual Document saved with changes: {material_editor.compare_colors(actual_color, expected_color)}") + + # Verify if the changes are saved in the document saved as copy + actual_color = material_editor.get_property(document1_id, property_name) + result_copy = material_editor.compare_colors(actual_color, expected_color_1) + print(f"Document saved as copy is saved with changes: {result_copy}") + + # Verify if the changes are saved in the document saved as child + actual_color = material_editor.get_property(document2_id, property_name) + result_child = material_editor.compare_colors(actual_color, expected_color_2) + print(f"Document saved as child is saved with changes: {result_child}") + + # Revert back the changes in the actual document + material_editor.set_property(document_id, property_name, initial_color) + material_editor.save_document(document_id) + material_editor.close_all_documents() + + # 9) Test Case: Saving all Open Materials + # Open first material and make change to the values + document1_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + property1_name = azlmbr.name.Name("metallic.factor") + initial_metallic_factor = material_editor.get_property(document1_id, property1_name) + expected_metallic_factor = 0.444 + material_editor.set_property(document1_id, property1_name, expected_metallic_factor) + + # Open second material and make change to the values + document2_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_2)) + property2_name = azlmbr.name.Name("baseColor.color") + initial_color = material_editor.get_property(document2_id, property2_name) + expected_color = math.Color(0.4156, 0.0196, 0.6862, 1.0) + material_editor.set_property(document2_id, property2_name, expected_color) + + # Save all and close all documents + material_editor.save_all() + material_editor.close_all_documents() + + # Reopen materials and verify values + document1_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + result = material_editor.is_close( + material_editor.get_property(document1_id, property1_name), expected_metallic_factor, 0.00001 + ) + document2_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_2)) + result = result and material_editor.compare_colors( + expected_color, material_editor.get_property(document2_id, property2_name)) + print(f"Save All worked as expected: {result}") + + # Revert the changes made + material_editor.set_property(document1_id, property1_name, initial_metallic_factor) + material_editor.set_property(document2_id, property2_name, initial_color) + material_editor.save_all() + material_editor.close_all_documents() + + +if __name__ == "__main__": + run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py new file mode 100644 index 0000000000..77d1285188 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py @@ -0,0 +1,274 @@ +""" +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 azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. +""" + +import os +import sys +import time +import azlmbr.atom +import azlmbr.materialeditor as materialeditor +import azlmbr.bus as bus +import azlmbr.atomtools.general as general + + +def is_close(actual, expected, buffer=sys.float_info.min): + """ + :param actual: actual value + :param expected: expected value + :param buffer: acceptable variation from expected + :return: bool + """ + return abs(actual - expected) < buffer + + +def compare_colors(color1, color2, buffer=0.00001): + """ + Compares the red, green and blue properties of a color allowing a slight variance of buffer + :param color1: first color to compare + :param color2: second color + :param buffer: allowed variance in individual color value + :return: bool + """ + return ( + is_close(color1.r, color2.r, buffer) + and is_close(color1.g, color2.g, buffer) + and is_close(color1.b, color2.b, buffer) + ) + + +def open_material(file_path): + """ + :return: uuid of material document opened + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "OpenDocument", file_path) + + +def is_open(document_id): + """ + :return: bool + """ + return materialeditor.MaterialDocumentRequestBus(bus.Event, "IsOpen", document_id) + + +def save_document(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveDocument", document_id) + + +def save_document_as_copy(document_id, target_path): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus( + bus.Broadcast, "SaveDocumentAsCopy", document_id, target_path + ) + + +def save_document_as_child(document_id, target_path): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus( + bus.Broadcast, "SaveDocumentAsChild", document_id, target_path + ) + + +def save_all(): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveAllDocuments") + + +def close_document(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseDocument", document_id) + + +def close_all_documents(): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocuments") + + +def close_all_except_selected(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocumentsExcept", document_id) + + +def get_property(document_id, property_name): + """ + :return: property value or invalid value if the document is not open or the property_name can't be found + """ + return materialeditor.MaterialDocumentRequestBus(bus.Event, "GetPropertyValue", document_id, property_name) + + +def set_property(document_id, property_name, value): + materialeditor.MaterialDocumentRequestBus(bus.Event, "SetPropertyValue", document_id, property_name, value) + + +def is_pane_visible(pane_name): + """ + :return: bool + """ + return materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "IsDockWidgetVisible", pane_name) + + +def set_pane_visibility(pane_name, value): + materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "SetDockWidgetVisible", pane_name, value) + + +def select_lighting_config(config_name): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SelectLightingPresetByName", config_name) + + +def set_grid_enable_disable(value): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SetGridEnabled", value) + + +def get_grid_enable_disable(): + """ + :return: bool + """ + return azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "GetGridEnabled") + + +def set_shadowcatcher_enable_disable(value): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SetShadowCatcherEnabled", value) + + +def get_shadowcatcher_enable_disable(): + """ + :return: bool + """ + return azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "GetShadowCatcherEnabled") + + +def select_model_config(configname): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SelectModelPresetByName", configname) + + +def wait_for_condition(function, timeout_in_seconds=1.0): + # type: (function, float) -> bool + """ + Function to run until it returns True or timeout is reached + the function can have no parameters and + waiting idle__wait_* is handled here not in the function + + :param function: a function that returns a boolean indicating a desired condition is achieved + :param timeout_in_seconds: when reached, function execution is abandoned and False is returned + """ + with Timeout(timeout_in_seconds) as t: + while True: + try: + general.idle_wait_frames(1) + except Exception: + print("WARNING: Couldn't wait for frame") + + if t.timed_out: + return False + + ret = function() + if not isinstance(ret, bool): + raise TypeError("return value for wait_for_condition function must be a bool") + if ret: + return True + + +class Timeout: + # type: (float) -> None + """ + contextual timeout + :param seconds: float seconds to allow before timed_out is True + """ + + def __init__(self, seconds): + self.seconds = seconds + + def __enter__(self): + self.die_after = time.time() + self.seconds + return self + + def __exit__(self, type, value, traceback): + pass + + @property + def timed_out(self): + return time.time() > self.die_after + + +screenshotsFolder = os.path.join(azlmbr.paths.devroot, "AtomTest", "Cache" "pc", "Screenshots") + + +class ScreenshotHelper: + """ + A helper to capture screenshots and wait for them. + """ + + def __init__(self, idle_wait_frames_callback): + super().__init__() + self.done = False + self.capturedScreenshot = False + self.max_frames_to_wait = 60 + + self.idle_wait_frames_callback = idle_wait_frames_callback + + def capture_screenshot_blocking(self, filename): + """ + Capture a screenshot and block the execution until the screenshot has been written to the disk. + """ + self.handler = azlmbr.atom.FrameCaptureNotificationBusHandler() + self.handler.connect() + self.handler.add_callback("OnCaptureFinished", self.on_screenshot_captured) + + self.done = False + self.capturedScreenshot = False + success = azlmbr.atom.FrameCaptureRequestBus(azlmbr.bus.Broadcast, "CaptureScreenshot", filename) + if success: + self.wait_until_screenshot() + print("Screenshot taken.") + else: + print("screenshot failed") + return self.capturedScreenshot + + def on_screenshot_captured(self, parameters): + # the parameters come in as a tuple + if parameters[0]: + print("screenshot saved: {}".format(parameters[1])) + self.capturedScreenshot = True + else: + print("screenshot failed: {}".format(parameters[1])) + self.done = True + self.handler.disconnect() + + def wait_until_screenshot(self): + frames_waited = 0 + while self.done == False: + self.idle_wait_frames_callback(1) + if frames_waited > self.max_frames_to_wait: + print("timeout while waiting for the screenshot to be written") + self.handler.disconnect() + break + else: + frames_waited = frames_waited + 1 + print("(waited {} frames)".format(frames_waited)) + + +def capture_screenshot(file_path): + return ScreenshotHelper(azlmbr.atomtools.general.idle_wait_frames).capture_screenshot_blocking( + os.path.join(file_path) + ) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index 39689816b8..be75801b63 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -11,6 +11,7 @@ import os import pytest +import ly_test_tools.environment.file_system as file_system import editor_python_test_tools.hydra_test_utils as hydra from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES @@ -242,3 +243,65 @@ class TestAtomEditorComponentsMain(object): null_renderer=True, cfg_args=cfg_args, ) + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("launcher_platform", ['windows_generic']) +@pytest.mark.system +class TestMaterialEditorBasicTests(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request, workspace, project): + def delete_files(): + file_system.delete( + [ + os.path.join(workspace.paths.project(), "Materials", "test_material.material"), + os.path.join(workspace.paths.project(), "Materials", "test_material_1.material"), + os.path.join(workspace.paths.project(), "Materials", "test_material_2.material"), + ], + True, + True, + ) + # Cleanup our newly created materials + delete_files() + + def teardown(): + # Cleanup our newly created materials + delete_files() + + request.addfinalizer(teardown) + + @pytest.mark.parametrize("exe_file_name", ["MaterialEditor"]) + def test_MaterialEditorBasicTests( + self, request, workspace, project, launcher_platform, generic_launcher, exe_file_name): + + expected_lines = [ + "Material opened: True", + "Test asset doesn't exist initially: True", + "New asset created: True", + "New Material opened: True", + "Material closed: True", + "All documents closed: True", + "Close All Except Selected worked as expected: True", + "Actual Document saved with changes: True", + "Document saved as copy is saved with changes: True", + "Document saved as child is saved with changes: True", + "Save All worked as expected: True", + ] + unexpected_lines = [ + # "Trace::Assert", + # "Trace::Error", + "Traceback (most recent call last):" + ] + + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + generic_launcher, + "hydra_AtomMaterialEditor_BasicTests.py", + run_python="--runpython", + timeout=80, + expected_lines=expected_lines, + unexpected_lines=unexpected_lines, + halt_on_unexpected=True, + log_file_name="MaterialEditor.log", + ) From 041aa42307fcf42bfdb41871530acac7464efe82 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 11 Aug 2021 13:56:03 -0700 Subject: [PATCH 245/251] fixes after merge Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Include/IFileUtil.h | 1 + Code/Legacy/CryCommon/CrySizer.h | 1 + Code/Legacy/CryCommon/WinBase.cpp | 3 ++- Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp | 4 ++-- Gems/Maestro/Code/Source/Cinematics/Movie.cpp | 8 ++++---- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Code/Editor/Include/IFileUtil.h b/Code/Editor/Include/IFileUtil.h index 746a81b87c..700e04f6d3 100644 --- a/Code/Editor/Include/IFileUtil.h +++ b/Code/Editor/Include/IFileUtil.h @@ -9,6 +9,7 @@ #pragma once #include "../Include/SandboxAPI.h" +#include class QWidget; diff --git a/Code/Legacy/CryCommon/CrySizer.h b/Code/Legacy/CryCommon/CrySizer.h index b541b698f9..3f9eed84f6 100644 --- a/Code/Legacy/CryCommon/CrySizer.h +++ b/Code/Legacy/CryCommon/CrySizer.h @@ -30,6 +30,7 @@ #include #include #include +#include // forward declarations for overloads struct AABB; diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 4e48d29ed7..a2b4056a56 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -12,6 +12,7 @@ #include "platform.h" // Note: This should be first to get consistent debugging definitions +#include #include #if defined(AZ_RESTRICTED_PLATFORM) @@ -29,7 +30,7 @@ #include AZ_RESTRICTED_FILE(WinBase_cpp) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #else #include #endif diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp index 5d6cbe90eb..35fde93e83 100644 --- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp +++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp @@ -27,11 +27,11 @@ // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(eUiAnimNodeType_ ## name) == g_animNodeEnumToStringMap.end()); \ g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = AZ_STRINGIZE(name); \ - g_animNodeStringToEnumMap[string(STRINGIFY(name))] = eUiAnimNodeType_ ## name; + g_animNodeStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = eUiAnimNodeType_ ## name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(eUiAnimParamType_ ## name) == g_animParamEnumToStringMap.end()); \ g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = AZ_STRINGIZE(name); \ - g_animParamStringToEnumMap[string(STRINGIFY(name))] = eUiAnimParamType_ ## name; + g_animParamStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = eUiAnimParamType_ ## name; namespace { diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp index 8bbaf6e0c8..cf51ef3729 100644 --- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp @@ -74,12 +74,12 @@ static SMovieSequenceAutoComplete s_movieSequenceAutoComplete; ////////////////////////////////////////////////////////////////////////// // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(AnimNodeType::name) == g_animNodeEnumToStringMap.end()); \ - g_animNodeEnumToStringMap[AnimNodeType::name] = AZ_STRINGIZE(name); \ - g_animNodeStringToEnumMap[string(STRINGIFY(name))] = AnimNodeType::name; + g_animNodeEnumToStringMap[AnimNodeType::name] = AZ_STRINGIZE(name); \ + g_animNodeStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = AnimNodeType::name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(AnimParamType::name) == g_animParamEnumToStringMap.end()); \ - g_animParamEnumToStringMap[AnimParamType::name] = AZ_STRINGIZE(name); \ - g_animParamStringToEnumMap[string(STRINGIFY(name))] = AnimParamType::name; + g_animParamEnumToStringMap[AnimParamType::name] = AZ_STRINGIZE(name); \ + g_animParamStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = AnimParamType::name; namespace { From c6714595b1edb22748a68f25c9d9e59a479390fa Mon Sep 17 00:00:00 2001 From: Junbo Liang <68558268+junbo75@users.noreply.github.com> Date: Wed, 11 Aug 2021 13:59:29 -0700 Subject: [PATCH 246/251] Define a new Jenkins build script to deploy AWS resources (#2983) * Define a new Jenkins job to deploy AWS resources Signed-off-by: junbo * Address PR comments Signed-off-by: junbo * Add error checking for all the calls Signed-off-by: junbo * Remove the weekly-build-metrics tag Signed-off-by: junbo * Parameterize ARN/Region and move it to a Jenkins envvar. Signed-off-by: junbo * Revert the changes for build_config.json Signed-off-by: junbo --- .../Windows/deploy_cdk_applications.cmd | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 scripts/build/Platform/Windows/deploy_cdk_applications.cmd diff --git a/scripts/build/Platform/Windows/deploy_cdk_applications.cmd b/scripts/build/Platform/Windows/deploy_cdk_applications.cmd new file mode 100644 index 0000000000..2845707923 --- /dev/null +++ b/scripts/build/Platform/Windows/deploy_cdk_applications.cmd @@ -0,0 +1,105 @@ +@ECHO OFF +REM +REM Copyright (c) Contributors to the Open 3D Engine Project. +REM For complete copyright and license terms please see the LICENSE at the root of this distribution. +REM +REM SPDX-License-Identifier: Apache-2.0 OR MIT +REM +REM + +REM Deploy the CDK applcations for AWS gems (Windows only) +REM Prerequisites: +REM 1) Node.js is installed +REM 2) Node.js version >= 10.13.0, except for versions 13.0.0 - 13.6.0. A version in active long-term support is recommended. +SETLOCAL EnableDelayedExpansion + +SET SOURCE_DIRECTORY=%CD% +SET PATH=%SOURCE_DIRECTORY%\python;%PATH% +SET GEM_DIRECTORY=%SOURCE_DIRECTORY%\Gems + +REM Create and activate a virtualenv for the CDK deployment +CALL python -m venv .env +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to create a virtualenv for the CDK deployment + exit /b 1 +) +CALL .env\Scripts\activate.bat +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to activate the virtualenv for the CDK deployment + exit /b 1 +) + +ECHO [cdk_installation] Install the latest version of CDK +CALL npm uninstall -g aws-cdk +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to uninstall the current version of CDK + exit /b 1 +) +CALL npm install -g aws-cdk@latest +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to install the latest version of CDK + exit /b 1 +) + +REM Set temporary AWS credentials from the assume role +FOR /f "tokens=1,2,3" %%a IN ('CALL aws sts assume-role --query Credentials.[SecretAccessKey^,SessionToken^,AccessKeyId] --output text --role-arn %ASSUME_ROLE_ARN% --role-session-name o3de-Automation-session') DO ( + SET AWS_SECRET_ACCESS_KEY=%%a + SET AWS_SESSION_TOKEN=%%b + SET AWS_ACCESS_KEY_ID=%%c +) +FOR /F "tokens=4 delims=:" %%a IN ("%ASSUME_ROLE_ARN%") DO SET O3DE_AWS_DEPLOY_ACCOUNT=%%a + +REM Bootstrap and deploy the CDK applications +ECHO [cdk_bootstrap] Bootstrap CDK +CALL cdk bootstrap aws://%O3DE_AWS_DEPLOY_ACCOUNT%/%O3DE_AWS_DEPLOY_REGION% +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to bootstrap CDK + exit /b 1 +) + +CALL :DeployCDKApplication AWSCore --all +IF ERRORLEVEL 1 ( + exit /b 1 +) +CALL :DeployCDKApplication AWSClientAuth +IF ERRORLEVEL 1 ( + exit /b 1 +) +CALL :DeployCDKApplication AWSMetrics "-c batch_processing=true" +IF ERRORLEVEL 1 ( + exit /b 1 +) + +EXIT /b 0 + +:DeployCDKApplication +REM Deploy the CDK application for a specific AWS gem +SET GEM_NAME=%~1 +SET ADDITIONAL_ARGUMENTS=%~2 +ECHO [cdk_deployment] Deploy the CDK application for the %GEM_NAME% gem +PUSHD %GEM_DIRECTORY%\%GEM_NAME%\cdk + +REM Revert the CDK application code to a stable state using the provided commit ID +CALL git checkout %COMMIT_ID% -- . +IF ERRORLEVEL 1 ( + ECHO [git_checkout] Failed to checkout the CDK application for the %GEM_NAME% gem using commit ID %COMMIT_ID% + POPD + exit /b 1 +) + +REM Install required packages for the CDK application +CALL python -m pip install -r requirements.txt +IF ERRORLEVEL 1 ( + ECHO [cdk_deployment] Failed to install required packages for the %GEM_NAME% gem + POPD + exit /b 1 +) + +REM Deploy the CDK application +CALL cdk deploy %ADDITIONAL_ARGUMENTS% --require-approval never +IF ERRORLEVEL 1 ( + ECHO [cdk_deployment] Failed to deploy the CDK application for the %GEM_NAME% gem + POPD + exit /b 1 +) +POPD From 7e5cbdab1e26fa829fdc70c0978914a22ac128ca Mon Sep 17 00:00:00 2001 From: chiyenteng <82238204+chiyenteng@users.noreply.github.com> Date: Wed, 11 Aug 2021 14:11:26 -0700 Subject: [PATCH 247/251] Create a new automated test for Prefab basic workflows (#2715) Adds a new ebus for prefab apis and refactored the apis Removed an empty test level Auto delete tmp level when teardown tests Add Base test level in Prefab folder Removed unused comments Checked if absolute path as an input of Create Prefab functions Changed created prefab file path to support all platfroms Added missing includes Signed-off-by: chiyteng --- .../prefab/PrefabLevel_BasicWorkflow.py | 66 ++++++++++++++++ .../Gem/PythonTests/prefab/TestSuite_Main.py | 6 ++ .../Levels/Prefab/Base/Base.prefab | 53 +++++++++++++ .../API/ToolsApplicationAPI.h | 4 +- .../Application/ToolsApplication.cpp | 1 - .../Prefab/PrefabPublicHandler.cpp | 48 +++++++---- .../Prefab/PrefabPublicHandler.h | 7 +- .../Prefab/PrefabPublicInterface.h | 21 ++++- .../Prefab/PrefabPublicRequestBus.h | 56 +++++++++++++ .../Prefab/PrefabPublicRequestHandler.cpp | 79 +++++++++++++++++++ .../Prefab/PrefabPublicRequestHandler.h | 41 ++++++++++ .../Prefab/PrefabSystemComponent.cpp | 4 +- .../Prefab/PrefabSystemComponent.h | 4 + .../UI/Prefab/PrefabIntegrationManager.cpp | 8 +- .../aztoolsframework_files.cmake | 3 + 15 files changed, 372 insertions(+), 29 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py create mode 100644 AutomatedTesting/Levels/Prefab/Base/Base.prefab create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py new file mode 100644 index 0000000000..44b7dc2ee4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py @@ -0,0 +1,66 @@ +""" +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 +""" + +# fmt:off +class Tests(): + create_new_entity = ("Entity: 'CreateNewEntity' passed", "Entity: 'CreateNewEntity' failed") + create_prefab = ("Prefab: 'CreatePrefab' passed", "Prefab: 'CreatePrefab' failed") + instantiate_prefab = ("Prefab: 'InstantiatePrefab' passed", "Prefab: 'InstantiatePrefab' failed") + new_prefab_position = ("Prefab: new prefab's position is at the expected position", "Prefab: new prefab's position is *not* at the expected position") +# fmt:on + +def PrefabLevel_BasicWorkflow(): + """ + This test will help verify if the following functions related to Prefab work as expected: + - CreatePrefab + - InstantiatePrefab + """ + + import os + import sys + + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + import editor_python_test_tools.hydra_editor_utils as hydra + + import azlmbr.bus as bus + import azlmbr.entity as entity + from azlmbr.entity import EntityId + import azlmbr.editor as editor + import azlmbr.prefab as prefab + from azlmbr.math import Vector3 + import azlmbr.legacy.general as general + + EXPECTED_NEW_PREFAB_POSITION = Vector3(10.00, 20.0, 30.0) + + helper.init_idle() + helper.open_level("Prefab", "Base") + +# Create a new Entity at the root level + new_entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', EntityId()) + Report.result(Tests.create_new_entity, new_entity_id.IsValid()) + +# Checks for prefab creation passed or not + new_prefab_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'new_prefab.prefab') + create_prefab_result = prefab.PrefabPublicRequestBus(bus.Broadcast, 'CreatePrefabInMemory', [new_entity_id], new_prefab_file_path) + Report.result(Tests.create_prefab, create_prefab_result) + +# Checks for prefab instantiation passed or not + container_entity_id = prefab.PrefabPublicRequestBus(bus.Broadcast, 'InstantiatePrefab', new_prefab_file_path, EntityId(), EXPECTED_NEW_PREFAB_POSITION) + Report.result(Tests.instantiate_prefab, container_entity_id.IsValid()) + +# Checks if the new prefab is at the correct position and if it fails, it will provide the expected postion and the actual postion of the entity in the Editor log + new_prefab_position = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", container_entity_id) + is_at_position = new_prefab_position.IsClose(EXPECTED_NEW_PREFAB_POSITION) + Report.result(Tests.new_prefab_position, is_at_position) + if not is_at_position: + Report.info(f'Expected position: {EXPECTED_NEW_PREFAB_POSITION.ToString()}, actual position: {new_prefab_position.ToString()}') + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(PrefabLevel_BasicWorkflow) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py index acd8f60b07..4e3d6ba77f 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py @@ -16,6 +16,7 @@ from ly_test_tools import LAUNCHERS sys.path.append (os.path.dirname (os.path.abspath (__file__)) + '/../automatedtesting_shared') +import ly_test_tools.environment.file_system as file_system from base import TestAutomationBase @pytest.mark.SUITE_main @@ -29,3 +30,8 @@ class TestAutomation(TestAutomationBase): def test_PrefabLevel_OpensLevelWithEntities(self, request, workspace, editor, launcher_platform): from . import PrefabLevel_OpensLevelWithEntities as test_module self._run_prefab_test(request, workspace, editor, test_module) + + def test_PrefabLevel_BasicWorkflow(self, request, workspace, editor, launcher_platform): + from . import PrefabLevel_BasicWorkflow as test_module + self._run_prefab_test(request, workspace, editor, test_module) + diff --git a/AutomatedTesting/Levels/Prefab/Base/Base.prefab b/AutomatedTesting/Levels/Prefab/Base/Base.prefab new file mode 100644 index 0000000000..f7e42e7731 --- /dev/null +++ b/AutomatedTesting/Levels/Prefab/Base/Base.prefab @@ -0,0 +1,53 @@ +{ + "ContainerEntity": { + "Id": "Entity_[1146574390643]", + "Name": "Level", + "Components": { + "Component_[10641544592923449938]": { + "$type": "EditorInspectorComponent", + "Id": 10641544592923449938 + }, + "Component_[12039882709170782873]": { + "$type": "EditorOnlyEntityComponent", + "Id": 12039882709170782873 + }, + "Component_[12265484671603697631]": { + "$type": "EditorPendingCompositionComponent", + "Id": 12265484671603697631 + }, + "Component_[14126657869720434043]": { + "$type": "EditorEntitySortComponent", + "Id": 14126657869720434043 + }, + "Component_[15230859088967841193]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 15230859088967841193, + "Parent Entity": "" + }, + "Component_[16239496886950819870]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 16239496886950819870 + }, + "Component_[5688118765544765547]": { + "$type": "EditorEntityIconComponent", + "Id": 5688118765544765547 + }, + "Component_[6545738857812235305]": { + "$type": "SelectionComponent", + "Id": 6545738857812235305 + }, + "Component_[7247035804068349658]": { + "$type": "EditorPrefabComponent", + "Id": 7247035804068349658 + }, + "Component_[9307224322037797205]": { + "$type": "EditorLockComponent", + "Id": 9307224322037797205 + }, + "Component_[9562516168917670048]": { + "$type": "EditorVisibilityComponent", + "Id": 9562516168917670048 + } + } + } +} \ No newline at end of file diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h index 0ba10d7388..f6046b9f25 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h @@ -600,8 +600,8 @@ namespace AzToolsFramework * Open 3D Engine Internal use only. * * Run a specific redo command separate from the undo/redo system. - * In many cases before a modifcation on an entity takes place, it is first packaged into - * undo/redo commands. Running the modification's redo command separete from the undo/redo + * In many cases before a modification on an entity takes place, it is first packaged into + * undo/redo commands. Running the modification's redo command separate from the undo/redo * system simulates its execution, and avoids some code duplication. */ virtual void RunRedoSeparately(UndoSystem::URSequencePoint* redoCommand) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp index 970f5aa28c..56ef749247 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp @@ -1781,5 +1781,4 @@ namespace AzToolsFramework { appType.m_maskValue = AZ::ApplicationTypeQuery::Masks::Tool; }; - } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index bb394720c9..7af953efca 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -61,7 +61,7 @@ namespace AzToolsFramework m_prefabUndoCache.Destroy(); } - PrefabOperationResult PrefabPublicHandler::CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) + PrefabOperationResult PrefabPublicHandler::CreatePrefabInMemory(const AZStd::vector& entityIds, AZ::IO::PathView filePath) { EntityList inputEntityList, topLevelEntities; AZ::EntityId commonRootEntityId; @@ -73,8 +73,6 @@ namespace AzToolsFramework return findCommonRootOutcome; } - AZ_Assert(absolutePath.IsAbsolute(), "CreatePrefab requires an absolute path for saving the initial prefab file."); - InstanceOptionalReference instanceToCreate; { // Initialize Undo Batch object @@ -125,7 +123,7 @@ namespace AzToolsFramework PrefabDom linkPatchesCopy; linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); nestedInstanceLinkPatchesMap.emplace(nestedInstance, AZStd::move(linkPatchesCopy)); - + RemoveLink(outInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); instancePtrs.emplace_back(AZStd::move(outInstance)); @@ -139,18 +137,20 @@ namespace AzToolsFramework if (!prefabEditorEntityOwnershipInterface) { return AZ::Failure(AZStd::string("Could not create a new prefab out of the entities provided - internal error " - "(PrefabEditorEntityOwnershipInterface unavailable).")); + "(PrefabEditorEntityOwnershipInterface unavailable).")); } // Create the Prefab + AZ_Assert(filePath.IsAbsolute(), "CreatePrefabInMemory requires an absolute file path."); + instanceToCreate = prefabEditorEntityOwnershipInterface->CreatePrefab( - entities, AZStd::move(instancePtrs), m_prefabLoaderInterface->GenerateRelativePath(absolutePath), + entities, AZStd::move(instancePtrs), m_prefabLoaderInterface->GenerateRelativePath(filePath), commonRootEntityOwningInstance); if (!instanceToCreate) { return AZ::Failure(AZStd::string("Could not create a new prefab out of the entities provided - internal error " - "(A null instance is returned).")); + "(A null instance is returned).")); } AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); @@ -218,7 +218,7 @@ namespace AzToolsFramework linkUpdate.Redo(); } }); - + // Create a link between the templates of the newly created instance and the instance it's being parented under. CreateLink( instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), @@ -255,18 +255,35 @@ namespace AzToolsFramework // Select Container Entity { - auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); + auto selectionUndo = aznew SelectionCommand({ containerEntityId }, "Select Prefab Container Entity"); selectionUndo->SetParent(undoBatch.GetUndoBatch()); ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequestBus::Events::RunRedoSeparately, selectionUndo); } } - // Save Template to file - m_prefabLoaderInterface->SaveTemplateToFile(instanceToCreate->get().GetTemplateId(), absolutePath); - return AZ::Success(); } + PrefabOperationResult PrefabPublicHandler::CreatePrefabInDisk(const AZStd::vector& entityIds, AZ::IO::PathView filePath) + { + auto result = CreatePrefabInMemory(entityIds, filePath); + if (result.IsSuccess()) + { + // Save Template to file + auto relativePath = m_prefabLoaderInterface->GenerateRelativePath(filePath); + Prefab::TemplateId templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(relativePath); + if (!m_prefabLoaderInterface->SaveTemplateToFile(templateId, filePath)) + { + AZStd::string_view filePathString(filePath); + return AZ::Failure(AZStd::string::format( + "Could not save the newly created prefab to file path %.*s - internal error ", + AZ_STRING_ARG(filePathString))); + } + } + + return result; + } + PrefabDom PrefabPublicHandler::ApplyContainerTransformAndGeneratePatch(AZ::EntityId containerEntityId, AZ::EntityId parentEntityId, const EntityList& childEntities) { AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -301,7 +318,7 @@ namespace AzToolsFramework return AZStd::move(patch); } - PrefabOperationResult PrefabPublicHandler::InstantiatePrefab( + InstantiatePrefabResult PrefabPublicHandler::InstantiatePrefab( AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) { auto prefabEditorEntityOwnershipInterface = AZ::Interface::Get(); @@ -347,6 +364,7 @@ namespace AzToolsFramework relativePath.Native().c_str(), instanceToParentUnder->get().GetTemplateSourcePath().Native().c_str())); } + AZ::EntityId containerEntityId; { // Initialize Undo Batch object ScopedUndoBatch undoBatch("Instantiate Prefab"); @@ -367,7 +385,7 @@ namespace AzToolsFramework instanceToParentUnder->get(), "Update prefab instance", instanceToParentUnderDomBeforeCreate, undoBatch.GetUndoBatch()); // Create Link with correct container patches - AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); + containerEntityId = instanceToCreate->get().GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); AZ_Assert(containerEntity, "Invalid container entity detected in InstantiatePrefab."); @@ -394,7 +412,7 @@ namespace AzToolsFramework &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } - return AZ::Success(); + return AZ::Success(containerEntityId); } PrefabOperationResult PrefabPublicHandler::FindCommonRootOwningInstance( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 0e24b0841d..8f124e8edd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -42,8 +42,11 @@ namespace AzToolsFramework void UnregisterPrefabPublicHandlerInterface(); // PrefabPublicInterface... - PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) override; - PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; + PrefabOperationResult CreatePrefabInDisk( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + PrefabOperationResult CreatePrefabInMemory( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + InstantiatePrefabResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; PrefabOperationResult SavePrefab(AZ::IO::Path filePath) override; PrefabEntityResult CreateEntity(AZ::EntityId parentId, const AZ::Vector3& position) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h index 6b3fdcd391..67d65dfca6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -25,6 +25,7 @@ namespace AzToolsFramework namespace Prefab { typedef AZ::Outcome PrefabOperationResult; + typedef AZ::Outcome InstantiatePrefabResult; typedef AZ::Outcome PrefabRequestResult; typedef AZ::Outcome PrefabEntityResult; @@ -39,22 +40,34 @@ namespace AzToolsFramework AZ_RTTI(PrefabPublicInterface, "{931AAE9D-C775-4818-9070-A2DA69489CBE}"); /** - * Create a prefab out of the entities provided, at the path provided. + * Create a prefab out of the entities provided, at the path provided, and save it in disk immediately. * Automatically detects descendants of entities, and discerns between entities and child instances. * @param entityIds The entities that should form the new prefab (along with their descendants). * @param filePath The absolute path for the new prefab file. * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) = 0; + virtual PrefabOperationResult CreatePrefabInDisk( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; + + /** + * Create a prefab out of the entities provided, at the path provided, and keep it in memory. + * Automatically detects descendants of entities, and discerns between entities and child instances. + * @param entityIds The entities that should form the new prefab (along with their descendants). + * @param filePath The absolute path for the new prefab file. + * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. + */ + virtual PrefabOperationResult CreatePrefabInMemory( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; /** * Instantiate a prefab from a prefab file. * @param filePath The path to the prefab file to instantiate. * @param parent The entity the prefab should be a child of in the transform hierarchy. * @param position The position in world space the prefab should be instantiated in. - * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. + * @return An outcome object with an entityId of the new prefab's container entity; + * on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; + virtual InstantiatePrefabResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; /** * Saves changes to prefab to disk. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h new file mode 100644 index 0000000000..1b86d3cd4e --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h @@ -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 + * + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AzToolsFramework +{ + namespace Prefab + { + /** + * The primary purpose of this bus is to facilitate writing automated tests for prefabs. + * It calls PrefabPublicInterface internally to talk to the prefab system. + * If you would like to integrate prefabs into your system, please call PrefabPublicInterface + * directly for better performance. + */ + class PrefabPublicRequests + : public AZ::EBusTraits + { + public: + using Bus = AZ::EBus; + + ////////////////////////////////////////////////////////////////////////// + // EBusTraits overrides + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + ////////////////////////////////////////////////////////////////////////// + + virtual ~PrefabPublicRequests() = default; + + /** + * Create a prefab out of the entities provided, at the path provided, and keep it in memory. + * Automatically detects descendants of entities, and discerns between entities and child instances. + */ + virtual bool CreatePrefabInMemory( + const AZStd::vector& entityIds, AZStd::string_view filePath) = 0; + + /** + * Instantiate a prefab from a prefab file. + */ + virtual AZ::EntityId InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; + }; + + using PrefabPublicRequestBus = AZ::EBus; + + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp new file mode 100644 index 0000000000..0e68a286a6 --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp @@ -0,0 +1,79 @@ +/* + * 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 AzToolsFramework +{ + namespace Prefab + { + void PrefabPublicRequestHandler::Reflect(AZ::ReflectContext* context) + { + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->EBus("PrefabPublicRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) + ->Attribute(AZ::Script::Attributes::Category, "Prefab") + ->Attribute(AZ::Script::Attributes::Module, "prefab") + ->Event("CreatePrefabInMemory", &PrefabPublicRequests::CreatePrefabInMemory) + ->Event("InstantiatePrefab", &PrefabPublicRequests::InstantiatePrefab) + ; + } + } + + void PrefabPublicRequestHandler::Connect() + { + m_prefabPublicInterface = AZ::Interface::Get(); + AZ_Assert(m_prefabPublicInterface, "PrefabPublicRequestHandler - Could not retrieve instance of PrefabPublicInterface"); + + PrefabPublicRequestBus::Handler::BusConnect(); + } + + void PrefabPublicRequestHandler::Disconnect() + { + PrefabPublicRequestBus::Handler::BusDisconnect(); + + m_prefabPublicInterface = nullptr; + } + + bool PrefabPublicRequestHandler::CreatePrefabInMemory(const AZStd::vector& entityIds, AZStd::string_view filePath) + { + auto createPrefabOutcome = m_prefabPublicInterface->CreatePrefabInMemory(entityIds, filePath); + if (!createPrefabOutcome.IsSuccess()) + { + AZ_Error("CreatePrefabInMemory", false, + "Failed to create Prefab on file path '%.*s'. Error message: %s.", + AZ_STRING_ARG(filePath), + createPrefabOutcome.GetError().c_str()); + + return false; + } + + return true; + } + + AZ::EntityId PrefabPublicRequestHandler::InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) + { + auto instantiatePrefabOutcome = m_prefabPublicInterface->InstantiatePrefab(filePath, parent, position); + if (!instantiatePrefabOutcome.IsSuccess()) + { + AZ_Error("InstantiatePrefab", false, + "Failed to instantiate Prefab on file path '%.*s'. Error message: %s.", + AZ_STRING_ARG(filePath), + instantiatePrefabOutcome.GetError().c_str()); + + return AZ::EntityId(); + } + + return instantiatePrefabOutcome.GetValue(); + } + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h new file mode 100644 index 0000000000..548bc8e04a --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h @@ -0,0 +1,41 @@ +/* + * 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 AzToolsFramework +{ + namespace Prefab + { + class PrefabPublicInterface; + + class PrefabPublicRequestHandler final + : public PrefabPublicRequestBus::Handler + { + public: + AZ_CLASS_ALLOCATOR(PrefabPublicRequestHandler, AZ::SystemAllocator, 0); + AZ_RTTI(PrefabPublicRequestHandler, "{83FBDDF9-10BE-4373-B1DC-44B47EE4805C}"); + + static void Reflect(AZ::ReflectContext* context); + + void Connect(); + void Disconnect(); + + bool CreatePrefabInMemory(const AZStd::vector& entityIds, AZStd::string_view filePath) override; + AZ::EntityId InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; + + private: + PrefabPublicInterface* m_prefabPublicInterface = nullptr; + }; + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index bfdb6b79f2..1051e530c8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -35,12 +35,14 @@ namespace AzToolsFramework m_instanceUpdateExecutor.RegisterInstanceUpdateExecutorInterface(); m_instanceToTemplatePropagator.RegisterInstanceToTemplateInterface(); m_prefabPublicHandler.RegisterPrefabPublicHandlerInterface(); + m_prefabPublicRequestHandler.Connect(); AZ::SystemTickBus::Handler::BusConnect(); } void PrefabSystemComponent::Deactivate() { AZ::SystemTickBus::Handler::BusDisconnect(); + m_prefabPublicRequestHandler.Disconnect(); m_prefabPublicHandler.UnregisterPrefabPublicHandlerInterface(); m_instanceToTemplatePropagator.UnregisterInstanceToTemplateInterface(); m_instanceUpdateExecutor.UnregisterInstanceUpdateExecutorInterface(); @@ -54,6 +56,7 @@ namespace AzToolsFramework AzToolsFramework::Prefab::PrefabConversionUtils::PrefabConversionPipeline::Reflect(context); AzToolsFramework::Prefab::PrefabConversionUtils::PrefabCatchmentProcessor::Reflect(context); AzToolsFramework::Prefab::PrefabConversionUtils::EditorInfoRemover::Reflect(context); + PrefabPublicRequestHandler::Reflect(context); AZ::SerializeContext* serialize = azrtti_cast(context); if (serialize) @@ -62,7 +65,6 @@ namespace AzToolsFramework } AZ::JsonRegistrationContext* jsonRegistration = azrtti_cast(context); - if (jsonRegistration) { jsonRegistration->Serializer()->HandlesType(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index 04457b5a97..b07ccbada6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -369,6 +370,9 @@ namespace AzToolsFramework // Used for updating Templates when Instances are modified InstanceToTemplatePropagator m_instanceToTemplatePropagator; + + // Handler of the public Prefab requests + PrefabPublicRequestHandler m_prefabPublicRequestHandler; }; } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 5bf9b15abe..eb9cf2b65f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -256,11 +256,11 @@ namespace AzToolsFramework void PrefabIntegrationManager::HandleSourceFileType(AZStd::string_view sourceFilePath, AZ::EntityId parentId, AZ::Vector3 position) const { - auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(sourceFilePath, parentId, position); + auto instantiatePrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(sourceFilePath, parentId, position); - if (!createPrefabOutcome.IsSuccess()) + if (!instantiatePrefabOutcome.IsSuccess()) { - WarnUserOfError("Prefab Instantiation Error", createPrefabOutcome.GetError()); + WarnUserOfError("Prefab Instantiation Error", instantiatePrefabOutcome.GetError()); } } @@ -348,7 +348,7 @@ namespace AzToolsFramework } } - auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefab(selectedEntities, prefabFilePath.data()); + auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefabInDisk(selectedEntities, prefabFilePath.data()); if (!createPrefabOutcome.IsSuccess()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 53173f83af..14c5f34f90 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -657,6 +657,9 @@ set(FILES Prefab/PrefabPublicHandler.cpp Prefab/PrefabPublicInterface.h Prefab/PrefabPublicNotificationBus.h + Prefab/PrefabPublicRequestBus.h + Prefab/PrefabPublicRequestHandler.h + Prefab/PrefabPublicRequestHandler.cpp Prefab/PrefabUndo.h Prefab/PrefabUndo.cpp Prefab/PrefabUndoCache.cpp From 016cfef6ca569b3a407e819481ef6a83d661202c Mon Sep 17 00:00:00 2001 From: Jacob Hilliard <64656371+jcbhl@users.noreply.github.com> Date: Wed, 11 Aug 2021 15:32:11 -0700 Subject: [PATCH 248/251] Visualizer: fix empty rows being shown (#2881) Fixes a bug with the visualizer where there would be empty rows shown, e.g. threads without any profiling regions. This was especially noticable when going from a high thread count sample (MultiThread) to a low thread count sample, where most of the visualizer would be empty lines. This adds a data culling step to remove the threads without any remaining execution data + an early out so that all threads shown onscreen must have some regions recorded. Signed-off-by: Jacob Hilliard --- .../Code/Include/Atom/Utils/ImGuiCpuProfiler.inl | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl index ffc9a60c00..a24fdbf1d8 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl @@ -329,7 +329,7 @@ namespace AZ ImGui::Text("Viewport width: %.3f ms", CpuProfilerImGuiHelper::TicksToMs(GetViewportTickWidth())); ImGui::Text("Ticks [%lld , %lld]", m_viewportStartTick, m_viewportEndTick); - ImGui::Text("Recording %ld threads", RHI::CpuProfiler::Get()->GetTimeRegionMap().size()); + ImGui::Text("Recording %zu threads", m_savedData.size()); ImGui::Text("%llu profiling events saved", m_savedRegionCount); ImGui::NextColumn(); @@ -389,6 +389,11 @@ namespace AZ return wrapper.m_startTick < target; }); + if (regionItr == singleThreadData.end()) + { + continue; + } + // Draw all of the blocks for a given thread/row u64 maxDepth = 0; while (regionItr != singleThreadData.end()) @@ -559,6 +564,14 @@ namespace AZ m_savedRegionCount -= sizeBeforeRemove - savedRegions.size(); } + + // Remove any threads from the top-level map that no longer hold data + AZStd::erase_if( + m_savedData, + [](const auto& singleThreadDataEntry) + { + return singleThreadDataEntry.second.empty(); + }); } inline void ImGuiCpuProfiler::DrawBlock(const TimeRegion& block, u64 targetRow) From dba26cc2357b001da4a890ca211a78db3afce335 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 11 Aug 2021 16:07:46 -0700 Subject: [PATCH 249/251] Fix code that trips -Wsign-compare (#3046) Signed-off-by: Chris Burel --- .../Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp index ac824bfc4d..3dd49574fd 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp @@ -43,7 +43,7 @@ void CUiAVNewSequenceDialog::OnOK() return; } - for (int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k) + for (unsigned int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k) { CUiAnimViewSequence* pSequence = CUiAnimViewSequenceManager::GetSequenceManager()->GetSequenceByIndex(k); QString fullname = pSequence->GetName(); From 094d06f1e370c04fe0edd0a8abea190f71994253 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 11 Aug 2021 16:08:05 -0700 Subject: [PATCH 250/251] Update EMotionFX layouts to deal with changed QObject names (#3045) Commit 1837d05169 changed some of the EMotionFX editor's QObject names to match their new class member names. Unfortunately this broke the EMotionFX layouts. This recreates the good layouts to contain the new QObject names. Signed-off-by: Chris Burel --- .../Assets/Editor/Layouts/AnimGraph.layout | Bin 6480 -> 7200 bytes .../Editor/Layouts/SimulatedObjects.layout | Bin 7203 -> 6901 bytes 2 files changed, 0 insertions(+), 0 deletions(-) diff --git a/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout b/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout index 85fa2f2253311fb9b538d0953c5951658f46a683..e85d6054a3e54df86030125994f050171e52f622 100644 GIT binary patch literal 7200 zcmc&&Ux-vy82@J1RWV4TAPb8tSZD~{bN|epD^YD~F8q?~xIc5abQ$-r z#FKHU8_%6MAKsaqe;wnAW7@lZ^nT{i?kT~|RO7Bu;?HhIpOfFO*Yf53#aZKqrigE* zPVEd5Gxiv~Wf&OE zN$Sh_e8;x6-m2DX*5+3$wbq2Zq3zuB#|}sPBj#sDuV@aBYtZfKX#CN2XRlCCBcJcd ztI^lYH}8M94r{wse)rYY((tb0&^E^lY{&7Pg0fvl)*f5_4e`ynamhc^>Ccm^Kh^TC zAD`ie@-9xUzSKGHlM^2&_*)@SApLatvr`;r^rF7Q^)c(YYHhTBNHXNXwN>akFt|_0!w3PjeU!^k zIbjCzu(LW|v7W6~4oQ|gATJ69#|=G(MCfF|!}dm{Rvfl=RBEG@rl}MQUMH1rdyZ3Z z1B8R^N(MYc>&1j*%Y);qLf*B*07;?zEb3&uZjMy2T4Wdxj$c4x6r3>3E6IWftQYmB zwY6L;k5!ryub>N`7eVMLN99o;@?PH0ATI`M)p4uXEI0N`mOQwg3Y79)aAAAF0`stb z1$R<+zmMG|YLndL-QVbayb$R>A~LXQn!Ccj8#t_$k_^i(Daw#+6D7Xb;)#P_L0k!N z4)N3$H{M5bzP!v`8)t8ly;6~JsY^?$IM!qWSCcZT?hPa&T1CZf&D>((@^3Zb?~Ql6~3$1^jqM9O60+f4^Cho6-k&vRvwc< z%&)?=MPQVrA^Tz0LAZ8IBX5umc((%*D6t7gQ`RP2?~?;S%v}da`>ScLpHw6p+R#6F zuuQgj&Wlftj-j{Ebpthv`T-i??n097Te&~t+SSf8P7K8{jK3G73f1Z*wIv-o z+z#6jlQT(;6++bm1sIK=uLGBaFbf%WxhJ6HZ=D)Hp2{_YV6O$2R1p-DxTo}(rVf%b(l<}J2OUCrWdsg9Eje#&@|LUDZ%v6wGdf9u*yh; znSFnvhx!4{WWMO~lP)^wNtOzlN?&#wH&6i92_vev##!*B4PUy52>2exajjYk!*Z<7 zx>4ejshqVJ7Ie>?fjWR5iZF$Xz>*)q(W7{9t-UJsykc`9=6c3}XUH1g^>OKVTbDy9 zaT=X@{ZX<$rnR~;pZ87y_Xl*{dhb2vFf))Vqo)_7B(1mOy;`>#g_u}82?L&v&Cn^9 zZkgMQN_UGY1;iyoK>N89@tKrSHWp{f{6%5Oukh;q20uFMl-0S3dwoV6>I*E9`kbtk zTw%DzFnqY^J2*y_5=YKw!Gt2C3 zq6bkyFk)i7c+n^u$VtJAU=H!%E#%-q5QJPrQ3wiNL=tt)`hC@1o9WC>7;%!Wrn;)T z|N0-_|EQYTJ-(+j{M_Wey{jU3Nz{fHnwC|t9NV$Q8a#A*ITL@tuzdNOkNEuRwr|h< z`I^Y%6Qh?tKY1m$|MJ!|n(i0tG^x3yosXd(HFP9GGyKhHzW-zoj0^a8leguq=RY>` z^cX)I`m3;q&FE*|3-lxXDq2L5(}U4ZBzm^TmOdn%S${3N=@9KT>!YK~Iivk!V)3i5M^@rbQfkau&sOWRjpLFc z4z8_2*C7^4c|kt*$4;Z<9l&9DM#sZwb+OfGz9NbIH2%H)@!%JHAKeK(Cy-Qd*wv`j z%Jo_6>2g!j!$G;O=PTPsxeS#PrVtNteb`e$R-}l7;};4Ar{IKPUP&4_ATJtCYrI@9 z&sCa|R$ize^pvCWp6}$nyq`im?5)-+)-%=0aY+*g)JcSc8v=*W3!M~j7_L`qRNT99#u)CBPWstt~EBpmDu?#?v)dkI0Ksk(xB5B~{$(vWVG|%<88_ zjPszd+AeM!3KGcKmON!Zvz)>Yip>}w0MqZ#A#LEqnx;9N5VObdcn)7KQ1}YX*+dl{ zOBmpSDMh$oA7D;HR4g!06SktiiLM*hKblzY!)#w)9BDkk2+Yd)c%ksfdN1_-0ppiY z==u#rw}1qKnV6xk%TEklr@6+jLd^$ z<_ehb*OYFZeo~QaXhZ+xfiltNm=~WKy^YRL(+$w%{s7YePoE~yUeEmz)~RB5y)6N@mh2IF=Cw7Pam118hx_KeY$=_MnS z-1`@r2AU`(m>#+oBI~o?L(pNJQh4|sJ;aMs$sFq~I_OE33Ytn^wi~yh0Iu(&>(*c6 zEO^p}FI_|gd=KNeS0!B*$=$&JL0AR2dFTo=kq=nT#ye_8L$o~X?;LOIel{$Iqtkv%rr92@Q)12im>B)F|<6FZ#o(i^&6>o7R< zSdl>4w?YG6Z2iM%o$UM17tJE(7YJ^?i|p`X!YNp!89q1vJ;iBELY?{e0IRy`f;JM6vX4+v1p Eza4RxFaQ7m diff --git a/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout b/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout index 9deac32edb492ea4d405a1bceca49df4954e0511..a7879584a9601f005f1c5aeba8d04f3320c8c66c 100644 GIT binary patch literal 6901 zcmc&&U2IfE6h7PSpAdc&H5!R7k(g=>xxah&qERbiEh%i%+CYN}h26lGcDJ^>k?^32 zL?Z^GQ9<+teK5Xgf>G2&A9ye^A;cIHCHSJe7=L0!eL@iYzS%o_?=A~&Y3a^pX71cO z^PO|PIcI)$_1eL{?&0*%qZ=Q0TBV%2OWP8rk+2NQlnY3F`!>FxeMZDc$1*2kVSDrF zzFxMwkePx?)lr;R7FLfx*dp?s?u>CSy5;ZTtKq{0dEm?{B~O7z3a!uS{$onM(edS1 zQ9O~}!)$B3{*U(bQ%~Iw;)V9;?~DH~%h7G!Uu0O}e9%+YPxGPi`**)^>L1|fq{r8` zHJ-Ld+ioOb}GAW`t1Ev{e43{z3VK~cMRKfZQHXPNA@iGkoa9eJ#pMU z66OD`Wp5~XKkp6sp}eD|Wyhoa4(>lt#ouBnd*Rn74!y^IS}*FGp2+5V`Vs@#d?q`Y zSf9&h3Qx(L^I#jE>6>2CNqLsJF;Wh zVj-VMmx^P#e0EZru|AlV;o7F$qbq*(WmZ1RgH1^)E8_{YpB=R@+$=56LFU%D5DyC^?jQnZi>^GO9I& zdIx$W>i#V8#SoN0Yuhank7HXcApbH`WD}?^eh!e^7emecW#stxGeBO?5j}xJ&w_PllvNdSxA;sW!n)z?*C0DE3ZYawh`6|AlJDC_P4%n5|};u91pmM+&ghT`F|2K=um zBbcJC$~*a-gO_Gyvc@mzGi1z0NvW8VKqASIQAGxbyA5XCf)}4xn{h{#87@GQV8>UW zu7Y(mGZ-8@h(e{=H6jc&8!~-_fTk^+QA)f|xp)osRIyJ1-zE_51rWId2#8gY=UFfjvvwkBKfM9|0A1kNXr-tVXpMi10Z(uw6GvBj zm!&+*MQN(h2F7u`kCx5xLl{!w5Z=}LDPC^C%QY3Jt>axDW|!_tr5F*mQjRovoNIV! zY!dZ7#JE@~dI%z4VNgL=;n*ClXpX%K9p1(GuE1A1mjLiLyl4%TVkBVQXhB~j1{ftP zT}Ne5O-Tt8F@jYz3-Z(O+)+GjMSDHIW-vinJeMbE6INSJ;-yCPs`Ypx7+=6N1``OG zZMQ>iiApfh+S!Yx&5%sab5LlGwBKv4-# z*@$tiF9G$7h^RVKp%%5-w3)6-zoL&Y^qs(`LKDeyW5)Hv0~na&YPPvrg)`T};Mp88 zF7^kA<;xm}TG>#PQ`DFeQ_W%fBH(?ZP*Geh2jPON)+&(Iz7TdyL?z~BwXBtgWrM7k zMsWOJ-^+zX>@Vo>O;m?_8)9)l1sOw(D`wSn-4C=i8WC>a@){ZtgH#p&%d55!N3AqG zYj7_zRSQchXo|0Zio6D2;<5Gg%@2d@hDUTz~}%GoLe z0gETJ*!%!Is8r1G9}S#Yq?0w*3kDQ79@f>{4UZw*w+-b?T%&Q`K{Pt$C?wJ9D2sv7 z)P~0NkFa$PZNPaMxpG{lhDfd00c4jtL&X{o{>$yV3U-$&!-8#+#Z0m~NfwemM_&6J z2t0rn)3>$GF%md?k!x*@@5jpxp{+AmeE_5qH}q&4K%<_W`c%8{2iSQAou+SRxMfwY zCBUgSr?GK3;K|U=#uoHT?pA?)v6I1rt~TSLo~`<()cz;F^KdZ}TPqhO;MAK_+8RF= z+B)+&jUR)kNK%1c&rW@B>v$S=<}qSsb_Ulr;2cG+^<8eKQ9I{&-+@LsQ)VT@;>*vJ_?`1A*(1~gG^h#inuQ_5x^lHwW&8BsF4XWJT0_!-t Y4c;%&vwCCXjrZX^v&L2S3#q1|L}Cc7woP`n~y zQP8T0ulCtDUwrVvrxFl^A{E3pL46Q?6Kmr4otfE7I*FU?W(uBgX3osc`Tqa^{>wQh zC#M&t#?QXbn-?-hHe+apCY$?cL`k6cjk6Eg|EDP1R;d)K#mtGq z+P?hJFDG+Ti}}eJLw7CB)NRvr49kjBk$?u7t~E-vYG%P}tj8(7MW4@unRT*;k<%?b zn{(|r6$yD5ua+vA{92)YF;3|%8a90%Y&Yw;hHLAlW#nR2B;;YX?p5@+D@DS(c+<0X_gBOub7!Vzv3-7VswQn5(R?1cYKe*7N7n>PjV2pn|vDj8<(f#tawt9nlz+@YgN`U zYD!T(t>eCmFEWvThPa{$u0R`lT_lyl_NRvaOTWlEP;LBKKpwseYF_b?Q$O^NtceA! zZ6J@_1LVW#=b`&Pkquxul9Md{$c804kPp8AeZhMAKA?ZPKb>{p>A-Wqg$8s}93UT> zgezZzz8?emC3NgJM_$JB)tlUTrf=ecmUOswzy=>kTDZiN`+4Xi6lc-6d5pK0xG93+&GxOos!kh)xi{$(WY z1x3%8jN!K#P*wz0{HBKA>PYt*h+G8%a#iFl^fzQw?vHXL?PoL~9-s>X8&5gv1X@$q zG4pvsuyJ;GbQvnLY+Q9UTf;ogckyI${vxKdI7D=%-tpr)ajX@z5z*zqy9`$<#f&hO za-_+juMwe%QQS`v<5r~@A;^4%K?QAvV{*2l8L}n$8Rowd#LDmy0M_y1$F@?;1k{b> z2e_lWBEcwG>AE5d$|X%WqJS#uf&5uS?g~cBcs`9^i*S&KvG1U>sJ3+CPBSJ|J+24y zYj9)WK*$_oE;gwI8?7B&F15punMAI1NE}5;Nc^hA;S!XD)K!eX=q94K=o|+P4VY8{ zMNN#n4&&1A0ri^>Q4y|CMQxBaGgKK@j1i{36~@%JP~<_FxJj0KGj0wMz{IR5Z?jsp zJ(pzioI_U)JSKie=gZ3!(hjJxp0b>x%1TT(hr@RQ@k?LG!378luBufatJ_H=t12gD zTAr3AIlhPF_^)qwON+#x;PSgps~_))#d(!vOfgo>E_Xc%v}Z#^xGVV~9v}v-EB_zv zT0$&UX}H(mTBNHdlvL1^It~@jsQI`YROWIAMahifp~w6n^JP-vGd+=#4Ln`u)yHXdclO^!oz#_zJc2iuG^XlCe~=|caV*i zpM?YtkTJF0hA`aw7B*tj2AucNTia!7h?eGV`jXm1C3;W(-PTn}^@3uy4BZ2cS`gU7WSMYMFZEGLZ2SBPVg@fQek9(Az;jZ?`Pq6bZ ze6)8v+e=pKSOT0VpC&2@z#DBldn@QWu2z9*i5tNnyq&`!%GU6tH2epC{|z7YV{7Z6 z1e_?J($>_qwypj9G<6N4I+{xSC_BS*8&4e1~%wzTLyA3tzJxguSgjV28c^SJnP%Rd4cl+@_PNe*rXS By>S2l From 0f347c11bff9b1978a77c6f10a860f5e314d6ad7 Mon Sep 17 00:00:00 2001 From: SJ Date: Wed, 11 Aug 2021 16:08:21 -0700 Subject: [PATCH 251/251] Add header file needed for no unity builds (#3047) Signed-off-by: amzn-sj --- .../Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp | 1 + 1 file changed, 1 insertion(+) 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 148b1cbdfe..4099443913 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include

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: