From 5d6ab2699cfda84a77134475930652e1fc649d33 Mon Sep 17 00:00:00 2001 From: igarri Date: Wed, 16 Jun 2021 11:48:59 +0100 Subject: [PATCH 001/103] First Performance pass Signed-off-by: igarri --- .../AssetBrowser/AssetBrowserFilterModel.cpp | 3 +- .../AssetBrowser/AssetBrowserModel.cpp | 3 +- .../AssetBrowser/AssetBrowserTableModel.cpp | 56 +++++++++++++++---- .../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, 96 insertions(+), 27 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(); + 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; + 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/103] 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/103] 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/103] 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/103] 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/103] 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/103] 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/103] 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/103] 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 d08cbd2c339a40425c1376ba22f078196ac3b5df Mon Sep 17 00:00:00 2001 From: evanchia Date: Thu, 22 Jul 2021 13:55:55 -0700 Subject: [PATCH 010/103] 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 011/103] 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 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 012/103] 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 013/103] 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 8eb92057115ea2fd87354fc230f885ffc3d28927 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Mon, 2 Aug 2021 00:34:43 -0500 Subject: [PATCH 014/103] 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 015/103] 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 58ff2d8cab609637c16d2988451e0e494971444a Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Mon, 2 Aug 2021 14:59:45 -0500 Subject: [PATCH 016/103] 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 | 43 ++++------- .../Window/ShaderManagementConsoleWindow.h | 5 -- 9 files changed, 206 insertions(+), 121 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_actionPythonTerminal = m_menuView->addAction("Python &Terminal", [this]() { - m_pythonTerminalDockWidget->setVisible(!m_pythonTerminalDockWidget->isVisible()); - if (m_pythonTerminalDockWidget->isVisible()) + m_actionAssetBrowser = m_menuView->addAction( + "&Asset Browser", + [this]() { - // reposition console window on the bottom, otherwise it gets docked in some weird spot... - addDockWidget(Qt::BottomDockWidgetArea, m_pythonTerminalDockWidget); - } + const AZStd::string label = "Asset Browser"; + SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); + }); + + m_actionPythonTerminal = m_menuView->addAction( + "Python &Terminal", + [this]() + { + 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 63ed78d2679e9eaec353a2d3af0a40f0fb22a0c6 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Mon, 2 Aug 2021 17:27:26 -0500 Subject: [PATCH 017/103] 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 2ed07c2a6ad3937cd53f97cce159111cfd87a961 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Mon, 2 Aug 2021 23:09:28 -0500 Subject: [PATCH 018/103] 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 65704110ad283e031f3ee9bae1d74b340f5e3f80 Mon Sep 17 00:00:00 2001 From: evanchia Date: Tue, 3 Aug 2021 10:28:45 -0700 Subject: [PATCH 019/103] 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 4eacd076da89f7552eae93b47b8534d5538f4026 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Tue, 3 Aug 2021 15:53:20 -0500 Subject: [PATCH 020/103] 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 021/103] 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,6 +76,12 @@ 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); @@ -84,23 +89,6 @@ namespace ShaderManagementConsole outModules.push_back(aznew ShaderManagementConsoleWindowModule); } - void ShaderManagementConsoleApplication::OnShaderManagementConsoleWindowClosing() - { - ExitMainLoop(); - ShaderManagementConsoleWindowNotificationBus::Handler::BusDisconnect(); - AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); - } - - void ShaderManagementConsoleApplication::Destroy() - { - // before modules are unloaded, destroy UI to free up any assets it cached - ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Broadcast(&ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Handler::DestroyShaderManagementConsoleWindow); - - ShaderManagementConsoleWindowNotificationBus::Handler::BusDisconnect(); - - Base::Destroy(); - } - AZStd::vector ShaderManagementConsoleApplication::GetCriticalAssetFilters() const { return AZStd::vector({ "passes/", "config/" }); @@ -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 022/103] 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 73fee0c57e4206f5b2194b768fcc5d51a5628c72 Mon Sep 17 00:00:00 2001 From: Yuriy Toporovskyy Date: Wed, 4 Aug 2021 10:39:57 -0400 Subject: [PATCH 023/103] 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 | 115 +- Code/Editor/CryEditDoc.cpp | 2 + Code/Editor/EditorViewportWidget.cpp | 917 ++-- Code/Editor/EditorViewportWidget.h | 605 +-- 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 | 19 +- .../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 | 114 +- .../CrySystem/ViewSystem/ViewSystem.cpp | 35 +- .../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 | 91 +- .../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; + (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 + //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,64 +1632,64 @@ 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())) + Yes, No, YesButViewsOutOfSync + }; + + const ShouldUpdateObject shouldUpdateObject = [&]() { + if (!cameraObject) { - return; + return ShouldUpdateObject::No; } + if (m_viewSourceType == ViewSourceType::CameraComponent) + { + if (!m_viewEntityId.IsValid()) + { + // 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 + { + 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; + } + }(); + + if (shouldUpdateObject == ShouldUpdateObject::Yes) + { AZ::Matrix3x3 lookThroughEntityCorrection = AZ::Matrix3x3::CreateIdentity(); if (m_viewEntityId.IsValid()) { @@ -1924,89 +1698,77 @@ void EditorViewportWidget::SetViewTM(const Matrix34& viewTM, bool bMoveOnly) &LmbrCentral::EditorCameraCorrectionRequests::GetInverseTransformCorrection); } - if (m_pressedKeyState != KeyPressedState::PressedInPreviousFrame) + int flags = 0; { - AzToolsFramework::ScopedUndoBatch undo("Move Camera"); + // 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) + { + flags = eObjectUpdateFlags_UserInput; + undo.emplace("Move Camera"); + } + if (bMoveOnly) { - // specify eObjectUpdateFlags_UserInput so that an undo command gets logged - cameraObject->SetWorldPos(camMatrix.GetTranslation(), eObjectUpdateFlags_UserInput); + cameraObject->SetWorldPos(camMatrix.GetTranslation(), flags); } 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)); + cameraObject->SetWorldTM(camMatrix * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection), flags); } } } - else if (m_viewEntityId.IsValid()) + else if (shouldUpdateObject == ShouldUpdateObject::YesButViewsOutOfSync) { - // Ignore camera movement if locked. - if (IsCameraMovementLocked() || (!GetIEditor()->GetAnimation()->IsRecordMode() && !IsCameraObjectMove())) - { - return; - } - - if (m_pressedKeyState != KeyPressedState::PressedInPreviousFrame) - { - AzToolsFramework::ScopedUndoBatch 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)); - } - - AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequests::AddDirtyEntity, m_viewEntityId); - } - 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); + // 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; } +} - QtViewport::SetViewTM(camMatrix); +const Matrix34& EditorViewportWidget::GetViewTM() const +{ + // `m_viewTmStorage' is only required because we must return a reference + m_viewTmStorage = AZTransformToLYTransform(GetCurrentAtomView()->GetCameraTransform()); + return m_viewTmStorage; +}; - m_Camera.SetMatrix(camMatrix); +AZ::EntityId EditorViewportWidget::GetCurrentViewEntityId() +{ + // Sanity check that this camera entity ID is actually the camera entity which owns the current active render view + if (m_viewSourceType == ViewSourceType::CameraComponent) + { + // Check that the current view is the same view as the view entity view + AZ::RPI::ViewPtr viewEntityView; + AZ::RPI::ViewProviderBus::EventResult( + viewEntityView, m_viewEntityId, + &AZ::RPI::ViewProviderBus::Events::GetView + ); + + const bool isViewEntityCorrect = viewEntityView == GetCurrentAtomView(); + AZ_Error("EditorViewportWidget", isViewEntityCorrect, + "GetCurrentViewEntityId called while the current view is being changed. " + "You may get inconsistent results if you make use of the returned entity ID. " + "This is an internal error, please report it as a bug." + ); + } + + return m_viewEntityId; } ////////////////////////////////////////////////////////////////////////// @@ -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) - { - 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_viewEntityId.IsValid()) { - float fov = AZ::RadToDeg(m_camFOV); - Camera::CameraRequestBus::EventResult(fov, m_viewEntityId, &Camera::CameraComponentRequests::GetFov); - return AZ::DegToRad(fov); + float fov = 0.f; // AZ::RadToDeg(m_camFOV); + Camera::CameraRequestBus::EventResult(fov, m_viewEntityId, &Camera::CameraComponentRequests::GetFovRadians); + return fov; + } + else + { + return AZ::GetPerspectiveMatrixFOV(m_defaultView->GetViewToClipMatrix()); + } +} + +void EditorViewportWidget::OnActiveViewChanged(const AZ::EntityId& viewEntityId) +{ + // Avoid re-entry + if (m_sendingOnActiveChanged) + { + return; } - return m_camFOV; -} + // Ignore any changes in simulation mode + if (m_playInEditorState != PlayInEditorState::Editor) + { + return; + } -////////////////////////////////////////////////////////////////////////// -bool EditorViewportWidget::CreateRenderContext() -{ - return true; -} + // 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." + ); -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::DestroyRenderContext() -{ + 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())); + + 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); + + // 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(); } ////////////////////////////////////////////////////////////////////////// -bool EditorViewportWidget::IsDefaultCamera() const +AZ::RPI::ViewPtr EditorViewportWidget::GetCurrentAtomView() const { - return m_viewSourceType == ViewSourceType::None; -} - -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::SetSequenceCamera() -{ - 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); }; + static EditorViewportWidget* GetPrimaryViewport(); - virtual ~EditorViewportWidget(); + // Used by ViewPan in some circumstances + void ConnectViewportInteractionRequestBus(); + void DisconnectViewportInteractionRequestBus(); - Q_INVOKABLE void InjectFakeMouseMove(int deltaX, int deltaY, Qt::MouseButtons buttons); + // 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; - // 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; +private: + //////////////////////////////////////////////////////////////////////// + // Private types ... -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) + 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,193 +221,41 @@ 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; - - //------------------------------------------- - //--- 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; - 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 EditorViewportWidget* m_pPrimaryViewport; - - QRect m_safeFrame; - QRect m_safeAction; - QRect m_safeTitle; - - CPredefinedAspectRatios m_predefinedAspectRatios; - - 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(); @@ -547,48 +263,131 @@ private: 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(); + 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(); + + AzFramework::CameraState GetCameraState(); + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); + + QPoint WidgetToViewport(const QPoint& point) const; + QPoint ViewportToWidget(const QPoint& point) const; + QSize WidgetToViewport(const QSize& size) const; + + const DisplayContext& GetDisplayContext() const { return m_displayContext; } + CBaseObject* GetCameraObject() const; + + 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; + + AZ::RPI::ViewPtr GetCurrentAtomView() const; + + //////////////////////////////////////////////////////////////////////// + // Members ... + friend class AZ::ViewportHelpers::EditorEntityNotifications; + + AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING + + // Singleton for the primary viewport + static EditorViewportWidget* m_pPrimaryViewport; + + // 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; + + // The entity ID of the current camera for this viewport, or invalid if the default editor camera + AZ::EntityId m_viewEntityId; + + // Determines also if the current camera for this viewport is default editor camera + 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; + + // Determines if the viewport needs updating (false when out of focus for example) + bool m_bUpdateViewport = false; + + // 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; + + // 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; + + // 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; + (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); + //float x = 0.5f * width + 0.5f * camWidth * unitPos.x; + //float y = 0.5f * height * (1.f - unitPos.y); - return Vec2(x, 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; - } + (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(); + //if (m_azEntity) + //{ + // m_viewParams.SaveLast(); - CCamera* pSysCam = &m_pSystem->GetViewCamera(); + // CCamera* pSysCam = &m_pSystem->GetViewCamera(); - //process screen shaking - ProcessShaking(frameTime); + // //process screen shaking + // ProcessShaking(frameTime); - //FIXME:to let the updateView implementation use the correct shakeVector - m_viewParams.currentShakeShift = m_viewParams.rotation * m_viewParams.currentShakeShift; + // //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()); - } - } + // 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); + // ApplyFrameAdditiveAngles(m_viewParams.rotation); - const float fNearZ = gEnv->pSystem->GetIViewSystem()->GetDefaultZNear(); + // 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; + // //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()); + // 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; + // //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); + // // 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. + // // [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); + // 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); + // 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); - } + // 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()); + AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CViewSystem::UpdateSoundListeners)"); - // 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()); + //assert(gEnv->IsEditor() && !gEnv->IsEditorGameMode()); - 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()); - } - } + //// 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; - } + //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(); - } + //// 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); + 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); - } + //// 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 024/103] 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 025/103] 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 026/103] 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 027/103] 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 028/103] 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 029/103] 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 030/103] 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 031/103] 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 032/103] 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 033/103] 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 034/103] Re-use existing code Signed-off-by: Yuriy Toporovskyy --- .../Code/Source/CameraSystemComponent.cpp | 30 +++++-------------- 1 file changed, 7 insertions(+), 23 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); + AzFramework::CameraState cam; + AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(cam, view->GetViewToClipMatrix()); - // 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); + 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 035/103] 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 036/103] 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 037/103] 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 038/103] 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 039/103] 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 040/103] 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 041/103] 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 042/103] 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 b521113fe1f51416a35ee28226e9cc2b521c1743 Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 15:10:13 -0500 Subject: [PATCH 043/103] 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 044/103] 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 e50723625729df1ebc4608d22129feb105c4ecdc Mon Sep 17 00:00:00 2001 From: Dayo Lawal Date: Thu, 5 Aug 2021 17:59:00 -0500 Subject: [PATCH 045/103] 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 046/103] 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 047/103] 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 048/103] 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 049/103] 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 050/103] 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 051/103] removed unused headers and forwards Signed-off-by: Guthrie Adams --- .../Code/Source/MaterialEditorApplication.cpp | 2 +- .../Source/Window/MaterialEditorWindow.cpp | 30 ++++++------------- .../Code/Source/Window/MaterialEditorWindow.h | 7 +---- .../Window/ShaderManagementConsoleWindow.cpp | 29 ++++++++---------- .../Window/ShaderManagementConsoleWindow.h | 10 ++----- 5 files changed, 25 insertions(+), 53 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 #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 1c181af94e0c3dc637efca8822cb9dbb5f22b11d Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 5 Aug 2021 22:36:43 -0500 Subject: [PATCH 052/103] 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 f2c482b03dc672c20d59f3b77524e1c107263d92 Mon Sep 17 00:00:00 2001 From: Nemerle Date: Fri, 6 Aug 2021 13:02:23 +0200 Subject: [PATCH 053/103] 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 054/103] 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 d7c1185dc23d42e7a535c5977aa1ee568d5f28ab Mon Sep 17 00:00:00 2001 From: John Date: Fri, 6 Aug 2021 20:09:53 +0100 Subject: [PATCH 055/103] Add previously approved changes. Signed-off-by: John --- .../Code/Source/TestImpactConsoleMain.cpp | 89 ++-- ...tImpactConsoleTestSequenceEventHandler.cpp | 145 +++---- ...estImpactConsoleTestSequenceEventHandler.h | 61 +-- .../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 | 409 +++++++++++++----- .../Code/Source/TestImpactRuntimeUtils.cpp | 12 +- .../Code/Source/TestImpactRuntimeUtils.h | 76 ++-- .../testimpactframework_runtime_files.cmake | 5 +- 17 files changed, 1287 insertions(+), 599 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"; } - // SafeTestSequenceCompleteCallback - void TestSequenceEventHandler::operator()( - Client::SequenceFailure&& selectedFailureReport, - Client::SequenceFailure&& discardedFailureReport, - AZStd::chrono::milliseconds selectedDuration, - AZStd::chrono::milliseconds discaredDuration) + void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& 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); + 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 SafeImpactAnalysisTestSequenceCompleteCallback(const Client::SafeImpactAnalysisSequenceReport& sequenceReport) { - m_numTestsComplete++; - const auto progress = AZStd::string::format("(%03u/%03u)", m_numTestsComplete, m_numTests, test.GetTargetName().c_str()); + std::cout << "Selected test run:\n"; + Output::FailureReport(sequenceReport.GetSelectedTestRunReport()); + + std::cout << "Discarded test run:\n"; + 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"; + } + + void TestRunCompleteCallback(const Client::TestRun& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns) + { + 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); + //! Handler for TestSequenceStartCallback event. + void TestSequenceStartCallback(SuiteType suiteType, const Client::TestRunSelection& selectedTests); - //! TestSequenceStartCallback. - void operator()(Client::TestRunSelection&& selectedTests); + //! Handler for TestSequenceStartCallback event. + void ImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const AZStd::vector& discardedTests, + const AZStd::vector& draftedTests); - //! ImpactAnalysisTestSequenceStartCallback. - void operator()( - Client::TestRunSelection&& selectedTests, - AZStd::vector&& discardedTests, - AZStd::vector&& draftedTests); + //! Handler for SafeImpactAnalysisTestSequenceStartCallback event. + void SafeImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const Client::TestRunSelection& discardedTests, + const AZStd::vector& draftedTests); - //! SafeImpactAnalysisTestSequenceStartCallback. - void operator()( - Client::TestRunSelection&& selectedTests, - Client::TestRunSelection&& discardedTests, - AZStd::vector&& draftedTests); + //! Handler for TestSequenceCompleteCallback event. + void TestSequenceCompleteCallback(const Client::SequenceReport& sequenceReport); - //! TestSequenceCompleteCallback. - void operator()( - Client::SequenceFailure&& failureReport, - AZStd::chrono::milliseconds duration); + //! Handler for ImpactAnalysisTestSequenceCompleteCallback event. + void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& sequenceReport); - //! SafeTestSequenceCompleteCallback. - void operator()( - Client::SequenceFailure&& selectedFailureReport, - Client::SequenceFailure&& discardedFailureReport, - AZStd::chrono::milliseconds selectedDuration, - AZStd::chrono::milliseconds discaredDuration); + //! Handler for SafeImpactAnalysisTestSequenceCompleteCallback event. + void SafeImpactAnalysisTestSequenceCompleteCallback(const Client::SafeImpactAnalysisSequenceReport& sequenceReport); - //! TestRunCompleteCallback. - void operator()(Client::TestRun&& test); - - private: - void ClearState(); - - SuiteType m_suiteFilter; - size_t m_numTests = 0; - size_t m_numTestsComplete = 0; - }; + //! 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()) + // Functor for running instrumented test targets + const auto instrumentedTestRun = + [this, &testTargetTimeout]( + const AZStd::vector& testsTargets, + TestRunCompleteCallbackHandler& testRunCompleteHandler, + AZStd::optional globalTimeout) { - (*testSequenceStartCallback)( - Client::TestRunSelection(ExtractTestTargetNames(includedSelectedTestTargets), ExtractTestTargetNames(excludedSelectedTestTargets)), - ExtractTestTargetNames(discardedTestTargets), - ExtractTestTargetNames(draftedTestTargets)); - } + return m_testEngine->InstrumentedRun( + testsTargets, + m_testShardingPolicy, + m_executionFailurePolicy, + m_integrationFailurePolicy, + m_testFailurePolicy, + m_targetOutputCapture, + testTargetTimeout, + globalTimeout, + AZStd::ref(testRunCompleteHandler)); + }; + + // Functor for running uninstrumented test targets + const auto regularTestRun = + [this, &testTargetTimeout]( + const AZStd::vector& testsTargets, + TestRunCompleteCallbackHandler& testRunCompleteHandler, + AZStd::optional globalTimeout) + { + return m_testEngine->RegularRun( + testsTargets, + m_testShardingPolicy, + m_executionFailurePolicy, + m_testFailurePolicy, + m_targetOutputCapture, + testTargetTimeout, + globalTimeout, + AZStd::ref(testRunCompleteHandler)); + }; if (dynamicDependencyMapPolicy == Policy::DynamicDependencyMap::Update) { - const auto [result, testJobs] = m_testEngine->InstrumentedRun( - testTargetsToRun, - m_testShardingPolicy, - m_executionFailurePolicy, - Policy::IntegrityFailure::Continue, - m_testFailurePolicy, - m_targetOutputCapture, - testTargetTimeout, - globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); - - UpdateAndSerializeDynamicDependencyMap(testJobs); - - if (testSequenceEndCallback.has_value()) + AZStd::optional& jobs)>> updateCoverage = + [this](const AZStd::vector& jobs) { - (*testSequenceEndCallback)(GenerateSequenceFailureReport(testJobs), timer.Elapsed()); - } + UpdateAndSerializeDynamicDependencyMap(jobs); + }; - return result; + return ImpactAnalysisTestSequenceWrapper( + m_suiteFilter, + sequenceTimer, + instrumentedTestRun, + includedSelectedTestTargets, + excludedSelectedTestTargets, + discardedTestTargets, + draftedTestTargets, + globalTimeout, + testSequenceStartCallback, + testSequenceEndCallback, + testCompleteCallback, + updateCoverage); } else { - const auto [result, testJobs] = m_testEngine->RegularRun( - testTargetsToRun, - m_testShardingPolicy, - m_executionFailurePolicy, - m_testFailurePolicy, - m_targetOutputCapture, - testTargetTimeout, + return ImpactAnalysisTestSequenceWrapper( + m_suiteFilter, + sequenceTimer, + regularTestRun, + includedSelectedTestTargets, + excludedSelectedTestTargets, + discardedTestTargets, + draftedTestTargets, globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); - - if (testSequenceEndCallback.has_value()) - { - (*testSequenceEndCallback)(GenerateSequenceFailureReport(testJobs), timer.Elapsed()); - } - - return result; + 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(); - - if (testSequenceEndCallback.has_value()) + // Carry the remaining global sequence time over to the drafted test run + if (globalTimeout.has_value()) { - (*testSequenceEndCallback)( - GenerateSequenceFailureReport(selectedTestJobs), - GenerateSequenceFailureReport(discardedTestJobs), - selectedDuraton, - discardedDuraton); + const auto elapsed = selectedTestRunDuration + discardedTestRunDuration; + sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); } - UpdateAndSerializeDynamicDependencyMap(selectedTestJobs); - return { selectedResult, discardedResult }; + // 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)(sequenceReport); + } + + 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 056/103] 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 057/103] 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 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 058/103] 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 8884227fe6cdf0dd5235ac041e68247229d287cd Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:03:11 -0700 Subject: [PATCH 059/103] 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 | 109 +-- .../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, 1489 insertions(+), 3798 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; - } - - ~AnimGraphAnimFrame() - { - const uint32 numParams = mParameterValues.GetLength(); - for (uint32 i = 0; i < numParams; ++i) - { - delete mParameterValues[i]; - } - } + float mTimeValue = 0.0f; + uint32 mByteOffset = 0; + uint32 mNumBytes = 0; + AZStd::vector mObjectInfos{}; + AZStd::vector> mParameterValues{}; }; struct EMFX_API AnimGraphInstanceData { - AnimGraphInstance* mAnimGraphInstance; - uint32 mNumFrames; - uint32 mDataBufferSize; - uint8* mDataBuffer; - MCore::Array mFrames; + AnimGraphInstance* mAnimGraphInstance = nullptr; + uint32 mNumFrames = 0; + uint32 mDataBufferSize = 0; + uint8* mDataBuffer = nullptr; + AZStd::vector mFrames{}; - AnimGraphInstanceData() + AnimGraphInstanceData() = default; + AnimGraphInstanceData(const AnimGraphInstanceData&) = delete; + AnimGraphInstanceData(AnimGraphInstanceData&& rhs) { - mAnimGraphInstance = nullptr; - mNumFrames = 0; - mDataBufferSize = 0; - mDataBuffer = nullptr; + if (&rhs == this) + { + 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 = {}; + } + + AnimGraphInstanceData& operator=(const AnimGraphInstanceData&) = delete; + AnimGraphInstanceData& operator=(AnimGraphInstanceData&& rhs) + { + 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 060/103] 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 061/103] 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 062/103] 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 063/103] 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 064/103] 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 065/103] 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 066/103] 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 067/103] 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 068/103] 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 069/103] 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 070/103] 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) + const char* fileMode = [mode]() -> const char* { - 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) - { - 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 071/103] 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 072/103] 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 073/103] 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 074/103] 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 075/103] 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 076/103] 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 077/103] 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 078/103] [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 382ca192c8f729b8038ca4ccd40b89aa1c425e80 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 24 May 2021 12:04:10 -0700 Subject: [PATCH 079/103] 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 080/103] 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 081/103] 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 082/103] 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 083/103] 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) + const auto found = AZStd::find_if(begin(nodesToCopy), end(nodesToCopy), [node](const EMotionFX::AnimGraphNode* parent) { - if (node != nodesToCopy[j] && node->RecursiveIsParentNode(nodesToCopy[j])) - { - removeNode = true; - break; - } - } - - if (removeNode) - { - 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; + + // iterate through the deformers and update them + for (MeshDeformer* deformer : mDeformers) { - bool firstEnabled = true; - - // iterate through the deformers and update them - for (uint32 i = 0; i < numDeformers; ++i) + // 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 instance && AZStd::any_of(begin(mMotionInstances), end(mMotionInstances), [instance](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) - { - // 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 084/103] 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 | 209 +++++++--------- .../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, 1503 insertions(+), 2128 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) { - if (mEntries[i].mTexture == texture) - { - delete mEntries[i].mTexture; - mEntries.erase(AZStd::next(begin(mEntries), i)); - return; - } + return entry.mTexture == texture; + }); + + if (foundEntry != end(mEntries)) + { + 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; } - return false; + + if (removeFromMemory) + { + delete *foundConnection; + } + 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)); - - // update the scroll bars - UpdateScrollBars(); - - // done - return true; - } + if (foundDialog == end(mDialogs)) + { + return false; } - // not found - return false; + // 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); + + // update the scroll bars + UpdateScrollBars(); + + 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) { - if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) + return; + } + for (auto dialog = mDialogs.rbegin() + 1; dialog != mDialogs.rend(); ++dialog) + { + 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 085/103] 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 086/103] 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 087/103] 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 088/103] 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 089/103] 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 090/103] 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 091/103] 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 092/103] 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 093/103] 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 094/103] 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 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 095/103] 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 096/103] 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 097/103] 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 098/103] 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 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 099/103] [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 actual_buckets == expected_buckets + 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 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 100/103] 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 101/103] 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(pass_stats, entry) for entry in entries) + frame_time = sum(self._update_pass(gpu_pass_stats, entry) for entry in entries) + gpu_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 is_frame_time_file(file): + data = json.loads(file.read_text()) + frame_time = data['ClassData']['frameTime'] + cpu_frame_stats.update(frame_time) - if frame_stats['count'] < 1: - raise BenchmarkPathException(f'No frame timestamp logs were found in {benchmark_dir}') + if gpu_frame_stats.getCount() < 1: + raise BenchmarkPathException(f'No GPU frame timestamp logs were found in {benchmark_dir}') - return frame_stats, pass_stats + if cpu_frame_stats.getCount() < 1: + raise BenchmarkPathException(f'No CPU frame times were found in {benchmark_dir}') - def _generate_payloads(self, benchmark_metadata, frame_stats, pass_stats): + return gpu_frame_stats, gpu_pass_stats, cpu_frame_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(frame_time_avg), - 'max': ns_to_ms(frame_stats['maxTime']), - 'min': ns_to_ms(frame_stats['minTime']) + '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': 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 102/103] 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 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 103/103] 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